From ad4a6477b371d35e57945d382e9465be480d96f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:31:52 -0800 Subject: [PATCH 01/18] Color Wheel: Copy Color As copies the color as hex, hex with alpha, CSS or CMYK values Part of #978. The Color Wheel panel menu gets Copy Color As, with Hex, Hex with Alpha, CSS rgb(), CSS hsl(), CSS oklch() and CMYK Values. Each item puts the panel's color on the clipboard as plain text and shows what it copied in the status bar. The opacity that Show Opacity edits goes into Hex with Alpha (ff at 100 %) and, under 100 %, after a slash in the CSS forms. CSS oklch() is gray while the working RGB space is not sRGB. color.format {color, opacity?, notation} answers the text. Hex, the CSS forms and color.parse use the same working RGB numbers, so color.parse reads every form but CMYK back to the same color. CMYK Values converts through the color settings and is written as a new swatch is named (C=0 M=50 Y=100 K=0). --- crates/color/src/css.rs | 160 +++++++++++++++- crates/engine/src/cmd/colorcmds.rs | 34 ++++ crates/engine/src/cmd/paint.rs | 6 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/colormgmt.rs | 67 +++++++ crates/engine/tests/color_settings.rs | 36 ++++ crates/ui-egui/src/i18n/bg.tsv | 10 + crates/ui-egui/src/i18n/bs.tsv | 10 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 8 + crates/ui-egui/src/i18n/hi.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tests.rs | 21 +++ crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 50 ++++- .../src/panels/tests_color_wheel_copy.rs | 175 ++++++++++++++++++ docs/mcp.md | 17 ++ docs/target-app-parity.md | 2 +- 40 files changed, 843 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_copy.rs diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 6fa17e0df1..20fb11dd7a 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -6,7 +6,7 @@ //! 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 `#`. +//! color may leave out its `#`. [`format`] writes a color in these forms. use crate::oklab::{self, CHROMA_FULL}; @@ -83,6 +83,126 @@ fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } +/// The forms [`format`] writes a color in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Notation { + /// `#rrggbb`. + Hex, + /// `#rrggbbaa`, `ff` for a color without an alpha. + HexAlpha, + /// `rgb(51 102 153)`. + Rgb, + /// `hsl(210 50% 40%)`. + Hsl, + /// `oklch(49.93% 0.0987 250.43)`. + Oklch, +} + +/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation` +/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of +/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form +/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and +/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and +/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a +/// gray is 0. [`Notation::Hex`] leaves the alpha out. +pub fn format(rgb: [f32; 3], alpha: Option, notation: Notation) -> String { + // A NaN alpha reads as none. + let alpha = alpha.filter(|a| !a.is_nan()); + let bytes = rgb.map(byte); + let units = bytes.map(|v| f64::from(v) / 255.0); + let [r, g, b] = bytes; + match notation { + Notation::Hex => hex_of(rgb), + Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))), + Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)), + Notation::Hsl => { + let [h, s, l] = rgb_to_hsl(units); + format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha)) + } + Notation::Oklch => { + let lch = oklab::to_oklch(units.map(|v| v as f32)); + // The fewest places that read back to the same bytes, from two (four for chroma). + let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes); + let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch))); + let places = |base: i32| usize::try_from(base + p).unwrap_or(2); + let c = number(c, places(4)); + // A chroma that rounds to 0 is a gray, whose hue is 0. + let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) }; + format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha)) + } + } +} + +/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the +/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under +/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of +/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at +/// the rounded lightness and hue; the chroma is lowered a step at a time instead. +fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> { + let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra)); + let step = 10f64.powi(-(4 + extra)); + let mut c = rounded(c, 4 + extra); + for _ in 0..OKLCH_CHROMA_STEPS { + if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) { + return Some([l, c.max(0.0), h]); + } + c = rounded(c - step, 4 + extra); + } + None +} + +/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB. +const OKLCH_CHROMA_STEPS: usize = 50; + +/// `v` rounded to `places` decimal places. +fn rounded(v: f64, places: i32) -> f64 { + let f = 10f64.powi(places); + (v * f).round() / f +} + +/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing. +fn alpha_part(alpha: Option) -> String { + let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2); + if percent == "100" { String::new() } else { format!(" / {percent}%") } +} + +/// A hue in degrees to two places, 360 written as 0. +fn hue_text(h: f64) -> String { + hue_text_to(h, 2) +} + +/// A hue in degrees to `places` places, 360 written as 0. +fn hue_text_to(h: f64, places: usize) -> String { + let text = number(h, places); + if text == "360" { "0".to_string() } else { text } +} + +/// `v` to `places` decimal places, without trailing zeros or a sign on zero. +fn number(v: f64, places: usize) -> String { + let text = format!("{v:.places$}"); + let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() }; + if text == "-0" { "0".to_string() } else { text.to_string() } +} + +/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's +/// rgbToHsl (); the hue of a gray is 0. +fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] { + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let (d, l) = (max - min, (max + min) / 2.0); + if d == 0.0 { + return [0.0, 0.0, l]; + } + let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) }; + let h = if max == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if max == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + [h * 60.0, s, l] +} + /// 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); @@ -404,6 +524,26 @@ mod tests { assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00"); } + #[test] + fn format_writes_each_notation_with_the_alpha_where_it_belongs() { + let rgb = [0.2, 0.4, 0.6]; + let half = Some(0.5); + assert_eq!(format(rgb, half, Notation::Hex), "#336699"); + assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980"); + assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)"); + assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)"); + assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out"); + assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)"); + assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)"); + assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)"); + assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)"); + assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)"); + assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)"); + assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)"); + } + proptest! { #[test] fn random_text_never_panics(text in "\\PC{0,60}") { @@ -431,5 +571,23 @@ mod tests { 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}")); } + + #[test] + fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) { + let rgb = [r, g, b].map(|v| f32::from(v) / 255.0); + let alpha = f32::from(a) / 255.0; + for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] { + let text = format(rgb, Some(alpha), notation); + let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse")); + prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text); + let read = c.alpha.unwrap_or(1.0); + match notation { + Notation::Hex => prop_assert_eq!(c.alpha, None), + Notation::HexAlpha => prop_assert_eq!(byte(read), a), + // A percentage to two places, left out when it rounds to 100. + _ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read), + } + } + } } } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 071f2ed3f7..93dad8a9a2 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -145,9 +145,43 @@ pub fn specs() -> Vec { always, parse_color ), + cmd!( + query "color.format", + "Format Color", + [], + None, + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (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), each in the space-separated form with ` / opacity%` added when the opacity is under 100, hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + always, + format_color + ), ] } +fn format_color(_: &mut Session, p: &Value) -> Result { + const C: &str = "color.format"; + let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?; + let opacity = super::paint::opacity_param(p, C)?; + let notation = match text_param(p, "notation", C)? { + Some("hex") => Some(css::Notation::Hex), + Some("hexAlpha") => Some(css::Notation::HexAlpha), + Some("rgb") => Some(css::Notation::Rgb), + Some("hsl") => Some(css::Notation::Hsl), + Some("oklch") => Some(css::Notation::Oklch), + Some("cmyk") => None, + _ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")), + }; + let cms = vectorcraft_color::cms::active(); + let intent = cms.settings().intent; + let text = match notation { + None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)), + Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")), + // The working RGB numbers, as the Color panel's hex field and color.parse read them; for + // oklch() the working RGB space is sRGB. + Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n), + }; + Ok(json!({ "text": text })) +} + 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`"))?; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2a2cab339d..ae9dcda41e 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -522,9 +522,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result { apply_paint_opacity(s, p, paint, opacity, fill) } -/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None` -/// when it is left out or null. -fn opacity_param(p: &Value, cmd: &str) -> Result> { +/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as +/// 0..1; `None` when it is left out or null. +pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result> { match p.get("opacity") { None | Some(Value::Null) => Ok(None), Some(v) => match v.as_f64() { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index ff5734a4f6..0c55a60a49 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -140,6 +140,7 @@ pub(super) const ALLOWED: &[&str] = &[ "charStyle.setAttrs", "charStyle.unused", "color.convert", + "color.format", "color.gamutCheck", "color.harmony", "color.parse", diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 2c76f2b0b6..70b1aeb0b6 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -390,6 +390,73 @@ fn parse_err(s: &mut Session, p: Value) -> String { s.execute("color.parse", &p).unwrap_err().to_string() } +/// `color.format` writes each notation, with the opacity only where it belongs, and `color.parse` +/// reads every notation but CMYK back to the same color and opacity. +#[test] +fn format_writes_each_notation_and_parse_reads_it_back() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let s = &mut s; + let fmt = |s: &mut Session, color: Value, opacity: Value, notation: &str| { + let r = s.execute("color.format", &json!({ "color": color, "opacity": opacity, "notation": notation })).unwrap(); + r["text"].as_str().unwrap().to_string() + }; + let blue = json!("#336699"); + for (notation, at_half, at_full) in [ + ("hex", "#336699", "#336699"), + ("hexAlpha", "#33669980", "#336699ff"), + ("rgb", "rgb(51 102 153 / 50%)", "rgb(51 102 153)"), + ("hsl", "hsl(210 50% 40% / 50%)", "hsl(210 50% 40%)"), + ] { + assert_eq!(fmt(s, blue.clone(), json!(50), notation), at_half, "{notation}"); + assert_eq!(fmt(s, blue.clone(), Value::Null, notation), at_full, "{notation}"); + } + let oklch = fmt(s, blue.clone(), json!(25), "oklch"); + assert!(oklch.starts_with("oklch(") && oklch.ends_with(" / 25%)"), "{oklch}"); + // The working CMYK numbers through the color settings, as color.convert gives them. + let cmyk = s.execute("color.convert", &json!({ "color": "#336699", "to": "cmyk" })).unwrap(); + let pct: Vec = cmyk["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect(); + let expected = format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3]); + assert_eq!(expected, "C=87 M=61 Y=19 K=0", "the default color settings, as docs/mcp.md gives them"); + assert_eq!(fmt(s, blue.clone(), json!(50), "cmyk"), expected); + assert_eq!(fmt(s, json!({"c": 10, "m": 20, "y": 30, "k": 0}), Value::Null, "cmyk"), "C=10 M=20 Y=30 K=0", "a CMYK color keeps its values"); + assert_eq!(fmt(s, json!({"gray": 40}), Value::Null, "cmyk"), "C=0 M=0 Y=0 K=40"); + for color in [json!("#336699"), json!("#0a0b0c"), json!("#ff0000"), json!("#ffffff"), json!({"c": 100, "m": 0, "y": 0, "k": 0})] { + for (notation, opacity) in [("hex", Value::Null), ("hexAlpha", json!(40)), ("rgb", json!(12.5)), ("hsl", json!(99.99)), ("oklch", json!(0))] { + let text = fmt(s, color.clone(), opacity.clone(), notation); + let shown = fmt(s, color.clone(), Value::Null, "hex"); + let r = s.execute("color.parse", &json!({ "text": text })).unwrap(); + assert_eq!(r["hex"], json!(shown), "{color} {notation}: {text}"); + match notation { + "hex" => assert_eq!(r["opacity"], Value::Null, "{text}"), + "hexAlpha" => assert_eq!(r["opacity"], json!(40.0), "{text}"), + _ => assert_eq!(r["opacity"], opacity.as_f64().map_or(Value::Null, |o| json!(o)), "{text}"), + } + } + } +} + +/// `color.format` refuses a missing or wrong color, opacity or notation. +#[test] +fn format_refuses_bad_params() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let mut err = |p: Value| s.execute("color.format", &p).unwrap_err().to_string(); + let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk"; + assert!(err(json!({"color": "#336699"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "css"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "HEX"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": 1})).ends_with("`notation` must be a string")); + assert!(err(json!({"notation": "hex"})).ends_with("missing or invalid `color`")); + assert!(err(json!({"color": "#33669980", "notation": "hex"})).ends_with("missing or invalid `color`")); + for opacity in [json!(-1), json!(101), json!("50"), json!(true)] { + assert!( + err(json!({"color": "#336699", "opacity": opacity, "notation": "rgb"})).ends_with("`opacity` must be a number from 0 to 100"), + "{opacity}" + ); + } +} + #[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 81fc274743..6bd0a9d66f 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1048,3 +1048,39 @@ fn color_parse_takes_oklch_only_in_an_srgb_working_space() { 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"); } + +/// `color.format` writes `oklch()` only while the working RGB space is sRGB, and writes every CSS +/// form of a CMYK color from the RGB numbers the rendering intent gives, so `color.parse` reads each +/// back to the hex color `color.format` gives. +#[test] +fn color_format_writes_every_css_form_through_the_intent() { + let _g = settings(); + let old = cms::active_settings(); + let mut s = session(); + let format = |s: &mut Session, color: &serde_json::Value, notation: &str| { + s.execute("color.format", &json!({"color": color, "notation": notation})).map(|r| r["text"].as_str().unwrap_or_default().to_string()) + }; + s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let wide = format(&mut s, &json!("#336699"), "oklch").map_err(|e| e.to_string()); + // The Generic CMYK profile's file loaded as an ICC profile, which converts through the intent. + let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name; + s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap(); + let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0}); + let intents_differ = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8) + != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); + // Collected as results, so that a failure still restores the process-wide settings first. + let mut read_back = vec![]; + for notation in ["hex", "rgb", "hsl", "oklch"] { + let text = format(&mut s, &cyan, notation).map_err(|e| e.to_string()); + let hex = text.clone().and_then(|t| s.execute("color.parse", &json!({"text": t})).map(|r| r["hex"].clone()).map_err(|e| e.to_string())); + read_back.push((notation, text, hex)); + } + cms::set_active(&old).unwrap(); + cms::unregister_icc(&icc); + assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}"); + assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB"); + let hex = read_back[0].1.clone().unwrap(); + for (notation, text, back) in read_back { + assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}"); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8d6a2c626f..a263c2c503 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2360,6 +2360,14 @@ font-technology Variable Променливи Show Hex Field Показване на шестнадесетичното поле Hex or CSS color Шестнадесетичен или CSS цвят Parse Color Разчитане на цвят + Format Color Форматиране на цвят + Copy Color As Копиране на цвета като + Hex Hex + Hex with Alpha Hex с алфа + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Стойности CMYK Opacity & Mask Define Knockout Shape Непрозрачността и маската определят формата на изрязване Opacity Mask Маска за непрозрачност Opacity Mask Info Информация за маската за непрозрачност @@ -4354,6 +4362,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` трябва да бъде hex, hexAlpha, rgb, hsl, oklch или cmyk +@msg Copied the color as {text} Цветът е копиран като {text} @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` трябва да бъде масив diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0120f0ce67..a9ee0af99a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -466,6 +466,14 @@ Show Hex Field Prikaži hex polje Hex or CSS color Hex ili CSS boja Parse Color Raščlani boju + Format Color Formatiraj boju + Copy Color As Kopiraj boju kao + Hex Hex + Hex with Alpha Hex s alfom + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK vrijednosti Stroke Color Boja poteza Fill Gradient Gradijent ispune Stroke Gradient Gradijent poteza @@ -4771,6 +4779,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` mora biti hex, hexAlpha, rgb, hsl, oklch ili cmyk +@msg Copied the color as {text} Boja kopirana kao {text} @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 diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 630106a28c..2ccefb1300 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3006,6 +3006,14 @@ digits Malayalam Malaiàlam Show Hex Field Mostra el camp hex Hex or CSS color Color hex o CSS Parse Color Analitza el color + Format Color Formata el color + Copy Color As Copia el color com a + Hex Hex + Hex with Alpha Hex amb alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valors CMYK 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 @@ -5455,6 +5463,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` ha de ser hex, hexAlpha, rgb, hsl, oklch o cmyk +@msg Copied the color as {text} S’ha copiat el color com a {text} @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 diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f1203e3730..de1f1d8cc7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -479,6 +479,14 @@ Show Hex Field Zobrazit pole hex Hex or CSS color Barva hex nebo CSS Parse Color Analyzovat barvu + Format Color Formátovat barvu + Copy Color As Kopírovat barvu jako + Hex Hex + Hex with Alpha Hex s alfou + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Hodnoty CMYK Stroke Color Barva tahu Fill Gradient Přechod výplně Stroke Gradient Přechod tahu @@ -5030,6 +5038,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` musí být hex, hexAlpha, rgb, hsl, oklch nebo cmyk +@msg Copied the color as {text} Barva zkopírována jako {text} @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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9e005f7f9b..9d1bc87f96 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3111,6 +3111,14 @@ liquify-list-end {0}, {1} {0} og {1} Show Hex Field Vis hex-felt Hex or CSS color Hex- eller CSS-farve Parse Color Fortolk farve + Format Color Formatér farve + Copy Color As Kopiér farve som + Hex Hex + Hex with Alpha Hex med alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-værdier Stroke Color Stregfarve Fill Gradient Fyldgradient Stroke Gradient Streggradient @@ -8488,6 +8496,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` skal være hex, hexAlpha, rgb, hsl, oklch eller cmyk +@msg Copied the color as {text} Kopierede farven som {text} @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 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 82348d4849..47dbd96796 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2398,6 +2398,14 @@ file-filter Templates Vorlagen Show Hex Field Hex-Feld einblenden Hex or CSS color Hex- oder CSS-Farbe Parse Color Farbe auswerten + Format Color Farbe formatieren + Copy Color As Farbe kopieren als + Hex Hex + Hex with Alpha Hex mit Alpha + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-Werte Opacity & Mask Define Knockout Shape Deckkraft und Maske definieren Aussparungsform Opacity Mask Deckkraftmaske Opacity Mask Info Informationen zur Deckkraftmaske @@ -4633,6 +4641,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` muss hex, hexAlpha, rgb, hsl, oklch oder cmyk sein +@msg Copied the color as {text} Farbe kopiert als {text} @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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 40127f1383..4061465ffa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1978,6 +1978,14 @@ font-technology Variable Μεταβλητές Show Hex Field Εμφάνιση πεδίου Hex Hex or CSS color Χρώμα Hex ή CSS Parse Color Ανάλυση χρώματος + Format Color Μορφοποίηση χρώματος + Copy Color As Αντιγραφή χρώματος ως + Hex Hex + Hex with Alpha Hex με άλφα + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Τιμές CMYK Opacity Mask Μάσκα αδιαφάνειας Opacity: Αδιαφάνεια: Open Άνοιγμα @@ -6355,6 +6363,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk Το `notation` πρέπει να είναι hex, hexAlpha, rgb, hsl, oklch ή cmyk +@msg Copied the color as {text} Το χρώμα αντιγράφηκε ως {text} @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 επιλέξτε φάκελο προορισμού diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 0de22b4365..de84ca5e0a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2439,6 +2439,14 @@ font-technology Variable Variables Show Hex Field Mostrar campo hex Hex or CSS color Color hex o CSS Parse Color Analizar color + Format Color Formatear color + Copy Color As Copiar color como + Hex Hex + Hex with Alpha Hex con alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valores CMYK 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 @@ -4735,6 +4743,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` debe ser hex, hexAlpha, rgb, hsl, oklch o cmyk +@msg Copied the color as {text} Se copió el color como {text} @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 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2278d0a26f..63b03f2e54 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -476,6 +476,14 @@ Show Hex Field Näytä heksakenttä Hex or CSS color Heksa- tai CSS-väri Parse Color Jäsennä väri + Format Color Muotoile väri + Copy Color As Kopioi väri muodossa + Hex Heksa + Hex with Alpha Heksa ja alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-arvot Stroke Color Viivan väri Fill Gradient Täytön liukuväri Stroke Gradient Viivan liukuväri @@ -6365,6 +6373,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` on oltava hex, hexAlpha, rgb, hsl, oklch tai cmyk +@msg Copied the color as {text} Väri kopioitiin muodossa {text} @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 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 932b8ebe52..c57f6569aa 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2431,6 +2431,14 @@ font-technology Variable Variables Show Hex Field Afficher le champ hex Hex or CSS color Couleur hex ou CSS Parse Color Analyser la couleur + Format Color Mettre en forme la couleur + Copy Color As Copier la couleur en + Hex Hex + Hex with Alpha Hex avec alpha + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valeurs CMJN 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é @@ -4701,6 +4709,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` doit valoir hex, hexAlpha, rgb, hsl, oklch ou cmyk +@msg Copied the color as {text} Couleur copiée en {text} @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 diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 3b492b1cb0..46375e42c2 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2473,6 +2473,14 @@ Show Hex Field Hex ફીલ્ડ બતાવો Hex or CSS color Hex અથવા CSS રંગ Parse Color રંગ પાર્સ કરો + Format Color રંગ ફોર્મેટ કરો + Copy Color As રંગની આ રીતે નકલ કરો + Hex Hex + Hex with Alpha આલ્ફા સાથે Hex + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK મૂલ્યો 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 7186778d0e..6b5c2a0f22 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3280,6 +3280,14 @@ antiAlias Sharp शार्प Show Hex Field हेक्स फ़ील्ड दिखाएँ Hex or CSS color हेक्स या CSS रंग Parse Color रंग पार्स करें + Format Color रंग फ़ॉर्मेट करें + Copy Color As रंग इस रूप में कॉपी करें + Hex हेक्स + Hex with Alpha अल्फ़ा सहित हेक्स + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK मान Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप Opacity Mask ओपेसिटी मास्क Opacity Mask Info ओपेसिटी मास्क की जानकारी @@ -6356,6 +6364,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` hex, hexAlpha, rgb, hsl, oklch या cmyk होना चाहिए +@msg Copied the color as {text} रंग {text} के रूप में कॉपी किया गया @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" होना चाहिए। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1a8a386dbc..6cfd13644a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2918,6 +2918,14 @@ file-filter Templates Sablonok Show Hex Field Hex mező megjelenítése Hex or CSS color Hex vagy CSS szín Parse Color Szín értelmezése + Format Color Szín formázása + Copy Color As Szín másolása mint + Hex Hex + Hex with Alpha Hex alfával + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-értékek 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 @@ -5097,6 +5105,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk A `notation` értéke hex, hexAlpha, rgb, hsl, oklch vagy cmyk lehet +@msg Copied the color as {text} A szín másolva ebben a formában: {text} @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}` diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0f274ff3aa..8efb5b2972 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -434,6 +434,14 @@ Show Hex Field Tampilkan bidang hex Hex or CSS color Warna hex atau CSS Parse Color Urai warna + Format Color Format warna + Copy Color As Salin warna sebagai + Hex Hex + Hex with Alpha Hex dengan alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Nilai CMYK Stroke Color Warna stroke Fill Gradient Gradien isian Stroke Gradient Gradien stroke @@ -5755,6 +5763,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` harus hex, hexAlpha, rgb, hsl, oklch, atau cmyk +@msg Copied the color as {text} Warna disalin sebagai {text} @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 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f71698cec5..c10bb13ddc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2475,6 +2475,14 @@ file-filter Templates Modelli Show Hex Field Mostra campo hex Hex or CSS color Colore hex o CSS Parse Color Analizza colore + Format Color Formatta colore + Copy Color As Copia colore come + Hex Hex + Hex with Alpha Hex con alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valori CMYK 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à @@ -4763,6 +4771,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` deve essere hex, hexAlpha, rgb, hsl, oklch o cmyk +@msg Copied the color as {text} Colore copiato come {text} @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 diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 08c223a437..c3efd5b398 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -522,6 +522,14 @@ digits Malayalam マラヤーラム数字 Show Hex Field 16 進フィールドを表示 Hex or CSS color 16 進または CSS カラー Parse Color カラーを解析 + Format Color カラーを書式化 + Copy Color As 形式を指定してカラーをコピー + Hex 16 進 + Hex with Alpha 16 進 (アルファ付き) + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 値 Pie End Angle: 扇形の終了角度: Pie Start Angle: 扇形の開始角度: Stroke Color カラー (線) @@ -5179,6 +5187,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` は hex、hexAlpha、rgb、hsl、oklch または cmyk でなければなりません +@msg Copied the color as {text} カラーを {text} としてコピーしました @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 にすることはできません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b1af817bf2..20b8bf861c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2490,6 +2490,14 @@ Show Hex Field Hex ველის ჩვენება Hex or CSS color Hex ან CSS ფერი Parse Color ფერის გარჩევა + Format Color ფერის ფორმატირება + Copy Color As ფერის კოპირება როგორც + Hex Hex + Hex with Alpha Hex ალფათი + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK მნიშვნელობები Stroke Color კონტურის ფერი Fill Gradient შევსების გრადიენტი Stroke Gradient კონტურის გრადიენტი @@ -8101,6 +8109,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` უნდა იყოს hex, hexAlpha, rgb, hsl, oklch ან cmyk +@msg Copied the color as {text} ფერი დაკოპირდა როგორც {text} @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. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index be197ef35a..3117b7cad8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -515,6 +515,14 @@ digits Malayalam 말라얄람어 Show Hex Field 16진수 필드 표시 Hex or CSS color 16진수 또는 CSS 색상 Parse Color 색상 구문 분석 + Format Color 색상 서식 지정 + Copy Color As 다음 형식으로 색상 복사 + Hex 16진수 + Hex with Alpha 알파 포함 16진수 + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 값 Pie End Angle: 파이 끝 각도: Pie Start Angle: 파이 시작 각도: Stroke Color 선 색상 @@ -5106,6 +5114,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation`은 hex, hexAlpha, rgb, hsl, oklch 또는 cmyk여야 합니다 +@msg Copied the color as {text} 색상을 {text} 형식으로 복사했습니다 @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로 지정할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 64ec429108..87cb7942d4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1005,6 +1005,14 @@ liquify-list-end {0}, {1} {0} en {1} Show Hex Field Hexveld tonen Hex or CSS color Hex- of CSS-kleur Parse Color Kleur ontleden + Format Color Kleur opmaken + Copy Color As Kleur kopiëren als + Hex Hex + Hex with Alpha Hex met alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-waarden Stroke Color Contourkleur Fill Gradient Vulverloop Stroke Gradient Contourverloop @@ -8265,6 +8273,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` moet hex, hexAlpha, rgb, hsl, oklch of cmyk zijn +@msg Copied the color as {text} Kleur gekopieerd als {text} @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 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 156d2c6aba..65e18346b3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -438,6 +438,14 @@ Show Hex Field Pokaż pole hex Hex or CSS color Kolor hex lub CSS Parse Color Analizuj kolor + Format Color Formatuj kolor + Copy Color As Kopiuj kolor jako + Hex Hex + Hex with Alpha Hex z alfą + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Wartości CMYK Stroke Color Kolor obrysu Fill Gradient Gradient wypełnienia Stroke Gradient Gradient obrysu @@ -4853,6 +4861,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` musi mieć wartość hex, hexAlpha, rgb, hsl, oklch lub cmyk +@msg Copied the color as {text} Skopiowano kolor jako {text} @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 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 171f408e4f..503d4b57cc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1989,6 +1989,14 @@ antiAlias Sharp Nítido Show Hex Field Mostrar Campo Hex Hex or CSS color Cor hex ou CSS Parse Color Interpretar Cor + Format Color Formatar Cor + Copy Color As Copiar Cor Como + Hex Hex + Hex with Alpha Hex com Alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valores CMYK 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 @@ -6323,6 +6331,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` deve ser hex, hexAlpha, rgb, hsl, oklch ou cmyk +@msg Copied the color as {text} Cor copiada como {text} @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 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e49d353f62..768eddcb00 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2464,6 +2464,14 @@ file-filter Templates Шаблоны Show Hex Field Показать поле hex Hex or CSS color Цвет hex или CSS Parse Color Разобрать цвет + Format Color Форматировать цвет + Copy Color As Копировать цвет как + Hex Hex + Hex with Alpha Hex с альфа-каналом + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Значения CMYK Opacity & Mask Define Knockout Shape Непрозрачность и маска определяют форму вырезания Opacity Mask Непрозрачная маска Opacity Mask Info Сведения о непрозрачной маске @@ -4759,6 +4767,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` должен быть hex, hexAlpha, rgb, hsl, oklch или cmyk +@msg Copied the color as {text} Цвет скопирован как {text} @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}` не имеет параметров diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6db42ffbfb..b9abeb0927 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2376,6 +2376,14 @@ font-technology Variable Variabla Show Hex Field Visa hexfält Hex or CSS color Hex- eller CSS-färg Parse Color Tolka färg + Format Color Formatera färg + Copy Color As Kopiera färg som + Hex Hex + Hex with Alpha Hex med alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-värden Opacity & Mask Define Knockout Shape Opacitet och mask definierar utsparningsform Opacity Mask Opacitetsmask Opacity Mask Info Info om opacitetsmask @@ -6348,6 +6356,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` måste vara hex, hexAlpha, rgb, hsl, oklch eller cmyk +@msg Copied the color as {text} Kopierade färgen som {text} @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 diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 37b617d12d..9340b61f81 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -475,6 +475,27 @@ fn color_wheel_opacity_strings_are_in_complete_catalogs() { } } +/// The Color Wheel panel's Copy Color As, its status message and the error of `color.format`. +#[test] +fn copy_color_as_strings_are_in_complete_catalogs() { + let labels = ["Copy Color As", "Hex", "Hex with Alpha", "CSS rgb()", "CSS hsl()", "CSS oklch()", "CMYK Values", "Format Color"]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in labels { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let literals = message_literals(); + let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk"; + assert!(literals.contains(notation), "{notation}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, notation), notation, "{code}"); + let copied = "Copied the color as rgb(51 102 153 / 50%)"; + let shown = message(lang, copied); + assert!(shown != copied && shown.contains("rgb(51 102 153 / 50%)"), "{code}: {shown}"); + } +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index dd3e771a76..b1342e37d0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2215,6 +2215,14 @@ font-technology Variable Değişken Show Hex Field Hex Alanını Göster Hex or CSS color Hex veya CSS rengi Parse Color Rengi Ayrıştır + Format Color Rengi Biçimlendir + Copy Color As Rengi Farklı Biçimde Kopyala + Hex Hex + Hex with Alpha Alfalı Hex + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK Değerleri 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 @@ -4470,6 +4478,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` hex, hexAlpha, rgb, hsl, oklch veya cmyk olmalıdır +@msg Copied the color as {text} Renk şu biçimde kopyalandı: {text} @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 diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b84fe99f60..bf6c7dcf7f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2467,6 +2467,14 @@ file-filter Templates Шаблони Show Hex Field Показати поле hex Hex or CSS color Колір hex або CSS Parse Color Розібрати колір + Format Color Форматувати колір + Copy Color As Копіювати колір як + Hex Hex + Hex with Alpha Hex з альфа-каналом + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Значення CMYK Opacity & Mask Define Knockout Shape Непрозорість та маска визначають форму вирізування Opacity Mask Маска непрозорості Opacity Mask Info Відомості про маску непрозорості @@ -4747,6 +4755,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` має бути hex, hexAlpha, rgb, hsl, oklch або cmyk +@msg Copied the color as {text} Колір скопійовано як {text} @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}` не має параметрів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 34c0991600..1a748a1438 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2739,6 +2739,14 @@ digits Hindi Hindi 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 + Format Color Định dạng màu + Copy Color As Sao chép màu dưới dạng + Hex Hex + Hex with Alpha Hex có alpha + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Giá trị CMYK 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ờ @@ -4757,6 +4765,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` phải là hex, hexAlpha, rgb, hsl, oklch hoặc cmyk +@msg Copied the color as {text} Đã sao chép màu dưới dạng {text} @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 diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index dead5e5573..bd6a4cdbd0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2328,6 +2328,14 @@ file-filter Templates 模板 Show Hex Field 显示十六进制字段 Hex or CSS color 十六进制或 CSS 颜色 Parse Color 解析颜色 + Format Color 格式化颜色 + Copy Color As 将颜色复制为 + Hex 十六进制 + Hex with Alpha 十六进制 (含 Alpha) + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 值 Opacity & Mask Define Knockout Shape 不透明度与蒙版定义挖空形状 Opacity Mask 不透明度蒙版 Opacity Mask Info 不透明度蒙版信息 @@ -4860,6 +4868,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` 必须是 hex、hexAlpha、rgb、hsl、oklch 或 cmyk +@msg Copied the color as {text} 已将颜色复制为 {text} @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 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6152ca7220..442d2364f7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2486,6 +2486,8 @@ 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 `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` 必須是 hex、hexAlpha、rgb、hsl、oklch 或 cmyk +@msg Copied the color as {text} 已將顏色複製為 {text} @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 @@ -3601,6 +3603,14 @@ liquify-list-end {0}, {1} {0}和{1} Show Hex Field 顯示十六進位欄位 Hex or CSS color 十六進位或 CSS 顏色 Parse Color 剖析顏色 + Format Color 格式化顏色 + Copy Color As 將顏色複製為 + Hex Hex + Hex with Alpha Hex (含 Alpha) + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 值 Opacity & Mask Define Knockout Shape 不透明度與遮色片定義挖空形狀 Opacity Mask 不透明度遮色片 Opacity Mask Info 不透明度遮色片資訊 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 267834ab4f..1d03f9c35c 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_copy; +#[cfg(test)] mod tests_color_wheel_hex; #[cfg(test)] mod tests_color_wheel_opacity; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index ff6b8a1b4d..e5c7eaecca 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -212,7 +212,7 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S } /// The panel menu: Wheel View and Box View, Box Channel while the box shows, OKLCH Sliders, Show -/// Opacity and Show Hex Field. +/// Opacity, Show Hex Field and Copy Color As. 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)] { @@ -246,6 +246,54 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Show Hex Field"), true, set.hex_field) { command(app, &json!({ "hexField": !set.hex_field })).ok(); } + ui.separator(); + let has_color = wheel_target(app, ui).color().is_some(); + ui.add_enabled_ui(has_color, |ui| { + ui.menu_button(format!(" {}", tl!("Copy Color As")), |ui| copy_menu(app, ui)); + }); +} + +/// The items of Copy Color As. +pub(crate) fn copy_menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let notations = [ + (tl!("Hex"), "hex"), + (tl!("Hex with Alpha"), "hexAlpha"), + (tl!("CSS rgb()"), "rgb"), + (tl!("CSS hsl()"), "hsl"), + (tl!("CSS oklch()"), "oklch"), + (tl!("CMYK Values"), "cmyk"), + ]; + for (label, notation) in notations { + let clicked = if notation == "oklch" { + widgets::menu_item_hint(ui, label, cms::active().rgb_is_srgb(), false, tl!("OKLCH needs sRGB as the working RGB space")) + } else { + menu_item(ui, label, true, false) + }; + if clicked { + copy_color_as(app, ui, notation); + } + } +} + +/// Copy Color As: put `color.format`'s text in `notation` of the color the panel shows on the +/// clipboard, with the opacity of what the row of Show Opacity edits when it has one, and say in +/// the status bar what was copied. Does nothing without a solid color. +pub(crate) fn copy_color_as(app: &mut VectorcraftApp, ui: &Ui, notation: &str) { + let tgt = wheel_target(app, ui); + let Some(color) = tgt.color() else { return }; + let (o, live) = shown_opacity(app, &tgt); + let mut p = json!({ "color": color_json(&color), "notation": notation }); + if live { + p["opacity"] = json!(f64::from(o.clamp(0.0, 1.0)) * 100.0); + } + match app.run("color.format", p) { + Ok(r) => { + let text = r["text"].as_str().unwrap_or_default().to_string(); + ui.ctx().copy_text(text.clone()); + app.status(format!("Copied the color as {text}")); + } + Err(e) => app.status(e), + } } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, diff --git a/crates/ui-egui/src/panels/tests_color_wheel_copy.rs b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs new file mode 100644 index 0000000000..d80bb191d8 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs @@ -0,0 +1,175 @@ +//! The Color Wheel panel's Copy Color As: the text each item puts on the clipboard, the opacity it +//! carries, the status bar message, and that `color.parse` reads each text back. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use vectorcraft_color::cms; +use vectorcraft_engine::Session; + +use super::color_wheel::{copy_color_as, copy_menu, menu}; +use crate::VectorcraftApp; + +/// A harness that draws `draw` with the app's fonts installed. +fn harness(app: VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut egui::Ui)) -> Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + draw(app, ui); + }, + app, + ); + h.run_steps(3); + h +} + +/// An app with a selected rectangle filled with #336699 at `opacity` %. +fn app(opacity: f64) -> 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": "#336699", "opacity": opacity})).unwrap(); + app +} + +/// The texts Copy Color As › `notation` puts on the clipboard in one frame. +fn copy(app: &mut VectorcraftApp, notation: &str) -> Vec { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(Default::default(), |ui| copy_color_as(app, ui, notation)); + out.textures_delta.clear(); + out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }).collect() +} + +fn undo_count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// Copy Color As › CSS rgb() puts CSS Color 4's space-separated form on the clipboard, with the +/// opacity after a slash, and says what it copied; the document does not change. +#[test] +fn css_rgb_copies_the_color_and_the_opacity() { + let mut app = app(50.0); + let before = undo_count(&app); + assert_eq!(copy(&mut app, "rgb"), ["rgb(51 102 153 / 50%)"]); + assert_eq!(app.ui.status, "Copied the color as rgb(51 102 153 / 50%)"); + assert_eq!(undo_count(&app), before, "copying records no undo step"); +} + +/// Hex and CMYK Values never carry the opacity; Hex with Alpha always does, as `ff` at 100 %; CSS +/// adds it only under 100 %. +#[test] +fn each_item_writes_its_notation() { + let mut half = app(50.0); + assert_eq!(copy(&mut half, "hex"), ["#336699"]); + assert_eq!(copy(&mut half, "hexAlpha"), ["#33669980"]); + assert_eq!(copy(&mut half, "hsl"), ["hsl(210 50% 40% / 50%)"]); + let oklch = copy(&mut half, "oklch"); + assert!(oklch[0].starts_with("oklch(") && oklch[0].ends_with(" / 50%)"), "{oklch:?}"); + let mut full = app(100.0); + assert_eq!(copy(&mut full, "hexAlpha"), ["#336699ff"]); + assert_eq!(copy(&mut full, "rgb"), ["rgb(51 102 153)"]); + let cmyk = copy(&mut full, "cmyk"); + assert_eq!(copy(&mut half, "cmyk"), cmyk, "CMYK Values leaves the opacity out"); + // The working CMYK numbers through the color settings, as color.convert gives them. + let r = full.run("color.convert", json!({"color": "#336699", "to": "cmyk"})).unwrap(); + let pct: Vec = r["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect(); + assert_eq!(cmyk, [format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3])]); +} + +/// A CMYK fill copies its own CMYK values. +#[test] +fn a_cmyk_fill_copies_its_own_values() { + let mut app = app(100.0); + app.run("paint.setFill", json!({"color": {"c": 10, "m": 20, "y": 30, "k": 0}})).unwrap(); + assert_eq!(copy(&mut app, "cmyk"), ["C=10 M=20 Y=30 K=0"]); +} + +/// `color.parse` reads every copied text but CMYK Values back to the color the hex field shows, +/// and the alpha to the fill's opacity. +#[test] +fn color_parse_reads_each_copied_text_back() { + let mut app = app(25.0); + for notation in ["hex", "hexAlpha", "rgb", "hsl", "oklch"] { + let text = copy(&mut app, notation).pop().unwrap(); + let r = app.run("color.parse", json!({"text": text})).unwrap(); + assert_eq!(r["hex"], "#336699", "{notation}: {text}"); + let opacity = r["opacity"].as_f64(); + match notation { + "hex" => assert_eq!(opacity, None, "{text}"), + // 64 of 255. + "hexAlpha" => assert_eq!(opacity, Some(25.1), "{text}"), + _ => assert_eq!(opacity, Some(25.0), "{text}"), + } + } +} + +/// With nothing selected the panel shows the color for new art, which has no opacity of its own: +/// the copied text carries none. +#[test] +fn with_nothing_selected_the_color_for_new_art_is_copied_without_an_opacity() { + let mut app = app(50.0); + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": "#336699"})).unwrap(); + assert_eq!(copy(&mut app, "hexAlpha"), ["#336699ff"]); + assert_eq!(copy(&mut app, "rgb"), ["rgb(51 102 153)"]); +} + +/// Without a solid color (a fill of None) nothing is copied. +#[test] +fn nothing_is_copied_without_a_solid_color() { + let mut app = app(100.0); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.ui.status.clear(); + assert!(copy(&mut app, "hex").is_empty()); + assert_eq!(app.ui.status, ""); +} + +/// Panel menu › Copy Color As is gray without a solid color and available with one. +#[test] +fn copy_color_as_is_gray_without_a_solid_color() { + let h = harness(app(100.0), menu); + assert!(!h.get_by_label(" Copy Color As").accesskit_node().is_disabled()); + let mut none = app(100.0); + none.run("paint.setFill", json!({"none": true})).unwrap(); + let h = harness(none, menu); + assert!(h.get_by_label(" Copy Color As").accesskit_node().is_disabled()); +} + +/// While the working RGB space is not sRGB, Copy Color As › CSS oklch() is gray, the other items are +/// not, and copying as oklch() puts the error in the status bar and nothing on the clipboard. +#[test] +fn css_oklch_is_gray_while_the_working_space_is_not_srgb() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_COPY_P3"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "panels::tests_color_wheel_copy::css_oklch_is_gray_while_the_working_space_is_not_srgb", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated working space test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let h = harness(app(100.0), copy_menu); + assert!(!h.get_by_label(" CSS oklch()").accesskit_node().is_disabled(), "sRGB"); + let mut app = app(100.0); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert!(copy(&mut app, "oklch").is_empty()); + assert!(app.ui.status.ends_with("OKLCH needs sRGB as the working RGB space"), "{}", app.ui.status); + let h = harness(app, copy_menu); + assert!(h.get_by_label(" CSS oklch()").accesskit_node().is_disabled()); + for label in [" Hex", " Hex with Alpha", " CSS rgb()", " CSS hsl()", " CMYK Values"] { + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 80a887ab68..1dbecbb65c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -689,6 +689,23 @@ saturation and lightness are so large that a channel overflows to an infinity is 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`. +`color.format {"color": "#336699", "opacity": 50, "notation": "rgb"}` answers `{"text": "rgb(51 102 153 / 50%)"}`. +`notation` is `hex` (`#336699`), `hexAlpha` (`#33669980`, and `#336699ff` at 100 % or without `opacity`), `rgb`, `hsl` +(`hsl(210 50% 40% / 50%)`), `oklch` (`oklch(49.93% 0.0987 250.43 / 50%)`) or `cmyk` (`C=87 M=61 Y=19 K=0` with the +default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity is under 100; +`hex` and `cmyk` leave the opacity out. Every notation but `cmyk` writes the working RGB numbers, the same numbers +the Color panel's hex field shows, with lowercase hex digits; `oklch` is an error while the working RGB space is not +sRGB. `hsl()` and `oklch()` give their numbers to two decimal places (chroma to four), and `oklch()` takes up to two +more where fewer would read back to another color. `cmyk` is the color in the working CMYK space +through the color settings, written as a new swatch is named; a CMYK color keeps its own values. `color.parse` reads +every notation but `cmyk` back to the same `#rrggbb`. `opacity` is 0 to 100, and any other value, or another +`notation`, is an error. + +The Color Wheel panel menu's Copy Color As puts the panel's color on the clipboard as Hex, Hex with Alpha, CSS +rgb(), CSS hsl(), CSS oklch() or CMYK Values, the six `color.format` notations, with the opacity that Show Opacity +edits when it has one (whether or not that row shows), and the status bar shows what was copied. CSS oklch() is gray +while the working RGB space is not sRGB, and Copy Color As is gray without a solid color. + 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 3ea05ecde0..696ab895e5 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 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. + 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. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`), and `color.parse` reads every form but the CMYK values back to the same color. 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` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.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 727ef739e756f86dee1187231d9029f202a56330 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:48:37 -0800 Subject: [PATCH 02/18] Color Wheel: the progress line says where the alpha and oklch() apply - The Show Hex Field text says a typed alpha sets the opacity only where the Show Opacity row is not gray, and that oklch() is taken only while the working RGB space is sRGB; Copy Color As writes oklch() under the same condition. - color_format_writes_every_css_form_through_the_intent compares the hex with the absolute colorimetric RGB of the cyan, so a formatter that used another intent fails it. --- crates/engine/tests/color_settings.rs | 7 +++++-- docs/target-app-parity.md | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 6bd0a9d66f..a7ae09e5ba 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1066,8 +1066,9 @@ fn color_format_writes_every_css_form_through_the_intent() { let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name; s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap(); let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0}); - let intents_differ = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8) - != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); + let absolute = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8); + let intents_differ = + absolute != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); // Collected as results, so that a failure still restores the process-wide settings first. let mut read_back = vec![]; for notation in ["hex", "rgb", "hsl", "oklch"] { @@ -1080,6 +1081,8 @@ fn color_format_writes_every_css_form_through_the_intent() { assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}"); assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB"); let hex = read_back[0].1.clone().unwrap(); + let [r, g, b] = absolute; + assert_eq!(hex, format!("#{r:02x}{g:02x}{b:02x}"), "hex is the absolute colorimetric RGB"); for (notation, text, back) in read_back { assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}"); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 696ab895e5..ef1178e3b8 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 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. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`), and `color.parse` reads every form but the CMYK values back to the same color. 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` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.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 where that row is not gray (where it is gray, only the color is applied). `oklch()` is taken only while the working RGB space is sRGB. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`; `oklch()` only while the working RGB space is sRGB), and `color.parse` reads every form but the CMYK values back to the same color. 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` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.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 b54ff2d9db3c0c12f3fd5bbab40b94d883193fdd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:15:12 -0800 Subject: [PATCH 03/18] 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 6d6e8448e3..122c25c51f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6707,7 +6707,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 9a85690da0c7e3733e910da60e15361d3dbd5021 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 23:59:28 -0800 Subject: [PATCH 04/18] Color: color.format docs say the opacity suffix follows the rounded percentage The CSS forms add ` / opacity%` only when the opacity, rounded to two decimal places, is under 100, so 99.999 writes no suffix. The color.format help and docs/mcp.md now say so. --- crates/engine/src/cmd/colorcmds.rs | 2 +- docs/mcp.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 7783e46514..2740b1d27c 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -150,7 +150,7 @@ pub fn specs() -> Vec { "Format Color", [], None, - "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (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), each in the space-separated form with ` / opacity%` added when the opacity is under 100, hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (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), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", always, format_color ), diff --git a/docs/mcp.md b/docs/mcp.md index 6eae5c3b6f..9222ae8f5b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -730,7 +730,7 @@ color parameters of the other commands still refuse `#rrggbbaa` and `#rgba`. `color.format {"color": "#336699", "opacity": 50, "notation": "rgb"}` answers `{"text": "rgb(51 102 153 / 50%)"}`. `notation` is `hex` (`#336699`), `hexAlpha` (`#33669980`, and `#336699ff` at 100 % or without `opacity`), `rgb`, `hsl` (`hsl(210 50% 40% / 50%)`), `oklch` (`oklch(49.93% 0.0987 250.43 / 50%)`) or `cmyk` (`C=87 M=61 Y=19 K=0` with the -default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity is under 100; +default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity, rounded to two decimal places, is under 100 (`99.999` writes no suffix); `hex` and `cmyk` leave the opacity out. Every notation but `cmyk` writes the working RGB numbers, the same numbers the Color panel's hex field shows, with lowercase hex digits; `oklch` is an error while the working RGB space is not sRGB. `hsl()` and `oklch()` give their numbers to two decimal places (chroma to four), and `oklch()` takes up to two From 8c56faed9ec3a8d57a181385c0d90733131e2e2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 12:26:21 -0800 Subject: [PATCH 05/18] Color: color.format help gives the extra OKLCH decimal places The help for color.format now says oklch() takes up to two more decimal places where fewer would read back to another color, as docs/mcp.md does. --- crates/engine/src/cmd/colorcmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 2740b1d27c..6d658241eb 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -150,7 +150,7 @@ pub fn specs() -> Vec { "Format Color", [], None, - "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (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), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (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), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", always, format_color ), From 4e7ab22b9fc9631fb55d28847ebdc24fd253bcec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 19:16:52 -0800 Subject: [PATCH 06/18] Color Wheel: the panel menu lists Show Opacity once --- crates/ui-egui/src/panels/color_wheel.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index daee73d390..96a3e81963 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -385,9 +385,6 @@ 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 Color Vision Preview"), true, set.vision) { command(app, &json!({ "vision": !set.vision })).ok(); } From 3de7547b2ab56ea255bb068212cc5b9c545ab3dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:44:50 -0800 Subject: [PATCH 07/18] Clean Up: remove hairline slivers thinner than a set width Object > Path > Clean Up gets a Hairline Slivers option, off by default, with a Sliver Width (0.001 to 3 pt, 0.03 mm by default). It removes closed paths and compound paths with a visible fill, no visible stroke and no effect when no circle that wide fits anywhere inside their fill: shapes that look like single lines in Outline view but have almost no area. Select > Object > Hairline Slivers... selects the objects Clean Up would remove, only inside the isolated group while one is isolated. - vectorcraft-pathops: thinner_than measures the largest circle that fits in a fill. Bounds, the area against the outline length, and the width of the convex hull settle most shapes; the rest go through a cell search on the path's edges and then on the resolved outline. thinner_than_within takes the search's work from a budget, and one budget covers a whole document, so a run over thousands of shapes ends in bounded time. - Shapes too complex to measure, and shapes still unmeasured when the budget runs out, are kept, and the reply's warning counts them. - A compound path is measured as one fill. Hidden, locked and template objects, art on locked artboards, guides, the clipping paths of groups and layers, and the members of live and generated art are left alone. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/pathops.rs | 162 ++++- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/select.rs | 28 + crates/engine/src/lib.rs | 2 +- crates/engine/src/tests/pathops.rs | 308 ++++++++++ crates/pathops/src/boolean.rs | 2 +- crates/pathops/src/lib.rs | 2 + crates/pathops/src/thickness.rs | 557 ++++++++++++++++++ crates/ui-egui/src/dialogs/command.rs | 15 +- crates/ui-egui/src/menus/tree.rs | 13 +- docs/mcp.md | 18 + docs/target-app-parity.md | 1 + 12 files changed, 1099 insertions(+), 10 deletions(-) create mode 100644 crates/pathops/src/thickness.rs diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 1793f17d5c..a3eaf08567 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::BlendMode; use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer}; -use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject}; +use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject}; use vectorcraft_geom::{FillRule, PathData, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Clean Up…", ["Object", "Path"], None, - "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} → {removed}", + "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}", has_doc, clean_up ), @@ -1662,12 +1662,150 @@ fn is_painted(a: &Appearance) -> bool { }) } +/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value. +pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4; +/// The widths Hairline Slivers takes, in points. +pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive = 0.001..=3.0; + +/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string +/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`]. +pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result { + let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH); + if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) { + let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end()); + return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt"))); + } + Ok(w) +} + +/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths +/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke), +/// whose fill no circle `width` across fits inside? A compound path is measured as one fill. +/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]). +/// A hidden member of a compound path is measured too, since the compound path paints it. +fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option { + // A shape with no fill that paints is left to Unpainted Objects. + if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) { + return Some(false); + } + let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind { + NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule), + NodeKind::Compound { children, rule } => { + let mut all = vec![]; + for c in children { + let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) }; + all.extend(path.subpaths.iter()); + } + (all, *rule) + } + _ => return Some(false), + }; + // Paths of one anchor are stray points, and open paths are lines. + if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) { + return Some(false); + } + po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget) +} + +/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an +/// effect on the object or on one of its fills and strokes? +fn draws_beyond_its_fill(a: &Appearance) -> bool { + a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty()) +} + +/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a +/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping +/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers +/// leaves its members alone. +fn holds_generated_art(n: &Node) -> bool { + let e = n.extras(); + vectorcraft_tools::builder::is_live_paint(n) + || e.type_outlines + || e.clip_pieces + || e.graph.is_some() + || e.shaper.is_some() + || e.dimension.is_some() + || e.flare.is_some() + || e.trace.is_some() + || e.objects_on_path.is_some() + || e.live_paint_gaps.is_some() + || e.compound_shape +} + +/// The objects Hairline Slivers finds in `d` for `width`. +pub(crate) struct Slivers { + pub ids: Vec, + /// Closed paths and compound paths whose fill couldn't be measured, which are left as they are. + pub unmeasured: Vec, +} + +/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any. +pub(crate) fn unmeasured_warning(count: usize) -> Option { + (count > 0).then(|| { + format!( + "Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are" + ) + }) +} + +/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not +/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and +/// groups of the whole document. A compound path counts as one object. The clipping paths of groups +/// and layers (and all of a clipping group used as one), the members of live and generated art, and +/// the members of groups and layers whose own stroke or effect paints them are left out. +pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers { + struct Walk<'a> { + width: f64, + locks: LockedArtboards<'a>, + within: &'a dyn Fn(NodeId) -> bool, + // One budget for the whole document, so that thousands of shapes that need a search take + // a bounded time; the shapes after it runs out count as unmeasured. + budget: po::ThicknessBudget, + out: Vec<(NodeId, Option)>, + } + fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) { + if !n.visible || n.locked || n.is_template() || clip_path { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { + if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) { + return; + } + let clips = n.clips(); + for (i, c) in children.iter().enumerate() { + visit(c, clips && i == 0, w); + } + } + // Art on a locked artboard, or outside `within`, is left out before it is measured. + NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => { + match is_hairline_sliver(n, w.width, &mut w.budget) { + Some(false) => {} + found => w.out.push((n.id, found)), + } + } + _ => {} + } + } + let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] }; + for l in &d.layers { + visit(l, false, &mut w); + } + let mut found = w.out; + let editable = d.editable(); + found.retain(|(id, _)| editable(*id)); + let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some()); + Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() } +} + fn clean_up(s: &mut Session, p: &Value) -> Result { const C: &str = "object.path.cleanUp"; let stray = switch_or(p, "strayPoints", true, C)?; let unpainted = switch_or(p, "unpaintedObjects", true, C)?; let empty_text = switch_or(p, "emptyTextPaths", true, C)?; - let found = { + let slivers = switch_or(p, "hairlineSlivers", false, C)?; + let width = sliver_width(p, "sliverWidth", C)?; + let (found, warning) = { let d = &s.doc()?.doc; let mut v = vec![]; fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec, opts: (bool, bool, bool)) { @@ -1709,10 +1847,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } let editable = d.editable(); v.retain(|id| editable(*id)); - v + let mut warning = None; + if slivers { + let found = hairline_slivers(d, width, &|_| true); + let listed: BTreeSet = v.iter().copied().collect(); + // A shape another option removes isn't left as it is. + warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count()); + v.extend(found.ids.into_iter().filter(|id| !listed.contains(id))); + } + (v, warning) + }; + let reply = |removed: usize| match &warning { + Some(w) => json!({ "removed": removed, "warning": w }), + None => json!({ "removed": removed }), }; if found.is_empty() { - return Ok(json!({ "removed": 0 })); + return Ok(reply(0)); } s.edit("Clean Up", |d, _| { let mut gone = Beside::replacing(d, &found); @@ -1723,7 +1873,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } gone.finish(d) })?; - Ok(json!({ "removed": found.len() })) + Ok(reply(found.len())) } // ---------- Divide Objects Below ---------- diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..0d6afae1c5 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -529,6 +529,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.object.brushStrokes", "select.object.clippingMasks", "select.object.directionHandles", + "select.object.hairlineSlivers", "select.object.notAlignedToPixelGrid", "select.object.pointText", "select.object.slices", diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index b7a6043a98..6379762535 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint; use super::object::can_align; use super::panelcmds::artboard_at; +use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning}; use super::wand::{fill_of, stroke_of}; use super::{ CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param, @@ -196,6 +197,15 @@ pub fn specs() -> Vec { cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| p.anchor_count() == 1))), + cmd!( + "select.object.hairlineSlivers", + "Hairline Slivers…", + ["Select", "Object"], + None, + "{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}", + has_doc, + select_hairline_slivers + ), cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| !p.is_closed()))), @@ -1423,6 +1433,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result { Ok(json!({ "count": s.doc()?.selection.objects.len() })) } +/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes +/// ([`hairline_slivers`]), inside the isolated group while one is isolated. +fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.object.hairlineSlivers"; + let width = sliver_width(p, "width", C)?; + let st = s.doc()?; + let (d, iso) = (&st.doc, st.isolation); + let locks = d.locked_artboards(); + let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id)); + let warning = unmeasured_warning(found.unmeasured.len()); + s.select(|_, sel| sel.set(found.ids))?; + let count = s.doc()?.selection.objects.len(); + Ok(match warning { + Some(w) => json!({ "count": count, "warning": w }), + None => json!({ "count": count }), + }) +} + /// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned /// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk /// does not look at the paths inside it. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..fafcf7e943 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -32,7 +32,7 @@ pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::auto_simplify_level; +pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 60f223334c..be57671884 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1066,6 +1066,314 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// A path drawn by `d`, filled black with no stroke. +fn filled(s: &mut Session, d: &str) -> NodeId { + let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()); + fill_only(s, id); + id +} + +fn fill_only(s: &mut Session, id: NodeId) { + s.edit("t", |d, _| { + d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into(); + Ok(()) + }) + .unwrap(); +} + +/// Hairline Slivers' test art: (the slivers, the shapes with a width). +fn sliver_art(s: &mut Session) -> (Vec, Vec) { + // A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide + // and tall. A long one across the page. A compound path of two slivers. + let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z"); + let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z"); + let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z"); + let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, two); + // Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it + // draws a line), an open path, and a compound path of a sliver and a square. + let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z"); + let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, dot); + let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into(); + Ok(()) + }) + .unwrap(); + let open = filled(s, "M500 10 L540 40 L500.001 10.0015"); + let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z"); + let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z"); + s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap(); + let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, mixed); + s.execute("select.none", &json!({})).unwrap(); + (vec![triangle, long, two], vec![strip, dot, stroked, open, mixed]) +} + +#[test] +fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() { + let mut s = session(); + let (slivers, kept) = sliver_art(&mut s); + // Off by default. + assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0); + // A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is + // at 0 % opacity paints nothing either. + let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z"); + let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0); + if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() { + f.opacity = 0.0; + } + d.node_mut(clear).unwrap().appearance = a.into(); + Ok(()) + }) + .unwrap(); + let kept = [kept, vec![unpainted, clear]].concat(); + let undo = s.doc().unwrap().history.undo.len(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left"); + for (k, id) in kept.iter().enumerate() { + assert!(d.node(*id).is_some(), "shape {k} with a width went"); + } + assert_eq!(r["removed"], slivers.len()); + // One undo step brings every sliver back. + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some())); + // A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot. + let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"}); + assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1); + assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some()); +} + +/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or +/// locked slivers. +#[test] +fn select_hairline_slivers_selects_what_clean_up_removes() { + let mut s = session(); + let (slivers, _) = sliver_art(&mut s); + let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z"); + let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(hidden).unwrap().visible = false; + d.node_mut(locked).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], slivers.len()); + let mut selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + selected.sort_unstable(); + let mut want = slivers.clone(); + want.sort_unstable(); + assert_eq!(selected, want); + // Inside an isolated group, only the slivers in it are selected. + let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z"); + let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z"); + s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + // A sliver in a group is selected as Clean Up finds it. + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1); + assert!(s.doc().unwrap().selection.objects.contains(&inner)); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A template layer that was unlocked afterward. + let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z"); + s.edit("t", |d, _| { + let n = d.node_mut(template).unwrap(); + if let NodeKind::Layer { template, .. } = &mut n.kind { + *template = true; + } + n.locked = false; + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(template).unwrap().is_template()); + s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert!(!s.doc().unwrap().selection.objects.contains(&traced)); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some()); +} + +/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint +/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's +/// clipping path; Clean Up's other options keep the layer's clipping path too. +#[test] +fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() { + let mut s = session(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.execute("select.set", &json!({"ids": [rough.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap(); + let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z"); + let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z"); + s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + // A group's own 5 pt stroke draws along its member. + let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into(); + Ok(()) + }) + .unwrap(); + // A thin part of type's glyph outlines. + let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap(); + let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(outlines).unwrap().extras_mut().type_outlines = true; + Ok(()) + }) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + // A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects + // removes the clipping path. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z"); + let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z"); + let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went"); + // A clip group whose clipping path is a sliver. + let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z"); + let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + // A guide drawn as a sliver, and a sliver with an effect on its stroke. + let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z"); + let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind { + *guide = true; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(mask).is_some(), "the clip group's clipping path went"); + assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went"); + // A layer clipped by a group (as an opened file can have it): its sliver member clips too. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z"); + let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [bare.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind { + *clip = true; + let i = children.iter().position(|c| c.id == g).unwrap(); + let c = children.remove(i); + children.insert(0, c); + } + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went"); +} + +/// A sliver on a locked artboard is left alone. +#[test] +fn hairline_slivers_leave_art_on_a_locked_artboard_alone() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.edit("t", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + assert!(s.doc().unwrap().doc.node(sliver).is_some()); +} + +/// A shape too complex to measure is kept, and both commands say how many there were. +#[test] +fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + // A closed zigzag of more anchors than one shape is measured with. + let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1; + let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect(); + let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind { + *path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true)); + } + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + assert_eq!(r["removed"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(sliver).is_none() && d.node(huge).is_some()); +} + +/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the +/// document, the selection and the undo history stay as they were. +#[test] +fn hairline_slivers_refuse_a_width_out_of_range() { + let mut s = session(); + sliver_art(&mut s); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] { + for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] { + let mut p = serde_json::Map::new(); + p.insert(key.into(), w.clone()); + if cmd == "object.path.cleanUp" { + p.insert("hairlineSlivers".into(), json!(true)); + } + let r = s.execute(cmd, &Value::Object(p)); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}"); + assert!(state(&s) == before, "{cmd} {w} changed the document"); + } + } + // Both ends of the range are taken. + for w in [json!(0.001), json!(3), json!("3 pt")] { + assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}"); + let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w}); + assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}"); + } +} + /// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an /// error naming the param, and leave the document, the selection and the undo history as they were. /// Null keeps a param's default, and a distance still takes a string with a unit. diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index 60c2a8b296..e35e5e2664 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -21,7 +21,7 @@ thread_local! { /// The contour passes made over an arrangement on this thread, each of which walks all of it. pub(crate) static CONTOUR_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The sweeps [`normalize_bez`] made on this thread. - static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The input curves [`exact_merge`] tested on this thread. static EXACT_MERGE_CURVES: std::cell::Cell = const { std::cell::Cell::new(0) }; } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 0ff1b82594..d02e5a8a93 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -15,6 +15,7 @@ mod offset; mod pathfinder; mod planar; mod sweep_axis; +mod thickness; mod trap; pub use boolean::{ @@ -35,6 +36,7 @@ pub use planar::{ Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, }; +pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; /// Errors from fallible operations. diff --git a/crates/pathops/src/thickness.rs b/crates/pathops/src/thickness.rs new file mode 100644 index 0000000000..a4bffb998a --- /dev/null +++ b/crates/pathops/src/thickness.rs @@ -0,0 +1,557 @@ +//! The thickness of a filled shape: whether a circle of a given width fits anywhere inside its +//! fill (Clean Up's and Select › Object's Hairline Slivers). + +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _}; +use vectorcraft_geom::{FillRule, PathData}; + +use crate::boolean::{fill_bezpath, normalize_bez}; + +/// Most line pieces the outline of one shape is measured with. +pub const MAX_THICKNESS_PIECES: usize = 100_000; +/// Most cells one search for a wide enough spot looks at. +const MAX_CELLS: usize = 500_000; +/// Most distances from a point to a piece of outline one search measures. +const MAX_WORK: usize = 50_000_000; +/// Most distances from a point to a piece of outline the shapes of one document are measured +/// with, all together ([`ThicknessBudget::document`]). +pub const MAX_DOCUMENT_THICKNESS_WORK: usize = 1_000_000_000; +/// The resolved outline is measured as line pieces within `width / FINE_PARTS` of its curves. +const FINE_PARTS: f64 = 32.0; +/// The first, rough look measures the path as drawn with pieces within `width / ROUGH_PARTS`. +const ROUGH_PARTS: f64 = 8.0; + +/// Is the fill of `path` (every subpath closed, as a fill paints it) under `rule` thinner than +/// `width` everywhere: does no circle of diameter `width` fit inside it? A path with no fill is. +/// A shape within a small fraction of `width` of the limit is taken as thick enough. +/// +/// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't +/// finite, the fill can't be resolved into outlines, or measuring it would take more than +/// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long. +pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option { + thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK)) +} + +/// The work left for measuring shapes with [`thinner_than_within`]: a count of distances from a +/// point to a piece of outline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ThicknessBudget(usize); + +impl ThicknessBudget { + pub fn new(work: usize) -> Self { + Self(work) + } + /// The work all the shapes of one document may take: [`MAX_DOCUMENT_THICKNESS_WORK`]. + pub fn document() -> Self { + Self(MAX_DOCUMENT_THICKNESS_WORK) + } + /// The work left. + pub fn left(&self) -> usize { + self.0 + } +} + +/// [`thinner_than`], taking the search's work from `budget`: `None` as well when the search needs +/// more than is left. The quick checks take nothing from it, so they still settle shapes once it +/// runs out. +pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: &mut ThicknessBudget) -> Option { + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if !(width.is_finite() && width > 0.0) + || !path.subpaths.iter().flat_map(|sp| &sp.anchors).all(|a| finite(a.p) && finite(a.h_in) && finite(a.h_out)) + { + return None; + } + // Every segment is at least one piece of outline, so a path of more anchors is too long to + // measure before its outline is built. + if path.subpaths.iter().map(|sp| sp.anchors.len()).sum::() > MAX_THICKNESS_PIECES { + return None; + } + let mut bp = fill_bezpath(path); + if bp.elements().is_empty() { + return Some(true); + } + // Measured from the corner of its bounds, so that a shape far from the origin measures as it + // does near it. + let corner = bp.bounding_box().origin(); + bp.apply_affine(Affine::translate(-corner.to_vec2())); + let b = bp.bounding_box(); + let (r, fine) = (width / 2.0, width / FINE_PARTS); + // A circle inside the fill is inside its bounds. Bounds within the fine measure's error of the + // width go on to that measure, which keeps them. + if b.width().min(b.height()) < width - 2.0 * fine { + return Some(true); + } + // Every point of a fill lies within the widest circle's radius r of its outline, and the points + // within r of a closed outline of length L cover at most 2rL + πr². A fill larger than that holds + // a circle of diameter `width`. Only one subpath filled nonzero that winds at most once around + // any point is measured so: the areas of several subpaths add up to more than their fill where + // they overlap, a path that runs around a spot twice counts its area there twice, and an + // even-odd fill of a path that runs around twice is empty. + if path.subpaths.len() == 1 + && rule == FillRule::NonZero + && winds_at_most_once(&bp) + && bp.area().abs() > 2.0 * r * bp.perimeter(1e-3) * 1.01 + std::f64::consts::PI * r * r + { + return Some(false); + } + // The circle lies between any two parallel lines that hold the path's points and handles too, + // which settles a long sliver lying on a slant. + if hull_width(&bp) < width - 2.0 * fine { + return Some(true); + } + // A rough look at the path as drawn: an edge running inside the fill is nearer than the fill's + // outline, so a spot this far from every edge (and from the rough pieces' error) is far enough. + let rough = width / ROUGH_PARTS; + let mut edges = vec![]; + if !flatten_into(&bp, rough, &mut edges) { + return None; + } + match search(&edges, b, rule, r + rough, rough, budget) { + Search::Found => return Some(false), + // Resolving the outlines takes time of its own, so it isn't started when what is left of + // the budget cut the rough look short. The rough look can run out where the resolved + // outline is much shorter, so one that ran out of its own share goes on. + Search::TooLong if budget.0 < MAX_WORK => return None, + _ => {} + } + // The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the + // fill are no outline of it. A spot within the fine pieces' error of the radius counts as one. + let contours = normalize_bez(&bp, rule).ok()?; + edges.clear(); + for c in contours.contours() { + if !flatten_into(&c.path, fine, &mut edges) { + return None; + } + } + if edges.is_empty() { + return Some(true); + } + match search(&edges, b, FillRule::EvenOdd, r - fine, fine, budget) { + Search::Found | Search::Unsure => Some(false), + Search::Absent => Some(true), + Search::TooLong => None, + } +} + +/// The points and handles of `bp`, in order. +fn control_points(bp: &BezPath) -> Vec { + bp.elements() + .iter() + .flat_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p], + PathEl::QuadTo(a, p) => vec![a, p], + PathEl::CurveTo(a, b, p) => vec![a, b, p], + PathEl::ClosePath => vec![], + }) + .collect() +} + +/// Does `bp`, one closed subpath, wind at most once around every point? Every line through a point +/// that a curve winds around twice crosses it at least four times, so such a curve turns through +/// at least 4π in all. A Bézier curve turns no more than its control polygon, so a control polygon +/// that turns through less than 4π winds at most once. +fn winds_at_most_once(bp: &BezPath) -> bool { + let mut pts = control_points(bp); + pts.dedup(); + while pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + if pts.len() < 3 { + return true; + } + let turned: f64 = pts + .iter() + .zip(pts.iter().cycle().skip(1)) + .zip(pts.iter().cycle().skip(2)) + .map(|((&a, &b), &c)| { + let (u, v) = (b - a, c - b); + u.cross(v).atan2(u.dot(v)).abs() + }) + .sum(); + turned < 4.0 * std::f64::consts::PI * (1.0 - 1e-9) +} + +/// Most corners of a convex hull [`hull_width`] measures; a larger hull measures as unbounded. +const MAX_HULL: usize = 512; + +/// The least distance between two parallel lines that hold every point and handle of `bp` (the +/// width of their convex hull, which holds the curves too). +fn hull_width(bp: &BezPath) -> f64 { + let mut pts = control_points(bp); + pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + pts.dedup(); + if pts.len() < 3 { + return 0.0; + } + // Andrew's monotone chain: the lower hull, then the upper. + let turn = |o: Point, a: Point, b: Point| (a - o).cross(b - o); + let mut hull: Vec = Vec::with_capacity(pts.len() + 1); + for pass in [false, true] { + let floor = hull.len(); + let ordered: Box> = if pass { Box::new(pts.iter().rev()) } else { Box::new(pts.iter()) }; + for &p in ordered { + while hull.len() >= floor + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(&o, &a)| turn(o, a, p) <= 0.0) { + hull.pop(); + } + hull.push(p); + } + hull.pop(); + } + if hull.len() < 3 { + return 0.0; + } + if hull.len() > MAX_HULL { + return f64::INFINITY; + } + // For each side, the farthest corner from its line; the least of those is the width. + let mut least = f64::INFINITY; + for (&a, &b) in hull.iter().zip(hull.iter().cycle().skip(1)) { + let side = b - a; + let len = side.hypot(); + if len > 0.0 { + let far = hull.iter().map(|&p| side.cross(p - a).abs() / len).fold(0.0, f64::max); + least = least.min(far); + } + } + least +} + +/// Add `bp`'s outline to `edges` as line pieces within `tolerance` of it: false when that takes +/// more than [`MAX_THICKNESS_PIECES`], or when a curve is too long for [`vectorcraft_geom::flatten`] +/// to keep within `tolerance`. +fn flatten_into(bp: &BezPath, tolerance: f64, edges: &mut Vec<(Point, Point)>) -> bool { + let push = |from: Point, to: Point, edges: &mut Vec<(Point, Point)>| { + if from != to { + edges.push((from, to)); + } + }; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + let most = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE; + for el in bp.iter() { + if edges.len() > MAX_THICKNESS_PIECES { + return false; + } + match el { + // An outline that doesn't end where it starts is closed with a line, as a fill paints it. + PathEl::MoveTo(p) => { + push(last, start, edges); + (start, last) = (p, p); + } + PathEl::ClosePath => { + push(last, start, edges); + last = start; + } + PathEl::LineTo(p) => { + push(last, p, edges); + last = p; + } + PathEl::QuadTo(a, p) | PathEl::CurveTo(a, _, p) => { + let length = match el { + PathEl::CurveTo(_, b, _) => last.distance(a) + a.distance(b) + b.distance(p), + _ => last.distance(a) + a.distance(p), + }; + if length / most > tolerance { + return false; + } + let mut from = last; + vectorcraft_geom::flatten([PathEl::MoveTo(last), el], tolerance, |piece| { + if let PathEl::LineTo(to) = piece { + push(from, to, edges); + from = to; + } + }); + last = p; + } + } + } + push(last, start, edges); + edges.len() <= MAX_THICKNESS_PIECES +} + +/// The distance from `p` to the nearest of `edges`, negative outside the region they bound under +/// `rule`. +fn signed_distance(edges: &[(Point, Point)], rule: FillRule, p: Point) -> f64 { + let mut winding = 0i32; + let mut nearest = f64::INFINITY; + for &(a, b) in edges { + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + winding += if b.y > a.y { 1 } else { -1 }; + } + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + nearest = nearest.min((p - (a + ab * t)).hypot2()); + } + let inside = match rule { + FillRule::NonZero => winding != 0, + FillRule::EvenOdd => winding % 2 != 0, + }; + let d = nearest.sqrt(); + if inside { d } else { -d } +} + +/// A square cell of the search: its center, half its side, the signed distance from its center to +/// the outline, and the most that distance can be anywhere in it. +struct Cell { + c: Point, + h: f64, + d: f64, + most: f64, +} + +impl PartialEq for Cell { + fn eq(&self, other: &Self) -> bool { + self.most.total_cmp(&other.most) == Ordering::Equal + } +} + +impl Eq for Cell {} + +impl PartialOrd for Cell { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Cell { + fn cmp(&self, other: &Self) -> Ordering { + self.most.total_cmp(&other.most) + } +} + +/// What [`search`] found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Search { + /// A point at least the distance asked for from the outline. + Found, + /// No such point. + Absent, + /// None found, but cells smaller than the finest size could still hold one. + Unsure, + /// The search needed more cells or distances than it may take. + TooLong, +} + +/// Look for a point inside the region `edges` bound under `rule` (within `bounds`) at least `goal` +/// from its outline. The bounds are cut into square cells, and the cell that could hold the farthest +/// point is split first, until a cell's center is `goal` away or no cell could be. The distance +/// changes no faster than the point moves, so a cell holds no point farther than its center's +/// distance plus half its diagonal. Cells smaller than `finest` are not split further. The +/// distances it measures, no more than [`MAX_WORK`], are taken from `budget`. +fn search(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, goal: f64, finest: f64, budget: &mut ThicknessBudget) -> Search { + let mut work = 0usize; + let found = search_up_to(edges, bounds, rule, (goal, finest), budget.0.min(MAX_WORK), &mut work); + budget.0 = budget.0.saturating_sub(work); + found +} + +/// [`search`], measuring no more than `limit` distances and counting them in `work`. +fn search_up_to(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, (goal, finest): (f64, f64), limit: usize, work: &mut usize) -> Search { + let side = bounds.width().min(bounds.height()); + if side.is_nan() || side <= 0.0 { + return Search::Absent; + } + let (cols, rows) = ((bounds.width() / side).ceil(), (bounds.height() / side).ceil()); + if cols * rows > MAX_CELLS as f64 || cols * rows * edges.len() as f64 > limit as f64 { + return Search::TooLong; + } + let cell = |c: Point, h: f64, work: &mut usize| { + *work += edges.len(); + let d = signed_distance(edges, rule, c); + Cell { c, h, d, most: d + h * std::f64::consts::SQRT_2 } + }; + let mut heap = BinaryHeap::new(); + let h = side / 2.0; + for i in 0..cols as usize { + for j in 0..rows as usize { + heap.push(cell(Point::new(bounds.x0 + (i as f64 + 0.5) * side, bounds.y0 + (j as f64 + 0.5) * side), h, work)); + } + } + let (mut made, mut unsure) = (heap.len(), false); + while let Some(next) = heap.pop() { + if next.d >= goal { + return Search::Found; + } + if next.most < goal { + break; + } + if next.h < finest / 2.0 { + unsure = true; + continue; + } + if made + 4 > MAX_CELLS || work.saturating_add(4 * edges.len()) > limit { + return Search::TooLong; + } + let h = next.h / 2.0; + for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { + let part = cell(Point::new(next.c.x + dx, next.c.y + dy), h, work); + // A cell that can't hold a point `goal` away is left out. + if part.most >= goal { + heap.push(part); + } + } + made += 4; + } + if unsure { Search::Unsure } else { Search::Absent } +} + +#[cfg(test)] +mod tests { + use vectorcraft_geom::{Anchor, SubPath}; + + use super::*; + + fn polygon(points: &[(f64, f64)]) -> SubPath { + SubPath::new(points.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true) + } + + fn one(points: &[(f64, f64)]) -> PathData { + PathData::single(polygon(points)) + } + + fn thin(p: &PathData, rule: FillRule, width: f64) -> bool { + thinner_than(p, rule, width) == Some(true) + } + + fn thick(p: &PathData, rule: FillRule, width: f64) -> bool { + thinner_than(p, rule, width) == Some(false) + } + + #[test] + fn a_triangle_whose_third_anchor_almost_meets_its_first_is_thinner_than_a_hairline() { + let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); + assert!(thin(&sliver, FillRule::NonZero, 0.085)); + // Long and on a slant at the narrowest width, and far from the origin. + assert!(thin(&one(&[(0.0, 0.0), (600.0, 600.0), (0.0, 0.0001)]), FillRule::NonZero, 0.001)); + let (x, y) = (1_000_000.0, 1_000_000.0); + assert!(thin(&one(&[(x, y), (x + 0.01, y + 0.0075), (x + 0.0001, y + 0.0002)]), FillRule::NonZero, 0.001)); + } + + #[test] + fn a_bent_sliver_is_found_by_measuring_inside_it() { + // Out along two sides of a triangle and back 0.002 pt inside them: its hull and bounds are + // wide, and only the measure inside finds it thin. + let v = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]); + assert!(thin(&v, FillRule::NonZero, 0.085)); + } + + #[test] + fn a_narrow_strip_wider_than_the_width_is_kept_and_one_narrower_is_not() { + // A diagonal strip 100 pt long. + let strip = |w: f64| { + let (dx, dy) = (0.6 * w, -0.8 * w); + one(&[(0.0, 0.0), (80.0, 60.0), (80.0 + dx, 60.0 + dy), (dx, dy)]) + }; + assert!(thick(&strip(0.2), FillRule::NonZero, 0.085)); + assert!(thick(&strip(0.2), FillRule::NonZero, 0.18)); + assert!(thin(&strip(0.05), FillRule::NonZero, 0.085)); + assert!(thin(&strip(0.2), FillRule::NonZero, 0.24)); + } + + #[test] + fn a_triangle_holding_the_circle_off_every_cell_center_is_kept() { + // Its inscribed circle is 2 across, centered at (1, 1). + let t = one(&[(0.0, 0.0), (4.0, 0.0), (0.0, 3.0)]); + assert!(thick(&t, FillRule::NonZero, 1.95)); + assert!(thin(&t, FillRule::NonZero, 2.3)); + } + + #[test] + fn a_tiny_round_dot_is_kept() { + let dot = vectorcraft_geom::shapes::ellipse(kurbo::Rect::new(10.0, 10.0, 10.3, 10.3)); + assert!(thick(&dot, FillRule::NonZero, 0.085)); + assert!(thick(&dot, FillRule::NonZero, 0.29)); + assert!(thin(&dot, FillRule::NonZero, 0.4)); + } + + #[test] + fn a_thin_ring_is_thin_whichever_way_its_subpaths_run() { + let square = |x0: f64, x1: f64| polygon(&[(x0, x0), (x1, x0), (x1, x1), (x0, x1)]); + let mut hole = square(1.01, 98.99); + hole.reverse(); + assert!(thin(&PathData::new(vec![square(1.0, 99.0), hole]), FillRule::NonZero, 0.085)); + // Even-odd: an inner square running the same way still cuts a hole. + assert!(thin(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::EvenOdd, 0.085)); + // Nonzero: it doesn't, and the edges inside the fill are no outline of it. + assert!(thick(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::NonZero, 0.085)); + } + + #[test] + fn overlapping_strips_are_measured_by_their_union() { + // Two strips 0.2 pt tall overlapping by half: their fill is 0.3 pt tall, while the edges of + // each that run inside the other are no more than 0.1 pt apart. + let strip = |y: f64| polygon(&[(0.0, y), (100.0, y), (100.0, y + 0.2), (0.0, y + 0.2)]); + let strips = PathData::new(vec![strip(0.0), strip(0.1)]); + assert!(thick(&strips, FillRule::NonZero, 0.15)); + assert!(thin(&strips, FillRule::NonZero, 0.35)); + } + + #[test] + fn an_outline_out_and_back_along_itself_has_no_fill_and_is_thin() { + assert!(thin(&one(&[(0.0, 0.0), (30.0, 40.0), (0.0, 0.0), (30.0, 40.0)]), FillRule::NonZero, 0.085)); + assert!(thin(&PathData::default(), FillRule::NonZero, 0.085)); + } + + /// Shapes thicker than the width by their area, and slivers lying flat along an axis, are settled + /// without resolving their outlines, so a document of thousands of them is measured quickly. + #[test] + fn plain_shapes_and_flat_slivers_are_settled_without_resolving_their_outlines() { + let before = crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()); + for k in 0..2000 { + let x = f64::from(k) * 12.0; + assert!(thick(&one(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]), FillRule::NonZero, 0.085)); + assert!(thin(&one(&[(x, 20.0), (x + 10.0, 20.0), (x + 10.0, 20.01), (x, 20.01)]), FillRule::NonZero, 0.085)); + // Long slivers on a slant are settled by the width of their hull. + assert!(thin(&one(&[(x, 40.0), (x + 9.0, 52.0), (x + 0.001, 40.0015)]), FillRule::NonZero, 0.085)); + } + assert_eq!(crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()), before); + } + + /// The area measure is used only for an outline that runs around once: one that runs around + /// twice counts its area twice. + #[test] + fn an_outline_that_runs_around_twice_is_not_measured_by_its_area() { + let square = |n: usize| { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for _ in 0..n { + for p in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] { + bp.line_to(p); + } + } + bp.close_path(); + bp + }; + assert!(winds_at_most_once(&square(1))); + assert!(!winds_at_most_once(&square(2))); + // Measured inside instead, a square run around twice is still as thick as one. + let twice = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + assert!(thick(&twice, FillRule::NonZero, 0.085)); + } + + /// Shapes that need the search share one budget: once it is spent they can't be measured, and + /// the quick checks still settle the rest. + #[test] + fn a_spent_budget_leaves_the_shapes_that_need_a_search_unmeasured() { + let bent = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]); + let square = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let mut budget = ThicknessBudget::document(); + assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut budget), Some(true)); + assert!(budget.left() < MAX_DOCUMENT_THICKNESS_WORK); + let mut spent = ThicknessBudget::new(0); + assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut spent), None); + assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false)); + } + + #[test] + fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() { + let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); + for w in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(thinner_than(&sliver, FillRule::NonZero, w), None, "{w}"); + } + let flat = one(&[(0.0, 0.0), (f64::NAN, 0.0), (40.0, 0.0)]); + assert_eq!(thinner_than(&flat, FillRule::NonZero, 0.085), None); + } +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6fd3009921..e568c0f7c8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -21,7 +21,16 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let linked = d.fields.get("__rowGutterLinked").is_some() && d.fields.get("__rowGutterLinked") == d.fields.get("rowGutter"); let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k)); - form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit()); + // Hairline Slivers' widths show in the stroke unit (Preferences › Units › Stroke), or in + // points when that unit's field rounds the narrowest width to 0. + let unit = match command.as_str() { + "object.path.cleanUp" | "select.object.hairlineSlivers" => { + let stroke = app.session.stroke_unit(); + if stroke.number(*vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE.start()) == "0" { vectorcraft_doc::Unit::Points } else { stroke } + } + _ => app.session.general_unit(), + }; + form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, unit); if command == crate::addons::packaging::SET_ROLE_SWATCH { crate::addons::packaging::follow_role(app, d); } @@ -154,6 +163,8 @@ fn lengths(command: &str) -> &'static [&'static str] { crate::addons::cutting::BRIDGES => &["width"], "object.textWrap.options" => &["offset"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"], + "object.path.cleanUp" => &["sliverWidth"], + "select.object.hairlineSlivers" => &["width"], _ => &[], } } @@ -168,6 +179,7 @@ pub(super) fn length_range(command: &str, key: &str) -> Option { Some(0.0..=vectorcraft_engine::MAX_COORD) } + ("object.path.cleanUp", "sliverWidth") | ("select.object.hairlineSlivers", "width") => Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE), _ => None, } } @@ -192,6 +204,7 @@ fn order(command: &str) -> &'static [&'static str] { crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], + "object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"], _ => &[], } } diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 3e68b98c92..474fea5063 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -260,7 +260,17 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Divide Objects Below", "object.path.divideObjectsBelow"), c("Split Into Grid…", "object.path.splitIntoGrid"), Sep, - cp("Clean Up…", "object.path.cleanUp", json!({"strayPoints": true, "unpaintedObjects": true, "emptyTextPaths": true})), + cp( + "Clean Up…", + "object.path.cleanUp", + json!({ + "strayPoints": true, + "unpaintedObjects": true, + "emptyTextPaths": true, + "hairlineSlivers": false, + "sliverWidth": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH + }), + ), ], ), sub("Shape", vec![c("Convert to Shape", "object.shape.convertToShape"), c("Expand Shape", "object.expandShape")]), @@ -538,6 +548,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Clipping Masks", "select.object.clippingMasks"), c("Slices", "select.object.slices"), c("Stray Points", "select.object.strayPoints"), + cp("Hairline Slivers…", "select.object.hairlineSlivers", json!({"width": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH})), c("Open Paths", "select.object.openPaths"), c("Not Aligned to Pixel Grid", "select.object.notAlignedToPixelGrid"), Sep, diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..b9dc1a4087 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7204,6 +7204,24 @@ the dialog on those settings next time. `"joins": 3`, `"rows": "many"` or `"addGuides": "yes"`, and change nothing. A distance still takes a string with a unit (`"5 mm"`). `joins` must be `miter`, `round` or `bevel`. Omitting a param or giving null keeps its default. +`object.path.cleanUp` with `hairlineSlivers: true` also removes hairline slivers: closed paths and compound paths with +a visible fill, no visible stroke and no effect, so thin that no circle `sliverWidth` across fits inside their fill +(Unpainted Objects covers shapes with no paint). A compound path is measured as one fill, so a compound path with one +sliver member and one real shape stays. `sliverWidth` is a distance from 0.001 to 3 pt; it defaults to 0.03 mm, +VectorCraft's own value, and `hairlineSlivers` is off by default. In the desktop app the Clean Up dialog has a Hairline +Slivers checkbox and a Sliver Width field, shown in the stroke unit, or in points when that unit's field would round +0.001 pt to 0. `select.object.hairlineSlivers {width?}` (Select › Object › Hairline Slivers…) selects the objects Clean +Up would remove, only inside the isolated group while one is isolated, and replies `{count, warning?}`. Neither command +takes hidden or locked objects, objects in template layers, art on locked artboards, guides, the clipping paths of +groups and layers, shapes with an effect, or the members of Live Paint groups and other live or generated art. A shape +that holds a circle 15/16 of the width across is kept too. A shape too complex to measure is kept as well, and so is +every shape still unmeasured when one run reaches its limit of work; the reply's `warning` says how many there were: + +```json +{"name":"run_command","arguments":{"command":"object.path.cleanUp","params":{"strayPoints":false,"unpaintedObjects":false,"emptyTextPaths":false,"hairlineSlivers":true,"sliverWidth":"0.03 mm"}}} +{"name":"run_command","arguments":{"command":"select.object.hairlineSlivers","params":{"width":0.1}}} +``` + ## Smooth `object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..8df165d8d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1675,6 +1675,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Geometry and effects:** - **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged. - Pathfinder (10 exact curve booleans; single-result shape operations retain source names and SVG IDs, #1293), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. With one group selected alone, the Pathfinder panel's buttons work on its members (among other selected objects a group still acts as one shape), and a greyed-out button says what it needs (#1450; behaviour reference: [combine objects using Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html); one plain path selected alone stays disabled, which the documentation doesn't settle). Split Into Grid takes the number, height or width, gutter and total of the rows and of the columns, Add Guides and Preview, and several selected paths become one grid painted as the topmost one (#1462, `object.path.splitIntoGrid`; behaviour reference: [divide or split objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/divide-or-split-objects.html); a typed height or width keeps the gutter and changes the total, our choice). Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635). + Clean Up has a Hairline Slivers option, VectorCraft's own and off by default: it removes closed paths and compound paths with a visible fill, no visible stroke and no effect when no circle as wide as its Sliver Width (0.03 mm by default) fits inside their fill, and Select › Object › Hairline Slivers… selects them (`crates/engine/src/tests/pathops.rs`, `crates/pathops/src/thickness.rs` tests). Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow. Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests). Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`). From 3c3f2e82b7c84341f3a71efeeb7cb882f6b0959e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:48:14 -0800 Subject: [PATCH 08/18] Clean Up: leave a shape unmeasured when resolving it would merge edges Resolving a fill's outlines snaps points within the sweep tolerance together, and that tolerance grows with the shape's size. For a shape large enough that the tolerance reaches the fine measure's error, the outline could collapse and the shape was reported as thinner than the width (a 1e12 by 0.0011 pt rectangle at 0.001 pt was removed although a 0.001 pt circle fits inside it). Such a shape is now not measured and is left as it is. --- crates/pathops/src/thickness.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/pathops/src/thickness.rs b/crates/pathops/src/thickness.rs index a4bffb998a..67771c66a3 100644 --- a/crates/pathops/src/thickness.rs +++ b/crates/pathops/src/thickness.rs @@ -7,7 +7,7 @@ use std::collections::BinaryHeap; use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _}; use vectorcraft_geom::{FillRule, PathData}; -use crate::boolean::{fill_bezpath, normalize_bez}; +use crate::boolean::{eps_for, fill_bezpath, normalize_bez}; /// Most line pieces the outline of one shape is measured with. pub const MAX_THICKNESS_PIECES: usize = 100_000; @@ -28,7 +28,8 @@ const ROUGH_PARTS: f64 = 8.0; /// A shape within a small fraction of `width` of the limit is taken as thick enough. /// /// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't -/// finite, the fill can't be resolved into outlines, or measuring it would take more than +/// finite, the fill can't be resolved into outlines (or only so coarsely, for a shape that large, +/// that edges closer than `width` would merge), or measuring it would take more than /// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long. pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option { thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK)) @@ -118,6 +119,11 @@ pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: } // The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the // fill are no outline of it. A spot within the fine pieces' error of the radius counts as one. + // The sweep snaps points within its tolerance together, which grows with the shape's size: one + // as coarse as the fine pieces could close up a fill that holds the circle, so it isn't measured. + if eps_for([&bp]).ok()? >= fine { + return None; + } let contours = normalize_bez(&bp, rule).ok()?; edges.clear(); for c in contours.contours() { @@ -545,6 +551,16 @@ mod tests { assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false)); } + /// A shape so long that resolving its outline snaps edges closer than the width together is not + /// measured, while the same height at an ordinary length is. + #[test] + fn a_shape_too_long_to_resolve_at_the_width_cannot_be_measured() { + let rect = |w: f64| one(&[(0.0, 0.0), (w, 0.0), (w, 0.0011), (0.0, 0.0011)]); + assert_eq!(thinner_than(&rect(1e12), FillRule::NonZero, 0.001), None); + assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.001), Some(false)); + assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.0012), Some(true)); + } + #[test] fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() { let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); From adf9fb23f6d60fb32964e4b9747f243176d22791 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:48:52 -0800 Subject: [PATCH 09/18] Color Wheel: Copy Color As does not report a copy without a window Without a window to copy through, a Copy Color As item still answers its text, puts nothing on the clipboard and leaves the status bar as it was. Before, the status bar said the color was copied. --- crates/ui-egui/src/panels/color_wheel.rs | 9 +++++---- crates/ui-egui/src/panels/tests_color_wheel_copy.rs | 11 +++++++++++ docs/mcp.md | 3 ++- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index f2208c9dad..9661c45a48 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -523,7 +523,9 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { /// Copy Color As: put `color.format`'s text in `notation` of the color the panel shows on the /// clipboard, with the opacity of what the row of Show Opacity edits when it has one, and say in /// the status bar what was copied. Without a solid color nothing is copied and the answer is -/// null; an error of `color.format` goes to the status bar. → `{text}`. +/// null; an error of `color.format` goes to the status bar. Without a window to copy through, +/// nothing is copied and the status bar stays as it was, and the answer still holds the text. +/// → `{text}`. pub(crate) fn copy_color_as(app: &mut VectorcraftApp, notation: &str) -> Result { let tgt = target_now(app); let Some(color) = tgt.color() else { return Ok(Value::Null) }; @@ -535,9 +537,8 @@ pub(crate) fn copy_color_as(app: &mut VectorcraftApp, notation: &str) -> Result< match app.run("color.format", p) { Ok(r) => { let text = r["text"].as_str().unwrap_or_default().to_string(); - if let Some(ctx) = &app.ui_ctx { - ctx.copy_text(text.clone()); - } + let Some(ctx) = &app.ui_ctx else { return Ok(json!({ "text": text })) }; + ctx.copy_text(text.clone()); app.status(format!("Copied the color as {text}")); Ok(json!({ "text": text })) } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_copy.rs b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs index f041b62d59..1ffd93f70e 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_copy.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs @@ -71,6 +71,17 @@ fn css_rgb_copies_the_color_and_the_opacity() { assert_eq!(undo_count(&app), before, "copying records no undo step"); } +/// Without a window to copy through, an item answers its text and the status bar does not say it +/// was copied. +#[test] +fn without_a_window_the_text_is_answered_and_not_reported_as_copied() { + let mut app = app(50.0); + app.ui_ctx = None; + app.ui.status.clear(); + assert_eq!(run(&mut app, "ui.colorWheel.copy.hex", &json!({})), Some(Ok(json!({"text": "#336699"})))); + assert_eq!(app.ui.status, ""); +} + /// Hex and CMYK Values never carry the opacity; Hex with Alpha always does, as `ff` at 100 %; CSS /// adds it only under 100 %. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0dfbf4b224..fd322eff7e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -769,7 +769,8 @@ rgb(), CSS hsl(), CSS oklch() or CMYK Values, the six `color.format` notations, edits when it has one (whether or not that row shows), and the status bar shows what was copied. Its items are the menu commands `ui.colorWheel.copy.hex`, `ui.colorWheel.copy.hexAlpha`, `ui.colorWheel.copy.rgb`, `ui.colorWheel.copy.hsl`, `ui.colorWheel.copy.oklch` and `ui.colorWheel.copy.cmyk`, which answer `{text}`, or null without a solid color. They are gray without a solid color, and CSS oklch() is also gray -while the working RGB space is not sRGB. +while the working RGB space is not sRGB. Without a window to copy through, an item puts nothing on the clipboard and +leaves the status bar as it was, and still answers `{text}`. 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 f78d37cc6e38868bfb6f30450c4d9d8a80a117fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:42:59 -0800 Subject: [PATCH 10/18] Color Wheel: Copy Color As tests run their frame through ui_context and part_frame --- crates/ui-egui/src/panels/tests_color_wheel_copy.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_color_wheel_copy.rs b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs index 1ffd93f70e..84001223ab 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_copy.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs @@ -32,11 +32,10 @@ fn app(opacity: f64) -> VectorcraftApp { /// Run Copy Color As › `notation` in one frame: its answer and the texts it put on the clipboard. fn copy(app: &mut VectorcraftApp, notation: &str) -> (Result, Vec) { - let ctx = egui::Context::default(); - app.ui_ctx = Some(ctx.clone()); + let ctx = crate::testing::ui_context(); let mut answer = None; - let mut out = ctx.run_ui(Default::default(), |_| answer = run(app, &format!("ui.colorWheel.copy.{notation}"), &json!({}))); - out.textures_delta.clear(); + let out = + crate::testing::part_frame(app, &ctx, Default::default(), |app, _| answer = run(app, &format!("ui.colorWheel.copy.{notation}"), &json!({}))); let copied = out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }).collect(); (answer.expect("a Copy Color As item"), copied) From 0f069375adc7d33271ddd059119bc2dd75cfb1f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:01:00 -0800 Subject: [PATCH 11/18] Docs: Copy Color As names the active document's RGB space for oklch() --- docs/mcp.md | 4 ++-- docs/target-app-parity.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index d1e7d17522..2896d38d60 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -748,7 +748,7 @@ angles and `none`, so `calc()`, `var()`, `color-mix()`, relative color syntax an 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 +Sliders lower it; `oklch()` is an error while the active document's RGB space (its assigned profile, else 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 @@ -772,7 +772,7 @@ rgb(), CSS hsl(), CSS oklch() or CMYK Values, the six `color.format` notations, edits when it has one (whether or not that row shows), and the status bar shows what was copied. Its items are the menu commands `ui.colorWheel.copy.hex`, `ui.colorWheel.copy.hexAlpha`, `ui.colorWheel.copy.rgb`, `ui.colorWheel.copy.hsl`, `ui.colorWheel.copy.oklch` and `ui.colorWheel.copy.cmyk`, which answer `{text}`, or null without a solid color. They are gray without a solid color, and CSS oklch() is also gray -while the working RGB space is not sRGB. Without a window to copy through, an item puts nothing on the clipboard and +while the active document's RGB space is not sRGB. Without a window to copy through, an item puts nothing on the clipboard and leaves the status bar as it was, and still answers `{text}`. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4ad112ed0d..b402a75623 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2041,7 +2041,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **HSL Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item HSL Sliders (`ui.colorWheel {sliders: "hsl"}`, kept with the preferences) shows H, S and L rows in place of OKLCH Sliders that edit the color by the hue (0 to 360°), saturation and lightness (0 to 100 %) of its display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes from display sRGB into the working RGB space as the wheel's picks do, and the rows keep the hue of a gray. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. Evidence: `hsl_follows_css_color_4` and `hsl_roundtrip` in `crates/color/src/lib.rs`; the HSL tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `a_gray_keeps_the_hsl_hue_it_was_given` among them. Scores and estimates are unchanged. - **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`. - **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. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). 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 row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {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 where that row is not gray (where it is gray, only the color is applied). `oklch()` is taken only while the working RGB space is sRGB. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`; `oklch()` only while the working RGB space is sRGB), and `color.parse` reads every form but the CMYK values back to the same color. 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` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.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 row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {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 where that row is not gray (where it is gray, only the color is applied). `oklch()` is taken only while the active document's RGB space (its assigned profile, else the working RGB space) is sRGB. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`; `oklch()` only while the active document's RGB space is sRGB), and `color.parse` reads every form but the CMYK values back to the same color. 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` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.rs`. Scores and estimates are unchanged. The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). From 91e54b669ed43ea3eb41051db9f82925c982dbad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 17:16:09 -0800 Subject: [PATCH 12/18] Clean Up: Hairline Slivers' widths use the stroke unit in the framework dialog The parameter dialog on main builds its rows through the craft UI framework, so the unit rule for the Hairline Slivers width rows moves there: `Setting` carries the stroke unit's `LengthUnits` for `object.path.cleanUp` and `select.object.hairlineSlivers`, or points when the stroke unit rounds 0.001 pt to 0. --- crates/ui-egui/src/canvas/rulers.rs | 2 +- crates/ui-egui/src/dialogs/command.rs | 33 ++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/rulers.rs b/crates/ui-egui/src/canvas/rulers.rs index 34a6a223b9..a72e55995f 100644 --- a/crates/ui-egui/src/canvas/rulers.rs +++ b/crates/ui-egui/src/canvas/rulers.rs @@ -62,7 +62,7 @@ pub(crate) fn units() -> &'static [UnitKind] { } /// Lengths stored in points and shown in `unit`, a bare number read as Numbers Without Units Are Points says. -fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits { +pub(crate) fn lengths(app: &VectorcraftApp, unit: Unit) -> LengthUnits { crate::fields::bare_points( LengthUnits::new(UnitKind::Points, unit_kind(unit), PIXELS_PER_INCH), app.session.prefs.numbers_without_units_are_points, diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index e2bb683ddd..6d8741d342 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -59,6 +59,9 @@ struct Open { struct Setting { cmyk: bool, units: LengthUnits, + /// Hairline Slivers' widths: the stroke unit (Preferences › Units › Stroke), or points when + /// that unit's field rounds the narrowest width to 0. + sliver_units: LengthUnits, } impl Setting { @@ -67,8 +70,23 @@ impl Setting { cmyk: app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk), // PLAN: assumed `canvas::rulers::general_lengths(&VectorcraftApp) -> LengthUnits` (cv.B5) units: crate::canvas::rulers::general_lengths(app), + sliver_units: crate::canvas::rulers::lengths(app, sliver_unit(app.session.stroke_unit())), } } + + /// The length units of `command`'s distance rows. + fn units_for(self, command: &str) -> LengthUnits { + match command { + "object.path.cleanUp" | "select.object.hairlineSlivers" => self.sliver_units, + _ => self.units, + } + } +} + +/// The unit Hairline Slivers' widths show in for the stroke unit `stroke`: `stroke`, or points +/// when `stroke` rounds the narrowest width to 0. +fn sliver_unit(stroke: vectorcraft_doc::Unit) -> vectorcraft_doc::Unit { + if stroke.number(*vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE.start()) == "0" { vectorcraft_doc::Unit::Points } else { stroke } } /// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the @@ -283,7 +301,7 @@ fn row(command: &str, key: &str, value: &Value, setting: Setting) -> Option Date: Sat, 28 Nov 2026 19:41:34 -0800 Subject: [PATCH 13/18] =?UTF-8?q?Drag=20and=20drop:=20panel=20drags=20held?= =?UTF-8?q?=20across=20File=20=E2=80=BA=20Revert=20are=20not=20dropped=20o?= =?UTF-8?q?n=20the=20restored=20drawing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #9931 refused an appearance carried across File › Revert. Graphic styles, brushes, symbols, swatch rows and appearance stack rows had the same fault: a held drag still resolved a name or id against the restored contents. - Graphic style, brush, symbol and swatch drags carry the document's revert count, and the canvas, the panels, the Fill/Stroke wells and the Gradient slider refuse a drag from before the revert. - The Brushes panel shows no reorder marker for a stale brush drag. - docs/mcp.md says which drops File › Revert cancels. Follows #9931 by @dotCooCoo. --- crates/ui-egui/src/canvas/drops.rs | 31 +++-- crates/ui-egui/src/canvas/drops/tests.rs | 111 ++++++++++++++++-- crates/ui-egui/src/panel_drag.rs | 17 ++- crates/ui-egui/src/panels.rs | 68 ++++++++++- crates/ui-egui/src/panels/appearance.rs | 3 +- crates/ui-egui/src/panels/appearance/tests.rs | 36 ++++++ crates/ui-egui/src/panels/brushes.rs | 26 ++-- crates/ui-egui/src/panels/brushes/tests.rs | 7 +- crates/ui-egui/src/panels/gradient.rs | 2 + crates/ui-egui/src/panels/graphic_styles.rs | 52 ++++++-- crates/ui-egui/src/panels/swatches.rs | 16 ++- crates/ui-egui/src/panels/swatches/dnd.rs | 10 +- crates/ui-egui/src/panels/swatches/tests.rs | 49 +++++++- crates/ui-egui/src/panels/symbols.rs | 20 +++- docs/mcp.md | 3 +- 15 files changed, 384 insertions(+), 67 deletions(-) diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index c15a150d31..1200db46de 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -120,9 +120,11 @@ pub(crate) struct CanvasDrops<'a> { kind: BodyKind, /// The uid of the document the canvas shows. document: u64, - /// The revert count of the document the canvas shows: an appearance dragged from contents File › Revert replaced is - /// refused. + /// The revert count of the document the canvas shows: an appearance, graphic style or brush dragged from contents + /// File › Revert replaced is refused. reverts: u64, + /// `(uid, reverts)` of every open document: a symbol dragged from contents File › Revert replaced is refused. + contents: Vec<(u64, u64)>, /// `(uid, revision)` of every open document: carried art whose source is not listed unchanged is refused. sources: Vec<(u64, u64)>, /// Whether the art being carried is taken though its source's revision moved: its move was given up and the source @@ -176,12 +178,17 @@ impl Component for CanvasDrops<'_> { let panel = Target::new(rect, view, covered, |p: &PanelDrag| match p { PanelDrag::Art { .. } => None, PanelDrag::Appearance { .. } if p.appearance_for(self.document, self.reverts).is_none() => None, + _ if p.stale_rows(Some((self.document, self.reverts))) => None, _ => Some(Payload::Panel(p.clone())), }); - let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); - let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); + let here = (self.document, self.reverts); + let style = Target::new(rect, view, covered, |d: &StyleDrag| ((d.document, d.reverts) == here).then(|| Payload::Style(d.clone()))); + // A symbol of any open document's current contents. + let symbol = Target::new(rect, view, covered, |d: &ListDrag| { + self.contents.contains(&(d.grabbed.doc, d.grabbed.reverts)).then(|| Payload::Symbol(d.grabbed.clone())) + }); let brush = Target::new(rect, view, covered, |d: &ListDrag| { - (d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone())) + ((d.grabbed.doc, d.grabbed.reverts) == here).then(|| Payload::Brush(d.grabbed.clone())) }); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); @@ -222,6 +229,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi BodyKind::Pane => pane_view(app, win, rect), }; let (Some(view), Some((document, reverts))) = (view, app.session.documents().get(win.0).map(|d| (d.uid, d.reverts))) else { return }; + let contents = app.session.documents().iter().map(|d| (d.uid, d.reverts)).collect(); let sources = app.session.documents().iter().map(|d| (d.uid, d.revision)).chain(app.canvas.panes.released_from).collect(); // A tab rest leaves the art to the document it showed while that is the current one: any canvas or pane takes it // then, and nothing once that document was closed or left by other means. @@ -234,7 +242,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kind: BodyKi let ctx = ui.ctx().clone(); let covered = |at: Pos2| crate::panel_docking::os_window_at(app, &ctx, at); let files = (CanvasFiles::new(app, rect, &view), &files_out); - let drops = CanvasDrops { common: Common::new(), view, kind, document, reverts, sources, given_up, covered: &covered, out: &out, files }; + let drops = + CanvasDrops { common: Common::new(), view, kind, document, reverts, contents, sources, given_up, covered: &covered, out: &out, files }; drops.id_salt(("canvas-drops", win)).show_at(ui, rect); if let Some(files) = files_out.take() { crate::place::canvas_drop(app, ui.ctx(), files); @@ -330,6 +339,8 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), ) } } + // A symbol of contents File › Revert replaced places nothing. + Payload::Symbol(key) if !app.session.documents().iter().any(|d| (d.uid, d.reverts) == (key.doc, key.reverts)) => Ok(()), Payload::Symbol(key) => run(app, "symbol.placeFromDocument", json!({"sourceDocument": key.doc, "name": key.name, "x": at.x, "y": at.y})), Payload::Library(key) if key.folder => Ok(()), Payload::Library(key) => match library_panel::parse(&key.panel) { @@ -346,7 +357,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => { run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]})) } - Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() { + Payload::Brush(key) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (key.doc, key.reverts)) => match hit() { None if brush_has_art(app, key) && no_art_at(app, at, zoom) => { run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})) } @@ -357,12 +368,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), } }, Payload::Brush(_) => Ok(()), - Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { + Payload::Style(style) if app.session.active().is_some_and(|st| (st.uid, st.reverts) == (style.document, style.reverts)) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } Payload::Style(_) => Ok(()), + // Swatch rows of contents File › Revert replaced apply and place nothing. + Payload::Panel(drag @ PanelDrag::Paint { .. }) if drag.stale_rows(app.session.active().map(|st| (st.uid, st.reverts))) => Ok(()), // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile art with its tile. Payload::Panel(PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) if hit().is_none() && no_art_at(app, at, zoom) => @@ -385,7 +398,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), { return Err(tl!("A linked color swatch can only be applied in its own document.").into()); } - let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) }; + let Some(mut params) = drag.paint_drop_params(app.session.active().map(|st| (st.uid, st.reverts))) else { return Ok(()) }; params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 9803cb73b6..8b3fb8e91f 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -68,7 +68,7 @@ fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() { let before = fill(&app); let history = undo_len(&app); let at = Point::new(250.0, 70.0); - let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() }); + let payload = Payload::Style(StyleDrag { document, reverts: 0, name: "Shared name".into() }); for operation in [DropOperation::Move, DropOperation::Copy] { drop_at(&mut app, payload.clone(), at, operation).unwrap(); assert_eq!(fill(&app), before); @@ -135,7 +135,7 @@ fn a_drop_runs_the_effect_of_its_payload() { assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays"); let st = app.session.active().unwrap(); let name = st.doc.graphic_styles[2].name.clone(); - let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() }); + let style = Payload::Style(StyleDrag { document: st.uid, reverts: st.reverts, name: name.clone() }); drop_at(&mut app, style.clone(), on_b, Move).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id)); @@ -165,7 +165,7 @@ fn a_drop_runs_the_effect_of_its_payload() { let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone()); let uid = app.session.active().unwrap().uid; - let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, name: name.into(), group: false }); + let brush = |name: &str| Payload::Brush(BrushKey { doc: uid, reverts: 0, name: name.into(), group: false }); let library = |kind: &str, id: &str, name: &str| { Payload::Library(LibraryKey { panel: library_panel::panel_id(kind, id), name: name.into(), folder: false }) }; @@ -200,7 +200,7 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, library(SymbolLibraries::KIND, "basic-shapes", "Star"), on_b, Move).unwrap(); assert_eq!(undo_len(&app), n + 1, "a library symbol is added and placed in one step"); symbol_at(&app, on_b); - drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, name: "Star".into() }), empty, Move).unwrap(); + drop_at(&mut app, Payload::Symbol(SymbolKey { doc: uid, reverts: 0, name: "Star".into() }), empty, Move).unwrap(); symbol_at(&app, empty); } @@ -215,8 +215,13 @@ fn a_brush_with_art_dropped_inside_a_fill_with_path_only_places_nothing() { app.run("prefs.set", json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); let uid = app.session.active().unwrap().uid; let n = undo_len(&app); - drop_at(&mut app, Payload::Brush(BrushKey { doc: uid, name: "Arrow".into(), group: false }), Point::new(300.0, 240.0), DropOperation::Move) - .unwrap(); + drop_at( + &mut app, + Payload::Brush(BrushKey { doc: uid, reverts: 0, name: "Arrow".into(), group: false }), + Point::new(300.0, 240.0), + DropOperation::Move, + ) + .unwrap(); assert_eq!(undo_len(&app), n, "{}", app.ui.status); } @@ -233,7 +238,7 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { app.run("select.none", json!({})).unwrap(); let document = app.session.active().unwrap().uid; let swatch = |name: &str, paint: Paint| { - let rows = SwatchRows { document, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + let rows = SwatchRows { document, reverts: 0, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; Payload::Panel(PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }) }; let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); @@ -281,7 +286,7 @@ fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() { let before = brush_of(&app); assert!(before.is_none()); let history = undo_len(&app); - let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false }); + let payload = Payload::Brush(BrushKey { doc: document, reverts: 0, name: "Shared Brush".into(), group: false }); drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap(); assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone"); drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap(); @@ -301,7 +306,7 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); frame(&mut app, &ctx, vec![]); - let key = |doc| Payload::Symbol(SymbolKey { doc, name: "Leaf".into() }); + let key = |doc| Payload::Symbol(SymbolKey { doc, reverts: 0, name: "Leaf".into() }); let at = Point::new(250.0, 180.0); let n = undo_len(&app); drop_at(&mut app, key(source), at, DropOperation::Move).unwrap(); @@ -329,7 +334,14 @@ fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let rows = SwatchRows { + document: source.uid, + reverts: source.reverts, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: true, + }; let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; let local_target = add_target(&mut app); @@ -720,3 +732,82 @@ fn an_appearance_drop_after_file_revert_leaves_the_restored_object_unchanged() { panel.release(); assert_eq!(fill(&panel.app()), red, "a drag started after the revert copies the appearance"); } + +/// A graphic style, brush or symbol held across File › Revert, released on art on the canvas, makes no edit to the +/// restored contents, both where the canvas takes the drop and where the drop is applied. The same drag started after +/// the revert still applies or places it. +#[test] +fn a_style_brush_or_symbol_held_across_file_revert_is_not_dropped_on_the_canvas() { + use crate::tests::panel_harness::Panel; + use craft::ui::runtime::drag; + + fn beside_canvas(app: &mut VectorcraftApp, ui: &mut egui::Ui, panel: fn(&mut VectorcraftApp, &mut egui::Ui)) { + app.sync_views(); + egui::Panel::top("source panel").exact_size(220.0).show(ui, |ui| panel(app, ui)); + canvas::show(app, ui); + } + fn styles(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + beside_canvas(app, ui, crate::panels::graphic_styles::show); + } + fn brushes(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + beside_canvas(app, ui, crate::panels::brushes::show); + } + fn symbols(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + beside_canvas(app, ui, crate::panels::symbols::show); + } + + type Show = fn(&mut VectorcraftApp, &mut egui::Ui); + let panels: [(&str, Show); 3] = [("style", styles), ("brush", brushes), ("symbol", symbols)]; + for (kind, show) in panels { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap(); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + match kind { + "style" => app.run("graphicStyle.new", json!({"name": "Held"})).map(drop), + "brush" => app + .run("brush.new", json!({"name": "Held", "type": "art"})) + .and_then(|_| app.run("brush.setCurrent", json!({"name": null})).map(drop)), + _ => app.run("symbol.new", json!({"name": "Held"})).map(drop), + } + .unwrap(); + app.run("path.create", json!({"anchors": [{"x": 200, "y": 150}, {"x": 380, "y": 150}]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("canvas-panel-item-drop-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.ellipse", json!({"x": 20, "y": 250, "width": 20, "height": 20})).unwrap(); + app.run("select.none", json!({})).unwrap(); + + let mut panel = Panel::new(app, show); + let hold = |panel: &mut Panel| { + let from = panel.rect("Held").center(); + let to = panel.app().canvas_view().unwrap().to_screen(Point::new(290.0, 150.0)); + panel.drag_hold_between(from, to); + }; + hold(&mut panel); + assert!(drag::mark(panel.ctx()).is_some(), "{kind}: the canvas takes it from the current contents"); + let opening = panel.app().session.active().map(|st| (st.uid, st.reverts)).unwrap(); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.frame(); + assert_eq!(panel.app().session.active().map(|st| (st.uid, st.reverts)), Some((opening.0, opening.1 + 1))); + let history = undo_len(&panel.app()); + assert!(drag::mark(panel.ctx()).is_none(), "{kind}: the canvas refuses it once the contents it came from are gone"); + panel.release(); + assert_eq!(undo_len(&panel.app()), history, "{kind}: the stale drop makes no edit"); + + let stale = match kind { + "style" => Payload::Style(StyleDrag { document: opening.0, reverts: opening.1, name: "Held".into() }), + "brush" => Payload::Brush(BrushKey { doc: opening.0, reverts: opening.1, name: "Held".into(), group: false }), + _ => Payload::Symbol(SymbolKey { doc: opening.0, reverts: opening.1, name: "Held".into() }), + }; + drop_at(&mut panel.app(), stale, Point::new(290.0, 150.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(&panel.app()), history, "{kind}: a stale payload that reaches the drop is not applied"); + + hold(&mut panel); + panel.release(); + assert_eq!(undo_len(&panel.app()), history + 1, "{kind}: a drag started after the revert is still dropped"); + } +} diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 587da09f84..dbf6f92e6b 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -46,6 +46,8 @@ pub enum PanelDrag { pub struct SwatchRows { /// The document whose rows the drag started on. pub document: u64, + /// The document's revert count: rows held across File › Revert name swatches of contents that are gone. + pub reverts: u64, pub grabbed: String, pub names: Vec, /// The names are colour groups. @@ -90,13 +92,24 @@ impl PanelDrag { } } + /// Whether the drag carries swatch rows of `current` (`(uid, reverts)` of the active document) from before + /// File › Revert: their names may now stand for other swatches, so a drop of them applies nothing. + pub(crate) fn stale_rows(&self, current: Option<(u64, u64)>) -> bool { + matches!(self, Self::Paint { rows: Some(r), .. } if current.is_some_and(|(uid, reverts)| uid == r.document && reverts != r.reverts)) + } + /// A named process swatch follows the source drawing's swatch. In another drawing its - /// captured process color applies without using a same-name swatch there. - pub(crate) fn paint_drop_params(&self, destination: Option) -> Option { + /// captured process color applies without using a same-name swatch there. Swatch rows of the destination's + /// contents from before File › Revert apply nothing. + pub(crate) fn paint_drop_params(&self, destination: Option<(u64, u64)>) -> Option { + if self.stale_rows(destination) { + return None; + } let Self::Paint { paint, params, rows, .. } = self else { return None }; if params.is_null() { return None; } + let destination = destination.map(|d| d.0); if let Some(rows) = rows.as_ref().filter(|rows| rows.unlinked_process_color) && destination.is_some_and(|uid| uid != rows.document) && let Some(color) = paint.color() diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 10172f2c5a..ca2f7cbcbc 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -754,12 +754,13 @@ pub(crate) fn proxy(app: &mut VectorcraftApp, ui: &mut Ui) { }; let wells = [well(tl!("Fill"), &fill, mixed.0), well(tl!("Stroke"), &stroke, mixed.1).ring(true)]; let active = if app.session.fill_active { Well::Primary } else { Well::Secondary }; + let current = app.session.active().map(|st| (st.uid, st.reverts)); let out = SwatchPair::new(tl!("Fill and Stroke"), wells, Bind::given(active)) .swap_button(tl!("Swap Fill and Stroke")) .default_button(tl!("Default Fill and Stroke")) .popover(false) .drags([Some(PanelDrag::paint(fill)), Some(PanelDrag::paint(stroke))]) - .accepts(move |well, drag| takes_drop(mixed, well, drag)) + .accepts(move |well, drag| takes_drop(mixed, well, drag) && !drag.stale_rows(current)) .show(ui); proxy_events(app, &out); if let Some((well, drag)) = &out.dropped { @@ -813,7 +814,7 @@ fn drop_paint(app: &mut VectorcraftApp, well: Well, drag: &PanelDrag) { app.status(tl!("A linked color swatch can only be applied in its own document.")); return; } - if let Some(params) = drag.paint_drop_params(destination) { + if let Some(params) = drag.paint_drop_params(app.session.active().map(|st| (st.uid, st.reverts))) { let cmd = if well == Well::Primary { "paint.setFill" } else { "paint.setStroke" }; app.run(cmd, params).ok(); } @@ -1125,6 +1126,50 @@ mod tests { assert_eq!(current_paints(&app).0.color().map(|c| c.to_hex()), Some("#00ff00".into())); } + /// A swatch row held across File › Revert and dropped on a Fill/Stroke well applies nothing to the restored + /// drawing; the same drop from the current contents still applies. + #[test] + fn a_proxy_drop_of_a_swatch_row_held_across_file_revert_applies_nothing() { + use crate::panel_drag::SwatchRows; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let name = "Held Swatch"; + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("proxy-swatch-drop-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + let drag = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let paint = st.doc.swatch(name).unwrap().paint.clone(); + let rows = SwatchRows { + document: st.uid, + reverts: st.reverts, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + }; + PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None } + }; + app.run("swatch.edit", json!({"name": name, "color": "#00ff00"})).unwrap(); + let held = drag(&app); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let before = current_paints(&app).0; + let undo = app.session.active().unwrap().history.undo.len(); + drop_paint(&mut app, Well::Primary, &held); + assert_eq!(current_paints(&app).0, before, "the stale swatch row paints nothing"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the stale drop makes no edit"); + + let fresh = drag(&app); + drop_paint(&mut app, Well::Primary, &fresh); + assert_eq!(current_paints(&app).0, app.session.active().unwrap().doc.swatch(name).unwrap().paint, "a fresh drag applies"); + } + #[test] fn proxy_drops_keep_the_dragged_process_color_after_switching_documents() { use crate::panel_drag::SwatchRows; @@ -1136,7 +1181,14 @@ mod tests { app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let rows = SwatchRows { + document: source.uid, + reverts: source.reverts, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: true, + }; let drag = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); drop_paint(&mut app, Well::Primary, &drag); @@ -1164,8 +1216,14 @@ mod tests { app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = - SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + let rows = SwatchRows { + document: source.uid, + reverts: source.reverts, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + }; let drag = PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }; if different_drawing { app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 3d95d2c28d..4e04758c7d 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -438,7 +438,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let order = rows.keys(); let sel = current_sel(app, node.as_deref()); let mut selection = node.as_deref().map_or_else(Selection::default, |n| list_selection(app, n, sel)); - let document = app.session.active().map(|st| st.uid); + // The list is keyed by the document's contents: rows held across File › Revert name items of contents that are gone. + let document = app.session.active().map(|st| (st.uid, st.reverts)); let list_id = ui.scope_id().with(("appearance-rows", document)); let has = node.is_some(); // A dragged fill/stroke or effect row lights Duplicate and Delete up, also with nothing picked. diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 1447ede3a8..534e78d1e8 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -613,6 +613,42 @@ fn the_selection_summary_is_reused_until_the_document_or_its_subjects_change() { assert!(fresh_summary(&mut app).mixed(&app).is_some_and(|m| !m.transparency), "the first document's again"); } +/// A fill row held across File › Revert and released on Duplicate Selected Item leaves the restored object's +/// appearance as it is; the same drag started after the revert still duplicates the row. +#[test] +fn an_appearance_row_held_across_file_revert_is_not_dropped_on_the_footer() { + use craft::ui::runtime::drag; + + let mut app = app_with_a_selected_rectangle(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let id = app.session.active().unwrap().selection.objects[0]; + let folder = vectorcraft_testkit::TempDir::new("appearance-rows-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let items = |panel: &Panel| node(&panel.app()).appearance.items.len(); + + let mut panel = Panel::new(app, show); + let hold = |panel: &mut Panel| { + let (from, to) = (panel.rect("Fill").center(), panel.rect("Duplicate Selected Item").center()); + panel.drag_hold_between(from, to); + }; + hold(&mut panel); + assert!(drag::mark(panel.ctx()).is_some(), "Duplicate Selected Item takes rows of the current contents"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({ "ids": [id.0] })).unwrap(); + panel.frame(); + let before = items(&panel); + assert!(drag::mark(panel.ctx()).is_none(), "the footer refuses rows of the contents File › Revert replaced"); + panel.release(); + assert_eq!(items(&panel), before, "the stale row duplicates nothing"); + + hold(&mut panel); + panel.release(); + assert_eq!(items(&panel), before + 1, "a drag started after the revert still duplicates the row"); +} + /// The panel's subject is the `Arc` the document holds for the selected object, a targeted group /// or a targeted layer, not a copy of it; nothing with nothing selected. #[test] diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 205a18ac05..7c1d4cfa96 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -312,6 +312,8 @@ pub(crate) struct BrushesView { pub(crate) struct BrushKey { /// The uid of the document whose brush it is: a drag from another document's panel names another brush. pub doc: u64, + /// The document's revert count: a drag held across File › Revert names a brush of contents that are gone. + pub reverts: u64, /// The brush's name, or the group's type. pub name: String, /// Whether the row is a type's group. @@ -319,15 +321,15 @@ pub(crate) struct BrushKey { } impl BrushKey { - fn brush(doc: u64, name: &str) -> Self { - Self { doc, name: name.to_string(), group: false } + fn brush((doc, reverts): (u64, u64), name: &str) -> Self { + Self { doc, reverts, name: name.to_string(), group: false } } } /// The panel's rows: a group per shown type in [`KINDS`] order, without the `hidden` types, each over its brushes of /// `shown` in library order. Of two brushes with one name only the first, the one a stroke that names it draws with, /// has a row, so row keys stay unique. -fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec> { +fn rows(doc: (u64, u64), shown: &[Shown], hidden: &[String]) -> Vec> { let first = by_name(shown); let mut rows = Vec::new(); for (ty, label) in KINDS.iter().filter(|(ty, _)| !hidden.iter().any(|h| h == ty)) { @@ -335,7 +337,7 @@ fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec if of_type.is_empty() { continue; } - rows.push(PresetRow::group(BrushKey { doc, name: ty.to_string(), group: true }, tl!(label), 0)); + rows.push(PresetRow::group(BrushKey { doc: doc.0, reverts: doc.1, name: ty.to_string(), group: true }, tl!(label), 0)); rows.extend(of_type.into_iter().map(|b| PresetRow::item(BrushKey::brush(doc, &b.name), b.name.clone(), 1))); } rows @@ -346,6 +348,7 @@ fn rows(doc: u64, shown: &[Shown], hidden: &[String]) -> Vec #[derive(MemoProps)] struct BrushSource<'a> { uid: u64, + reverts: u64, revision: u64, #[memo_props(covered_by = "revision", reason = "a document version's brushes and resources are fixed")] doc: Option<&'a Document>, @@ -356,8 +359,11 @@ struct BrushSource<'a> { /// The panel's presets: [`rows`]; a brush moves only among those of its type, and paints its stroke preview. fn brush_source(inputs: BrushSource<'_>) -> PresetSource<'_, BrushKey> { - let fns = PresetFns::, BrushKey>::new(|s, _| rows(s.uid, s.shown, &s.hidden)) + let fns = PresetFns::, BrushKey>::new(|s, _| rows((s.uid, s.reverts), s.shown, &s.hidden)) .accepts(|s, drag, over, _| { + if (drag.grabbed.doc, drag.grabbed.reverts) != (s.uid, s.reverts) { + return false; + } let first = by_name(s.shown); over.and_then(|over| type_of(&first, over)).is_some_and(|ty| type_of(&first, &drag.grabbed) == Some(ty)) }) @@ -531,7 +537,7 @@ fn names_of(sel: &Selection, doc: u64) -> Selection { } /// The keys of the brushes `sel` names in the document `doc`. -fn keys_of(sel: &Selection, doc: u64) -> Selection { +fn keys_of(sel: &Selection, doc: (u64, u64)) -> Selection { let key = |name: &String| BrushKey::brush(doc, name); Selection::new(sel.items.iter().map(key).collect(), sel.lead.as_ref().map(key), sel.anchor.as_ref().map(key)) } @@ -558,8 +564,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let sel_brush = selected_brush(app); let highlighted = sel_brush.clone().or_else(|| current.clone()); let given = match &multi { - Some(sel) => keys_of(sel, uid), - None => highlighted.as_deref().map(|name| Selection::single(BrushKey::brush(uid, name))).unwrap_or_default(), + Some(sel) => keys_of(sel, (uid, reverts)), + None => highlighted.as_deref().map(|name| Selection::single(BrushKey::brush((uid, reverts), name))).unwrap_or_default(), }; let hidden = app.ui.brushes_view.hidden.clone(); let view = if app.ui.brushes_view.list { PresetView::List } else { PresetView::Grid }; @@ -572,7 +578,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }; let ctx = ui.ctx().clone(); let (doc, first, multi_ref, list_ref) = (doc.as_deref(), &first, multi.as_ref(), list.as_slice()); - let source = brush_source(BrushSource { uid, revision, doc, shown: &memo, hidden: hidden.clone() }); + let source = brush_source(BrushSource { uid, reverts, revision, doc, shown: &memo, hidden: hidden.clone() }); let browser = |ui: &mut Ui| { let mut state = PresetState::new(); let ctx = ctx.clone(); @@ -639,7 +645,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } PresetEvent::Menu { target, command, .. } => item_command(app, &target, &command, multi.as_ref()), - PresetEvent::Reorder(edit) => move_brush(app, &rows(uid, &memo, &hidden), first, &edit), + PresetEvent::Reorder(edit) => move_brush(app, &rows((uid, reverts), &memo, &hidden), first, &edit), PresetEvent::Dropped { at, payload, .. } => { if let (DropAt::Onto(key), Some(ids)) = (&at, payload.get::().and_then(|p| art_of(p, uid, reverts))) { crate::dialogs::brush_replace_art::replace(app, &key.name, &ids); diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index 501bd051cd..cd922c895e 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -533,7 +533,8 @@ fn a_brush_dragged_onto_another_of_its_type_moves_before_it() { let mut t = Trial::new(); let app = t.app(); let st = app.session.active().unwrap(); - let order: Vec = rows(st.uid, &document_brushes(st), &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.label).collect(); + let order: Vec = + rows((st.uid, st.reverts), &document_brushes(st), &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.label).collect(); drop(app); assert_eq!(order[..4], ["3 pt. Round", "6 pt. Flat", "10 pt. Oval", "Dots"]); let undo = |t: &Trial| undo_count(&t.app()); @@ -886,8 +887,8 @@ fn rows_of_two_brushes_with_one_name_show_the_first() { let shown = by_name(&raw)["Twin"]; assert_eq!(shown.ty, "art"); assert_eq!(shown.def, got, "the first of two rows of one name is the one shown"); - let keys: Vec = rows(st.uid, &raw, &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.key).collect(); - assert_eq!(keys, [BrushKey::brush(st.uid, "Twin")], "one row, under the first one's type"); + let keys: Vec = rows((st.uid, st.reverts), &raw, &[]).into_iter().filter(|row| !row.is_group()).map(|row| row.key).collect(); + assert_eq!(keys, [BrushKey::brush((st.uid, st.reverts), "Twin")], "one row, under the first one's type"); } /// A brush's menu acts on it alone, or on the multi-selection when the brush is one of several diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index ce32696fce..c75d2f7c80 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -846,7 +846,9 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra open_popover(app, request.index, at); } // A colour swatch dropped on the slider: a global or spot colour (or a tint of one) stays linked. + // Swatch rows held across File › Revert change no stop. if let Some((place, drag)) = &out.dropped + && !drag.stale_rows(app.session.active().map(|st| (st.uid, st.reverts))) && let Some(c) = drag.color() { let link = match drag { diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 76b17c33be..c102a1ecdc 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -56,10 +56,11 @@ use crate::panel_drag::PanelDrag; /// A style of the panel: its name, which is unique in a document. pub(crate) type StyleKey = String; -/// A document's graphic style dragged out to the canvas. +/// A document's graphic style dragged out to the canvas. `reverts` identifies the contents it came from. #[derive(Clone, Debug)] pub(crate) struct StyleDrag { pub(crate) document: u64, + pub(crate) reverts: u64, pub(crate) name: StyleKey, } @@ -481,8 +482,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (alt, linked) = (alt_held(ui), app.session.selection_graphic_style().is_some()); let thumbs = style_thumbs(app, &doc, &looks, panel.preview); let source = style_source(thumbs); - // The browser's own state (an open rename field, the scroll position) is kept per document. - let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid)); + // The browser's own state (an open rename field, the scroll position) is kept per document contents: a style + // dragged from contents File › Revert replaced is not this list's. + let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid, reverts)); let list = PresetBrowser::::list_id(browser_id); let takes_object = move |drag: &PanelDrag, _: &DropAt| dropped_object(drag, uid, reverts).is_some(); // A style dragged from this panel's list. @@ -524,16 +526,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .selection(Bind::bound(&mut panel.selection)) .view_lock(view.preset_view()) .reorder(PresetReorder::items()) - .drag_payload(move |drag: &ListDrag| Some(StyleDrag { document: uid, name: drag.grabbed.clone() })) + .drag_payload(move |drag: &ListDrag| Some(StyleDrag { document: uid, reverts, name: drag.grabbed.clone() })) .empty(tl!("Select styled art and click New Graphic Style.")) .row_items(items) .tip(|ui, key| large_tip(app, &thumbs, ui, key)) .takes_drop(PresetDrop::new::(DropPlace::Between, takes_object)) .takes_drop(PresetDrop::new::(DropPlace::Onto, takes_object)) - .takes_drop(PresetDrop::new::>( - DropPlace::Onto, - |drag, at| matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)), - )) + .takes_drop(PresetDrop::new::>(DropPlace::Onto, move |drag, at| { + ours(drag) && matches!(at, DropAt::Onto(name) if !drag.keys.contains(name)) + })) .show(ui) }) }; @@ -1612,6 +1613,41 @@ mod tests { assert_eq!(names(&p.app()).len(), before.len() + 1, "a thumbnail drag started after the revert still makes a style"); } + /// A style of the list held across File › Revert and released on New Graphic Style duplicates no style of the + /// restored contents; the same drag started after the revert still duplicates it. + #[test] + fn a_style_held_across_file_revert_is_not_dropped_on_the_footer() { + use crate::tests::panel_harness::Panel as PanelHarness; + use craft::ui::runtime::drag; + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Held"})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("graphic-styles-footer-revert"); + let path = folder.join("drawing.vectorcraft"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string()))); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + + let mut p = PanelHarness::new(app, show); + let hold = |p: &mut PanelHarness| { + let (from, to) = (p.rect("Held").center(), p.rect("New Graphic Style (Alt-click to name it)").center()); + p.drag_hold_between(from, to); + }; + hold(&mut p); + assert!(drag::mark(p.ctx()).is_some(), "New Graphic Style takes a style of the current contents"); + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.frame(); + let before = names(&p.app()); + assert!(drag::mark(p.ctx()).is_none(), "New Graphic Style refuses a style of the contents File › Revert replaced"); + p.release(); + assert_eq!(names(&p.app()), before, "the stale drop duplicates nothing"); + + hold(&mut p); + p.release(); + assert_eq!(names(&p.app()).len(), before.len() + 1, "a drag started after the revert still duplicates the style"); + } + /// A style dropped on another with Alt takes that style's look; on itself it does nothing. #[test] fn a_style_dropped_on_another_with_alt_replaces_that_style() { diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index a179e07a53..4664017868 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -418,7 +418,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let state = &mut model.state; // The browser fills the room the footer leaves, so the footer stays in view under the swatches. The body can run // more than once in a pass, so each run builds its own browser. A list drag is keyed by its browser ID. Each - // document has its own browser. + // document's contents have their own browser, so rows held across File › Revert are not this list's. let mut footed = None; let out = Stack::new() .label(tl!("Swatches")) @@ -428,7 +428,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let dragged_doc = Arc::clone(&doc); let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc) }; let browser = SwatchesPanel::new(&data, Bind::bound(&mut *state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) + .drag_payload(move |drag: &ListDrag| { + Some(dnd::drag_of(&dragged_doc, (document, reverts), &drag.grabbed, dragged_rows(drag))) + }) .thumb(thumbs, thumb) .row_icons(|key| match key { SwatchKey::Swatch(name) => row_icons(shown_app, name), @@ -441,7 +443,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .search(search) .reveal(focus.clone().map(SwatchKey::Swatch)) .footer(None); - ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner + ui.push_id(("swatch-rows", document, reverts), |ui| browser.show(ui)).inner }) .inner; app.ui.swatches_panel = model; @@ -790,7 +792,8 @@ struct Footer { opts: Option, group: Option, libraries_open: bool, - document: Option, + /// The uid and revert count of the document the panel shows. + document: Option<(u64, u64)>, } impl Footer { @@ -803,7 +806,7 @@ impl Footer { Footer { kind: model.kind, libraries_open: library_panel::any_open::(&app.ui), - document: app.session.active().map(|state| state.uid), + document: app.session.active().map(|state| (state.uid, state.reverts)), sel, del, opts, @@ -815,7 +818,8 @@ impl Footer { fn show(&self, ui: &mut Ui) -> FooterOutput { let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); let document = self.document; - let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); + let rows_drag = + move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some((rows.document, rows.reverts)) == document); let edit = if self.group.is_some() { FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) } else { diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 6ff3420571..ebc0370b48 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -4,10 +4,10 @@ use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; -/// Swatches take paints, and take swatch rows or canvas art from the current document. +/// Swatches take paints, and take swatch rows or canvas art from the current document's current contents. pub(super) fn accepts(drag: &PanelDrag, document: u64, reverts: u64) -> bool { match drag { - PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document, + PanelDrag::Paint { rows: Some(rows), .. } => (rows.document, rows.reverts) == (document, reverts), PanelDrag::Paint { .. } => true, _ => drag.artwork_for(document, reverts).is_some(), } @@ -52,7 +52,7 @@ impl Drop { /// The drag a row of `key` starts, moving rows `names`. Colour groups have no paint of their own /// (the chip under the pointer draws Registration's mark for Registration). -pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec) -> PanelDrag { +pub(super) fn drag_of(d: &Document, (document, reverts): (u64, u64), key: &SwatchKey, names: Vec) -> PanelDrag { let name = name_of(key); let (paint, params, unlinked_process_color) = match key { SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name), false), @@ -65,7 +65,7 @@ pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec (Paint::None, Value::Null, false), }; - let rows = SwatchRows { document, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)), unlinked_process_color }; + let rows = SwatchRows { document, reverts, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)), unlinked_process_color }; PanelDrag::Paint { paint, params, rows: Some(rows), library: None } } @@ -126,7 +126,7 @@ pub(super) enum FooterTarget { /// the button does. Other drags are left to their own targets. pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) { let PanelDrag::Paint { rows: Some(r), .. } = drag else { return }; - if !app.session.active().is_some_and(|state| state.uid == r.document) { + if !app.session.active().is_some_and(|state| (state.uid, state.reverts) == (r.document, r.reverts)) { return; } let rows = footer_rows(app, r); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 617fb83a35..6e6630f17f 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -96,7 +96,7 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) { /// The drag the row `name` starts, carrying rows `names`. fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag { - let document = app.session.active().unwrap().uid; + let document = app.session.active().map(|st| (st.uid, st.reverts)).unwrap(); dnd::drag_of(&doc(app), document, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) } @@ -157,6 +157,53 @@ fn a_swatch_row_drag_reorders_only_its_source_document() { assert_eq!(names_of(&panel.app(), None), before_source); } +/// Swatch rows held across File › Revert move nothing in the restored swatches, and drop nothing on New Swatch or +/// Delete Swatch; the same drag started after the revert still moves them. +#[test] +fn a_swatch_row_drag_held_across_file_revert_moves_nothing() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let folder = vectorcraft_testkit::TempDir::new("swatch-rows-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("shape.ellipse", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap(); + let stale = rows_drag(&app, "Red", &["Red"]); + let before = names_of(&app, None); + + let mut panel = Panel::new(app, show); + let drag_red = |panel: &mut Panel| { + let red = "Red, #ed1c24"; + let from = panel.rect(red).center(); + let to = panel.rect("Green, #39b54a").center(); + panel.drag_hold_role(red, Role::LIST_ITEM, to - from); + }; + drag_red(&mut panel); + assert!(drag::mark(panel.ctx()).is_some(), "the list takes rows of the current contents"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.frame(); + assert!(drag::mark(panel.ctx()).is_none(), "the list refuses rows of the contents File › Revert replaced"); + panel.release(); + assert_eq!(names_of(&panel.app(), None), before, "the stale rows move nothing"); + + let restored = doc(&panel.app()); + let undo = undo_steps(&panel.app()); + for target in [dnd::FooterTarget::New, dnd::FooterTarget::Delete] { + dnd::on_footer_drop(&mut panel.app(), target, &stale); + assert_eq!(doc(&panel.app()), restored); + assert_eq!(undo_steps(&panel.app()), undo); + assert!(!dialog_open(&panel.app(), crate::dialogs::confirm::KIND)); + } + + drag_red(&mut panel); + panel.release(); + assert_ne!(names_of(&panel.app(), None), before, "a drag started after the revert still moves the rows"); +} + #[test] fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 11f805bad5..c257f30d0a 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -58,6 +58,8 @@ fn thumb_px(size: f32, pixels_per_point: f32) -> u32 { pub(crate) struct SymbolKey { /// The uid of the document whose Symbols panel showed the symbol. pub doc: u64, + /// The document's revert count: a drag held across File › Revert names a symbol of contents that are gone. + pub reverts: u64, /// The symbol's name. pub name: String, } @@ -496,6 +498,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { #[derive(MemoProps)] struct SymbolSource<'a> { uid: u64, + reverts: u64, revision: u64, #[memo_props(covered_by = "revision", reason = "a document version's symbols are fixed")] doc: &'a Document, @@ -506,7 +509,11 @@ struct SymbolSource<'a> { /// The panel's presets: a row per symbol of the document, in its order, each with its thumbnail. fn symbol_source(inputs: SymbolSource<'_>) -> PresetSource<'_, SymbolKey> { let fns = PresetFns::, SymbolKey>::new(|s, _| { - s.doc.symbols.iter().map(|sym| PresetRow::item(SymbolKey { doc: s.uid, name: sym.name.clone() }, sym.name.clone(), 0)).collect() + s.doc + .symbols + .iter() + .map(|sym| PresetRow::item(SymbolKey { doc: s.uid, reverts: s.reverts, name: sym.name.clone() }, sym.name.clone(), 0)) + .collect() }) .thumb(|s, cx, rect, info| paint_symbol(cx, rect, s.doc, s.keys, &info.key.name)); PresetSource::new(inputs, fns) @@ -540,8 +547,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let marked = marked(app); let inst = has_instances_selected(app); let linked = linked_symbols(app); - let key = |name: &str| SymbolKey { doc: uid, name: name.to_string() }; - let source = symbol_source(SymbolSource { uid, revision, doc: &doc, keys: &keys }); + let key = |name: &str| SymbolKey { doc: uid, reverts, name: name.to_string() }; + let source = symbol_source(SymbolSource { uid, reverts, revision, doc: &doc, keys: &keys }); // The symbols drawn selected: the ones Select All Unused picked, which further picks change, // else the current one. let (mut selection, select) = if marked.is_empty() { @@ -552,8 +559,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let (view, zoom) = app.ui.symbols_view.preset(); let browser_id = ui.make_persistent_id("symbols-browser"); let list = PresetBrowser::::list_id(browser_id); - // A symbol dragged from this panel's list, of the document it shows. - let ours = move |drag: &ListDrag| drag.list == list && drag.grabbed.doc == uid; + // A symbol dragged from this panel's list, of the contents of the document it shows. + let ours = move |drag: &ListDrag| drag.list == list && (drag.grabbed.doc, drag.grabbed.reverts) == (uid, reverts); let svg = |name: &'static str| IconSpec::svg(IconId::new(name)); let actions = [ FooterAction::new(svg("library"), tl!(SymbolLibraries::MENU)) @@ -656,7 +663,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(out) = footer else { return }; match &out.dropped { Some(dropped) => { - let Some(drag) = dropped.payload::>() else { return }; + // A symbol of other contents, another document's or the ones File › Revert replaced, drops nothing. + let Some(drag) = dropped.payload::>().filter(|drag| ours(drag)) else { return }; let name = &drag.grabbed.name; // A symbol deleted while it was dragged drops nothing. if !doc.symbols.iter().any(|s| s.name == *name) { diff --git a/docs/mcp.md b/docs/mcp.md index 32d41a1c4a..98ec4fae71 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5807,7 +5807,8 @@ Their OK runs `brush.new {type, name, params, ids?}`, and Cancel adds no brush. `brush.placeArt {name, x?, y?}` places a copy of the art a scatter, art or pattern brush is made of, centered on (`x`, `y`) (default: the center of the first artboard), and selects it, in one undo step. The app runs it when a brush is dragged from the Brushes panel onto an empty part of the canvas; dropped on a path, a brush is applied to it -(`brush.apply`). A pattern brush places its tiles left to right, 10 pt apart, in the order side, outer corner, inner +(`brush.apply`). A brush, graphic style, symbol, swatch or appearance whose drag started before File › Revert is not +dropped on the restored drawing. A pattern brush places its tiles left to right, 10 pt apart, in the order side, outer corner, inner corner, start, end (only the tiles it has art for), each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile. A tile with a repeat frame has an unpainted rectangle at the back of its group that marks the frame. A symbol instance in the art is measured by its symbol's art. A calligraphic or bristle brush is refused From b8daf6ff2cbafaafc8e289782922208be31f1852 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 20:03:00 -0800 Subject: [PATCH 14/18] Global Edit: the preview after an edit compares only the changed objects again With one object selected, the canvas highlights the objects Start Global Edit would take. After every edit the engine reduced each candidate in the document to its form again, measured its bounds twice, and made the outline of each highlighted object again. The forms, bounds and outlines are now kept by node between calls. An edit replaces each node it changes, so after an edit only the replaced nodes are measured again. Bounds of objects that hold symbol instances are not kept. The outline pass finds each object, its selected ancestors and its layer color in one walk down its index path. The new test counts the forms and outlines made: 40 and 39 for the first preview of 40 squares, then 1 and 0 after the selected square moves. --- crates/engine/src/cmd/globaledit.rs | 194 +++++++++++++++++++++++--- crates/engine/src/doc_state.rs | 4 + crates/engine/src/tests/globaledit.rs | 37 +++++ 3 files changed, 214 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 660df05f71..4f498e972a 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -91,6 +91,8 @@ //! deselects it as before), Global Edit ends when fewer than two members are left, and leaving //! one out is not an undo step. +use std::sync::Arc; + use serde::Serialize; use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer}; @@ -214,8 +216,18 @@ struct Form { frame: Affine, } +#[cfg(test)] +thread_local! { + /// Tests: how many times [`Form::of`] reduced an object to its form on this thread. + pub(crate) static FORMS_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread. + pub(crate) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + impl Form { fn of(n: &Node) -> Option { + #[cfg(test)] + FORMS_MADE.with(|c| c.set(c.get() + 1)); let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY }; f.add(n, 0)?; let first = *f.points.first()?; @@ -450,8 +462,8 @@ fn matches(s: &Session, o: &Options) -> Result> { ), }; let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center()); - let in_scope = |n: &Node| { - let Some(b) = n.geometric_bounds_with(&symbols) else { return false }; + let in_scope = |b: Option| { + let Some(b) = b else { return false }; if !d.artboards.iter().any(|a| on(a.rect, b)) { return o.include_canvas; } @@ -459,14 +471,16 @@ fn matches(s: &Session, o: &Options) -> Result> { }; // A copy that lies the same way has the size of the selected object when their boxes are as // wide and as high; a turned copy, when the transform that lays the object on it doesn't scale. - let same_size = |n: &Node, xf: Affine, turned: bool| { + let same_size = |b: Option, xf: Affine, turned: bool| { if turned { close(xf.determinant().abs().sqrt(), 1.0) } else { - matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)) + matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height())) } }; let mut out = vec![(*id, Affine::IDENTITY)]; + let mut cache = st.global_edit_forms.0.borrow_mut(); + let mut pass = cache.forms.pass(); super::select::walk_selectable(d, st.isolation, |n| { if n.id == *id || out.len() >= MAX_MEMBERS { return false; @@ -482,21 +496,134 @@ fn matches(s: &Session, o: &Options) -> Result> { _ => false, }; // The object count first: it turns most objects down before their form is made. - if n.children().map(Vec::len) == count - && let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n)) - && (!o.size || same_size(n, xf, turned)) - && (!o.appearance || same_look(key, n)) - && in_scope(n) - { - out.push((n.id, xf)); - // A group taken is taken whole, as compound paths, symbol instances and the others are. - return false; + if n.children().map(Vec::len) != count { + return look_in; + } + let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None }); + if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) { + let b = seen.bounds(n, &symbols); + if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) { + out.push((n.id, xf)); + // A group taken is taken whole, as compound paths, symbol instances and the others are. + return false; + } } look_in }); + cache.forms.end(pass, d); Ok(out) } +/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to +/// the next so that after an edit only the objects the edit replaced are measured again. A clone +/// starts empty. +#[derive(Default)] +pub struct FormCache(std::cell::RefCell); + +#[derive(Default)] +struct FormCacheInner { + forms: ByNode, + /// The outline of each highlighted object, or `None` when it has none and its box is shown. + outlines: ByNode>, +} + +/// An object as [`matches`] found it. +struct Seen { + /// Its form, or `None` when Global Edit doesn't support it. + form: Option
, + /// Its geometric bounds, once measured; not kept for an object with symbol instances, whose + /// bounds follow the symbols' art. + bounds: Option>, +} + +impl Seen { + fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option { + if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) { + return n.geometric_bounds_with(symbols); + } + *self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols)) + } +} + +/// Values found for nodes of a document, by node address. The layers they were found in are held, +/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so +/// no other node can have that address while its entry is here. +struct ByNode { + layers: Vec>, + values: ByAddress, +} + +impl Default for ByNode { + fn default() -> Self { + Self { layers: vec![], values: ByAddress::default() } + } +} + +/// Values by node address. +type ByAddress = std::collections::HashMap>; + +/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low +/// half (addresses are aligned, so their low bits are always the same). +#[derive(Default)] +struct AddressHasher(u64); + +impl std::hash::Hasher for AddressHasher { + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3); + } + } + + fn write_usize(&mut self, n: usize) { + let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15); + self.0 = x ^ (x >> 32); + } + + fn finish(&self) -> u64 { + self.0 + } +} + +/// One walk of a document: the values it asks for, taken from the ones kept or found anew. +struct Pass { + old: ByAddress, + new: ByAddress, +} + +impl Pass { + fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T { + let at = std::ptr::from_ref(n) as usize; + let old = &mut self.old; + self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find)) + } +} + +impl ByNode { + fn pass(&mut self) -> Pass { + let old = std::mem::take(&mut self.values); + Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old } + } + + /// Keep the values `pass` asked for, found in `d`. + fn end(&mut self, pass: Pass, d: &Document) { + self.values = pass.new; + self.layers.clone_from(&d.layers); + } +} + +impl Clone for FormCache { + fn clone(&self) -> Self { + Self::default() + } +} + +impl std::fmt::Debug for FormCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let c = self.0.borrow(); + f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish() + } +} + fn can_toggle(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.global_edit.is_some() { @@ -935,20 +1062,45 @@ pub fn similar(s: &Session) -> Outlines { /// selected object, in their layer's color. fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines { let symbols = st.doc.symbol_boxes(); - members + let mut cache = st.global_edit_forms.0.borrow_mut(); + let mut pass = cache.outlines.pass(); + let out = members .iter() .filter_map(|(id, _)| { - let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?; - if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) { - return None; + // One look-up of the object's place, then down through its layers and groups: none of + // them may be selected, and the innermost layer gives the color. + let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None); + for i in st.doc.index_path(*id)? { + let c: &Node = nodes.get(i)?; + if st.selection.objects.contains(&c.id) { + return None; + } + if c.is_layer() { + layer = Some(c); + } + if let Some(ch) = c.children() { + nodes = ch; + } + found = Some(c); } - let path = match n.stroke_path() { - Some(p) => p, + let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?; + let color = match layer.map(|l| &l.kind) { + Some(NodeKind::Layer { color, .. }) => color.rgb(), + _ => vectorcraft_doc::LAYER_COLORS[0].1, + }; + let path = match pass.get(n, || { + #[cfg(test)] + OUTLINES_MADE.with(|c| c.set(c.get() + 1)); + n.stroke_path() + }) { + Some(p) => p.clone(), None => n.geometric_bounds_with(&symbols)?.to_path(0.1), }; - Some((path, st.doc.layer_color(*id))) + Some((path, color)) }) - .collect() + .collect(); + cache.outlines.end(pass, &st.doc); + out } #[cfg(test)] diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 4f05e615af..e1bb6df83a 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -86,6 +86,9 @@ pub struct DocState { /// Whether Start Global Edit supports the one selected object /// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable. pub(crate) global_edit_support: cmd::globaledit::SupportCache, + /// The forms Start Global Edit compared the selected object with + /// ([`cmd::globaledit::FormCache`]). Not saved, not undoable. + pub(crate) global_edit_forms: cmd::globaledit::FormCache, /// What leaving symbol editing mode goes back to ([`cmd::symboledit`]). pub(crate) symbol_edit_return: cmd::symboledit::Return, pub interaction: Option, @@ -481,6 +484,7 @@ impl DocState { global_edit: None, similar_outlines: Default::default(), global_edit_support: Default::default(), + global_edit_forms: Default::default(), symbol_edit_return: Default::default(), interaction: None, undo_group: None, diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 3bfe6039fa..ae56fa7c5a 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -119,6 +119,43 @@ fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts assert!(highlights(&s).is_empty(), "two objects selected"); } +#[test] +fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() { + use crate::cmd::globaledit::{FORMS_MADE, OUTLINES_MADE, highlights}; + let made = || (FORMS_MADE.with(std::cell::Cell::get), OUTLINES_MADE.with(std::cell::Cell::get)); + let since = |b: (usize, usize)| { + let n = made(); + (n.0 - b.0, n.1 - b.1) + }; + let mut s = session(); + let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let copies: Vec = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0)).collect(); + sel(&mut s, &[key]); + let before = made(); + assert_eq!(highlights(&s).len(), 39); + assert_eq!(since(before), (40, 39), "the first preview measures each object"); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = made(); + assert_eq!(highlights(&s).len(), 39); + assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged"); + sel(&mut s, &[copies[0]]); + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + sel(&mut s, &[copies[1]]); + s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap(); + sel(&mut s, &[copies[2]]); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + sel(&mut s, &[key]); + let before = made(); + let shown = highlights(&s); + assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar"); + assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match"); + let moved = node(&s, copies[1]).stroke_path().unwrap(); + assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now"); + s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); + assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out"); + assert_eq!(crate::cmd::globaledit::match_count(&s), 38); +} + #[test] fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() { let mut s = session(); From aa5f1bdca1c8f9a83fb9a3d1ff7872c11242aad3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 20:07:16 -0800 Subject: [PATCH 15/18] Clean Up: Hairline Slivers leaves art at 0% opacity alone A sliver at 0% opacity, or inside a group or layer at 0% opacity, paints nothing, so Clean Up and Select > Object > Hairline Slivers now skip it. The params text and docs/mcp.md say so, and docs/mcp.md also names what a group or compound path used as a clipping path holds among the objects both commands leave. --- crates/engine/src/cmd/pathops.rs | 10 ++++++---- crates/engine/src/cmd/select.rs | 2 +- crates/engine/src/tests/pathops.rs | 25 +++++++++++++++++++++++++ docs/mcp.md | 5 +++-- 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index b30a6a6c37..61406fdc61 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Clean Up…", ["Object", "Path"], None, - "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}", + "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers, objects at 0% opacity and their members, and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}", has_doc, clean_up ), @@ -1804,8 +1804,9 @@ pub(crate) fn unmeasured_warning(count: usize) -> Option { /// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not /// those on a locked artboard or in a template layer) for which `within` holds, in the layers and /// groups of the whole document. A compound path counts as one object. The clipping paths of groups -/// and layers (and all of a clipping group used as one), the members of live and generated art, and -/// the members of groups and layers whose own stroke or effect paints them are left out. +/// and layers (and all of a clipping group used as one), the members of live and generated art, +/// objects at 0 % opacity and everything in a group or layer at 0 %, and the members of groups and +/// layers whose own stroke or effect paints them are left out. pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers { struct Walk<'a> { width: f64, @@ -1817,7 +1818,8 @@ pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) out: Vec<(NodeId, Option)>, } fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) { - if !n.visible || n.locked || n.is_template() || clip_path { + // An object at 0 % opacity, or anything in a group or layer at 0 %, paints nothing. + if !n.visible || n.locked || n.is_template() || clip_path || n.opacity <= 0.0 { return; } match &n.kind { diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index f10bb5b342..931504dedb 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -211,7 +211,7 @@ pub fn specs() -> Vec { "Hairline Slivers…", ["Select", "Object"], None, - "{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}", + "{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, objects at 0% opacity and their members, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}", has_doc, select_hairline_slivers ), diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 6b4c9f534a..f4e251638f 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1316,6 +1316,31 @@ fn hairline_slivers_leave_art_on_a_locked_artboard_alone() { assert!(s.doc().unwrap().doc.node(sliver).is_some()); } +/// A sliver at 0 % opacity, and one in a group at 0 % opacity, paint nothing and are left alone. +#[test] +fn hairline_slivers_leave_art_at_zero_opacity_alone() { + let mut s = session(); + let clear = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + let member = filled(&mut s, "M100 10 L140 40 L100.001 10.0015 Z"); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let seen = filled(&mut s, "M200 10 L240 40 L200.001 10.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(clear).unwrap().opacity = 0.0; + d.node_mut(group).unwrap().opacity = 0.0; + d.node_mut(seen).unwrap().opacity = 0.5; + Ok(()) + }) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 1); + let d = &s.doc().unwrap().doc; + assert!(d.node(clear).is_some() && d.node(member).is_some(), "a sliver at 0 % opacity went"); + assert!(d.node(seen).is_none(), "a sliver at 50 % opacity stayed"); +} + /// A shape too complex to measure is kept, and both commands say how many there were. #[test] fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() { diff --git a/docs/mcp.md b/docs/mcp.md index 876f5a3901..b633ff7224 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8220,8 +8220,9 @@ VectorCraft's own value, and `hairlineSlivers` is off by default. In the desktop Slivers checkbox and a Sliver Width field, shown in the stroke unit, or in points when that unit's field would round 0.001 pt to 0. `select.object.hairlineSlivers {width?}` (Select › Object › Hairline Slivers…) selects the objects Clean Up would remove, only inside the isolated group while one is isolated, and replies `{count, warning?}`. Neither command -takes hidden or locked objects, objects in template layers, art on locked artboards, guides, the clipping paths of -groups and layers, shapes with an effect, or the members of Live Paint groups and other live or generated art. A shape +takes hidden or locked objects, objects at 0% opacity or in a group or layer at 0% opacity, objects in template +layers, art on locked artboards, guides, the clipping paths of groups and layers, what a group or compound path used as +a clipping path holds, shapes with an effect, or the members of Live Paint groups and other live or generated art. A shape that holds a circle 15/16 of the width across is kept too. A shape too complex to measure is kept as well, and so is every shape still unmeasured when one run reaches its limit of work; the reply's `warning` says how many there were: From 8b30502be9b31b93c96c9e7de33aceb91c399882 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 20:11:28 -0800 Subject: [PATCH 16/18] Save options: All/Range and Transparent/Opaque radios have no empty caption over them The All and Range radios under the artboard check box of the .ai, VectorCraft and EPS save options, and EPS's Transparent and Opaque radios, were radio rows with an empty name, which the form draws as an empty caption: a blank band about one row tall above the radios. Both rows now use stacked options, so the radios follow the row above them. The Transparent/Opaque row carries the option's label as the group's accessible name. --- crates/ui-egui/src/dialogs/save_options.rs | 8 +-- .../ui-egui/src/dialogs/save_options/tests.rs | 54 +++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 6576e17c73..1d3cb996ee 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -302,10 +302,11 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc, legacy: bool) - }); return vec![row(ParamKind::choice(entries.collect(), None))]; } - // Only the colour preview can keep transparency. + // Only the colour preview can keep transparency. The options stand with no caption over them; the option's label + // names the group for assistive technology. if f.id == "eps" && o.name == "transparentPreview" { let kind = ParamKind::radio(vec![("true".into(), tl!("Transparent").into()), ("false".into(), tl!("Opaque").into())], None); - return vec![Param::new(o.name, "", kind).enabled_when("previewFormat", "tiffColor")]; + return vec![Param::new(o.name, label.clone(), kind).stacked_options().enabled_when("previewFormat", "tiffColor")]; } // Type is written as glyph outlines, which need no fonts: the row is on, and never enabled. if f.id == "eps" && o.name == "embedFonts" { @@ -320,7 +321,8 @@ fn option_rows(f: &Format, o: &FormatOption, menus: &Arc, legacy: bool) - let mut rows = vec![check]; if matches!(o.name, "separateArtboards" | "useArtboards") { let all = ParamKind::radio(vec![("true".into(), tl!("All").into()), ("false".into(), tl!("Range:").into())], None); - rows.push(Param::new("all", "", all).enabled_when(o.name, true)); + // Right under the check box, with no caption over the options. + rows.push(Param::new("all", "", all).stacked_options().enabled_when(o.name, true)); rows.push(Param::new("range", "", ParamKind::text("")).hint("1-3, 5").enabled_when("all", "false")); } rows diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 9076f18d21..8656fe3bf0 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -513,6 +513,60 @@ fn eps_save_transparency_follows_the_color_preview() { assert_eq!(dialog(&mut app).bool("embedFonts"), Some(true)); } +/// The open dialog's labelled controls with their bounds, as a screen reader is told them, after a few frames of a +/// 1440x900 window. +fn labelled_controls(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> { + let ctx = app.ui_ctx.clone().unwrap(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut nodes = Vec::new(); + for _ in 0..4 { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + nodes = crate::testing::app_frame(app, &ctx, input).platform_output.accesskit_update.map_or_else(Vec::new, |u| u.nodes); + } + nodes + .iter() + .filter_map(|(_, node)| { + let b = node.bounds()?; + Some((node.label()?.to_string(), egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32)))) + }) + .collect() +} + +/// The bounds of the control labelled `label` in `controls`, with or without a final colon. +fn control(controls: &[(String, egui::Rect)], label: &str) -> egui::Rect { + let bare = |l: &str| l.trim_end_matches(':').to_string(); + controls + .iter() + .find(|(l, _)| bare(l) == bare(label)) + .map(|(_, r)| *r) + .unwrap_or_else(|| panic!("no control labelled {label:?} in {:?}", controls.iter().map(|(l, _)| l).collect::>())) +} + +/// The All and Range radios stand right under the artboard check box, and EPS's Transparent and Opaque radios right +/// under the Preview menu, with no empty caption over them: an empty caption leaves a band about a row tall. +#[test] +fn save_options_radios_have_no_empty_caption_over_them() { + for (picked, check) in [("art.eps", "Use Artboards"), ("art.ai", "Save each artboard to a separate file")] { + let (mut app, _, _) = desktop(picked); + save_as(&mut app, "file.saveAs"); + let controls = labelled_controls(&mut app); + let (check, all, range) = (control(&controls, check), control(&controls, "All"), control(&controls, "Range:")); + assert!(all.top() - check.bottom() <= check.height() / 2.0, "{picked}: All at {all:?}, the check box at {check:?}"); + assert!(range.top() - all.bottom() <= all.height() / 2.0, "{picked}: Range at {range:?}, All at {all:?}"); + if picked == "art.eps" { + let transparent = control(&controls, "Transparent"); + // The Preview menu: the nearest control so named above the radios (the window has other Preview controls). + let preview = controls + .iter() + .filter(|(l, r)| l.trim_end_matches(':') == "Preview" && r.bottom() <= transparent.top()) + .map(|(_, r)| *r) + .max_by(|a, b| a.bottom().total_cmp(&b.bottom())) + .expect("the Preview menu above Transparent"); + assert!(transparent.top() - preview.bottom() <= check.height() / 2.0, "Transparent at {transparent:?}, Preview at {preview:?}"); + } + } +} + #[test] fn a_native_save_options_draft_cannot_redirect_its_path_to_another_drawing() { let (mut app, written, _) = desktop("original.vectorcraft"); From 30d22d07c82111c3378428e921640e7aef506b72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 20:50:13 -0800 Subject: [PATCH 17/18] Scripts: the checker scans a script that binds no name once A script whose only finding about its variables was that a name in brackets is not one literal (o[k]) was scanned a second time. That finding comes from the names the script declares, which the first scan has already read, so the second scan gave the same report and added up to three steps a byte. A 104-byte input of single-character tokens took 550 steps against the 536 the property test allows. The check now repeats a scan only when a variable holds a member chain or a File or Folder object. The property tests take their bound from the number of scans: five steps a byte for a script scanned once, and seventeen for one scanned up to five times. --- crates/scriptcheck/src/analyze.rs | 5 +++++ crates/scriptcheck/src/lib.rs | 6 ++++-- crates/scriptcheck/src/tests.rs | 33 +++++++++++++++++++++++++++++-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 0e331057d7..b7156550c8 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -65,6 +65,11 @@ impl Known { self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) + usize::from(self.unsure) } + /// No variable holds a member chain or a File or Folder object. [`Known::unsure`] may be set. + pub fn no_names(&self) -> bool { + self.bound.is_empty() && self.files.is_empty() + } + /// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already /// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder /// object only when both sides say so; otherwise it may hold a File object. diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index e74d299aaa..9075c53517 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -231,7 +231,9 @@ pub fn check(name: &str, bytes: &[u8], loader: Option<&mut dyn Loader>, limits: /// that includes nothing, so a variable a function uses before the global code assigns it holds /// what it is assigned. `first` holds the scan made with nothing known, which found `known`, and /// `pre` what came before it. A scan made with what the scans before it found, and that finds -/// nothing more, is the report scan; no other scan is repeated. +/// nothing more, is the report scan; no other scan is repeated. When `known` holds no name, `first` +/// is the report: [`analyze::Known::unsure`] alone comes from `declared`, which the first scan +/// already read. fn settle<'l>( first: report::Acc<'l>, pre: report::Acc<'l>, @@ -240,7 +242,7 @@ fn settle<'l>( braced: &[analyze::Braced], mut known: analyze::Known, ) -> report::Acc<'l> { - if known.len() == 0 { + if known.no_names() { return first; } let entries = pre.limits.entries; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0d65836ef6..af88ac8fa7 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1935,12 +1935,41 @@ fn the_costliest_inputs_stay_within_five_steps_a_byte() { format!("\\u0061;function f({}) {{ var {}; }}", names.join(","), names.join(",")), format!("\\u0061;function f({}) {{}}", vec!["a"; 900].join(",")), format!("\\u0061;{}", "x=(".repeat(600)), + format!("\\u0061;o[k];{}", "{".repeat(2_000)), ] { let r = report(&src); assert!(r.steps <= 5 * src.len() + 16, "{} steps for {} bytes", r.steps, src.len()); } } +/// The most steps a check of `bytes` without a loader may take. The text is read once for the +/// escapes and once for the names declared, and a scan takes at most three steps a byte. A script +/// whose variables hold nothing the check follows is scanned once: five steps a byte. Any other +/// script is scanned up to five times (the first scan, three more while what its variables hold +/// grows, and the report's): seventeen steps a byte. +fn step_bound(bytes: &[u8]) -> usize { + let limits = Limits::default(); + let mut acc = report::Acc::new(&limits); + let (text, _) = decode(bytes); + let (text, braced) = analyze::unescaped(text, &mut acc); + let declared = analyze::declarations(&text, &mut acc); + let known = analyze::scan(&text, &declared, &braced, None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc).known; + let scans = if known.no_names() { 1 } else { 5 }; + (2 + 3 * scans) * bytes.len() + 16 +} + +/// A name in brackets that is not one literal (`0[ \| … ]`) gives no variable a value, so the +/// script is scanned once. The bytes are the ones a run of the property below found. +#[test] +fn a_script_that_binds_no_name_is_scanned_once() { + let bytes: &[u8] = b"\x01\x01 \x010 !0!\x01!\x01#\x01#{#{ 0( #0\x01( \x01( {#{ # \x01#0:((0[\t \\| \x1b!!0:|!| 0) ) )] ! \x1b \x1b \x1b \\u\t\x01"; + assert_eq!(bytes.len(), 104); + let r = check("a.jsx", bytes, None, &Limits::default()); + assert_eq!(r.kind, Kind::Script); + assert_eq!(step_bound(bytes), 5 * bytes.len() + 16); + assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len()); +} + #[test] fn lists_stop_at_their_limits_and_echoes_are_cut() { let mut s = String::new(); @@ -2339,13 +2368,13 @@ proptest! { #[test] fn any_bytes_are_checked_in_linear_work(bytes in prop::collection::vec(any::(), 0..2_000), jsxbin in any::()) { let r = check(if jsxbin { "a.jsxbin" } else { "a.jsx" }, &bytes, None, &Limits::default()); - prop_assert!(r.steps <= 5 * bytes.len() + 16, "{} steps for {} bytes", r.steps, bytes.len()); + prop_assert!(r.steps <= step_bound(&bytes), "{} steps for {} bytes", r.steps, bytes.len()); } #[test] fn script_like_text_is_checked_in_linear_work(text in script_text()) { let r = report(&text); - prop_assert!(r.steps <= 5 * text.len() + 16, "{} steps for {} bytes", r.steps, text.len()); + prop_assert!(r.steps <= step_bound(text.as_bytes()), "{} steps for {} bytes", r.steps, text.len()); let limits = Limits::default(); for list in [r.targets.len(), r.directives.len(), r.includes.len(), r.members.len(), r.types.len(), r.menu_strings.len(), r.problems.len()] { prop_assert!(list <= limits.entries); From 5f99cb7ebbc33a3aef4e53bb8b6cc025f15d2d9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:05:01 -0800 Subject: [PATCH 18/18] =?UTF-8?q?Libraries:=20a=20swatch=20row=20held=20ac?= =?UTF-8?q?ross=20File=20=E2=80=BA=20Revert=20is=20not=20added=20to=20a=20?= =?UTF-8?q?library?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Libraries panel accepted a swatch row dragged before File › Revert and added the restored swatch of that name. Membership::grabbed now refuses stale rows, for the hover marker and on release. --- crates/ui-egui/src/panels/libraries.rs | 3 ++ crates/ui-egui/src/panels/libraries/tests.rs | 42 ++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 62e1da73ca..d9e2f9b70d 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -205,6 +205,9 @@ impl Membership { /// The item of this library that `drag` holds, or what it would add. `library.add` reads object IDs in the current document. fn grabbed(&self, drag: &PanelDrag) -> Option { + if drag.stale_rows(self.active_document) { + return None; + } let library = &self.library; match drag { PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), diff --git a/crates/ui-egui/src/panels/libraries/tests.rs b/crates/ui-egui/src/panels/libraries/tests.rs index 9af1be9d75..d8091cf2b7 100644 --- a/crates/ui-egui/src/panels/libraries/tests.rs +++ b/crates/ui-egui/src/panels/libraries/tests.rs @@ -277,6 +277,48 @@ fn a_library_drop_does_not_collect_unrelated_artwork_after_a_document_switch() { assert_eq!(graphics(&mut panel.app()).len(), 1, "artwork from the current document can still be added"); } +#[test] +fn a_library_drop_of_a_swatch_row_held_across_file_revert_adds_nothing() { + use crate::panel_drag::SwatchRows; + + let mut app = app(); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("library.create", json!({"name": "Brand"})).unwrap(); + let name = "Sunset"; + let gradient = json!({"stops": [{"offset": 0, "color": "#ffcc00"}, {"offset": 1, "color": "#cc3300"}]}); + app.run("swatch.new", json!({"name": name, "gradient": gradient})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("library-swatch-drop-revert"); + let path = folder.join("drawing.vectorcraft"); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + let gradient = json!({"stops": [{"offset": 0, "color": "#00ff00"}, {"offset": 1, "color": "#0000ff"}]}); + app.run("swatch.edit", json!({"name": name, "paint": {"gradient": gradient}})).unwrap(); + let state = app.session.active().unwrap(); + let held = PanelDrag::Paint { + paint: state.doc.swatch(name).unwrap().paint.clone(), + params: json!({"swatch": name}), + rows: Some(SwatchRows { + document: state.uid, + reverts: state.reverts, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + }), + library: None, + }; + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let state = app.session.active().unwrap(); + let membership = Membership::of("Brand", app.session.libraries.get("Brand").unwrap(), Some((state.uid, state.reverts))); + assert!(membership.landing(&held, None).is_none(), "hover refuses the stale swatch row"); + let mut panel = Harness::new(app, with_source); + panel.frame(); + let at = panel.rect("This library is empty").center(); + drop_at(&mut panel, held, at); + assert!(panel.app().session.libraries.get("Brand").unwrap().gradients.is_empty(), "release adds no gradient"); +} + +#[test] fn gradients_and_patterns_come_from_swatches_and_paint_the_selection() { let mut app = app(); app.run("library.create", json!({"name": "Brand"})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 98ec4fae71..a953c0f8ab 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6956,7 +6956,8 @@ the panel shows) is meant. takes them), `fillColor` / `strokeColor` (the first selected object's solid colour, else the default one, or `color`), `charStyle` / `paraStyle` (the selected text's attributes). The new item goes into `group` (by default into none) and, with `before` or `after` (another item of its kind), just before or after that item, as `library.moveItem` places one; -art and swatches dropped among the panel's items are added this way. An item the library already has is reported as +art and swatches dropped among the panel's items are added this way (a swatch dragged before File › Revert of its +drawing is not added). An item the library already has is reported as `existing`, and stays where it is. `library.use {library?, kind, item, center?, to?}` uses one: a graphic is placed centred on `center` (pasted with its resources; a swatch name the document gives another colour merges into the document's), a colour paints the selection's fill or stroke, and a style is added