From f763b86fdc49fd5da6df4ecc6aa5e7a4b113f9b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:06:25 -0800 Subject: [PATCH 01/51] Color Wheel: OKLCH Sliders edit a color by lightness, chroma and hue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Color Wheel panel's menu gets OKLCH Sliders: 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 of its display sRGB, as CSS Color 4 defines them. Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma that fits; a color outside sRGB keeps L and H and takes that chroma. The rows are gray, and the menu item and ui.colorWheel {sliders: "oklch"} are refused, while the working RGB space is not sRGB. The choice is kept with the preferences. - vectorcraft-color: oklab.rs with OKLCH conversions and max_chroma. - color.convert {to: "oklch"} answers [L %, C, H°]. - ui.colorWheel takes sliders next to view and channel. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/color/src/lib.rs | 1 + crates/color/src/oklab.rs | 138 +++++++++ crates/engine/src/cmd/colormgmt.rs | 14 +- crates/engine/src/tests/colormgmt.rs | 24 ++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 211 +++++++++++++- .../ui-egui/src/panels/tests_color_wheel.rs | 261 +++++++++++++++++- .../src/panels/tests_color_wheel_box.rs | 26 +- crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/widgets.rs | 4 +- crates/ui-egui/src/widgets/buttons.rs | 12 +- docs/control-protocol.md | 5 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 43 files changed, 840 insertions(+), 38 deletions(-) create mode 100644 crates/color/src/oklab.rs diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 3afca8063c..b3d97d7efd 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -10,6 +10,7 @@ pub mod freeform; pub mod gradient; pub mod harmony; pub mod libraries; +pub mod oklab; pub mod palette_io; pub mod recolor; pub mod swatch; diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs new file mode 100644 index 0000000000..90467fc6c3 --- /dev/null +++ b/crates/color/src/oklab.rs @@ -0,0 +1,138 @@ +//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it +//! (): lightness L from 0 to 1, chroma +//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take +//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`]. + +use crate::libraries::{oklab_to_srgb, srgb_to_oklab}; + +/// The chroma CSS reads as 100%. +pub const CHROMA_FULL: f64 = 0.4; + +/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there. +pub const POWERLESS_CHROMA: f64 = 0.000_004; + +/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut. +const GAMUT_SLACK: f64 = 1e-4; + +/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they +/// are. The hue is in 0..360, and 0 while the chroma is powerless. +pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] { + let [l, a, b] = srgb_to_oklab(rgb); + let c = a.hypot(b); + if c <= POWERLESS_CHROMA { + return [l, 0.0, 0.0]; + } + [l, c, b.atan2(a).to_degrees().rem_euclid(360.0)] +} + +/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped. +pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] { + let (sin, cos) = h.to_radians().sin_cos(); + oklab_to_srgb(l, c * cos, c * sin) +} + +/// Whether sRGB `rgb` lies inside the sRGB gamut. +pub fn in_srgb(rgb: [f64; 3]) -> bool { + rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v)) +} + +/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white. +pub fn max_chroma(l: f64, h: f64) -> f64 { + if !(l > 0.0 && l < 1.0) || !h.is_finite() { + return 0.0; + } + // sRGB holds every chroma from 0 up to its edge along a hue at a given lightness. + let (mut lo, mut hi) = (0.0, 0.5); + for _ in 0..40 { + let mid = (lo + hi) / 2.0; + if in_srgb(oklch_to_srgb(l, mid, h)) { lo = mid } else { hi = mid } + } + lo +} + +/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: +/// a color outside sRGB keeps its lightness and hue and takes the largest chroma that fits. +/// Lightness is clamped to 0..=1 and chroma to 0 or more. +pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { + let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; + let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; + let h = if h.is_finite() { h } else { 0.0 }; + let exact = oklch_to_srgb(l, c, h); + let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, max_chroma(l, h).min(c), h), true) }; + (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn eight(rgb: [f32; 3]) -> [u8; 3] { + rgb.map(|v| (v * 255.0).round() as u8) + } + + #[test] + fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() { + let [l, c, h] = to_oklch([1.0, 0.0, 0.0]); + assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}"); + let (rgb, lowered) = from_oklch(l, c, h); + assert_eq!((eight(rgb), lowered), ([255, 0, 0], false)); + } + + /// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give. + #[test] + fn the_polar_form_matches_the_css_examples() { + for ([l, a, b], [cl, cc, ch]) in + [([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])] + { + let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32); + let [ol, oc, oh] = to_oklch(rgb); + assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}"); + } + } + + #[test] + fn the_216_web_colors_round_trip() { + let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff]; + for r in steps { + for g in steps { + for b in steps { + let rgb = [r, g, b].map(|v| f32::from(v) / 255.0); + let [l, c, h] = to_oklch(rgb); + assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}"); + } + } + } + } + + #[test] + fn grays_have_no_chroma_and_hue_zero() { + for v in [0.0, 0.5, 1.0] { + let [_, c, h] = to_oklch([v, v, v]); + assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}"); + } + } + + /// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so. + #[test] + fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() { + let (l, h) = (0.7, 150.0); + let max = max_chroma(l, h); + assert!(max > 0.05 && max < CHROMA_FULL, "{max}"); + assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h))); + let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h); + assert!(lowered); + let [ol, oc, oh] = to_oklch(rgb); + assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}"); + assert!(!from_oklch(l, max * 0.5, h).1); + } + + #[test] + fn black_white_and_bad_numbers_hold_no_chroma() { + assert_eq!(max_chroma(0.0, 30.0), 0.0); + assert_eq!(max_chroma(1.0, 30.0), 0.0); + assert_eq!(max_chroma(f64::NAN, 30.0), 0.0); + assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0); + assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]); + assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]); + } +} diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 66295f50f2..c9d4daa0a9 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Convert Color", [], None, - "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", + "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; in a working RGB space other than sRGB, a color outside sRGB is clamped to sRGB first", always, convert_color ), @@ -707,10 +707,14 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { let intent = intent_param(p, C)?.unwrap_or(c.settings().intent); let lab = c.lab(&col); let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") { - "rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))), - "cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))), - "gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))), - "lab" => ("lab", vec![lab.l, lab.a, lab.b]), + "rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))), + "cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))), + "gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))), + "lab" => ("lab", json!([lab.l, lab.a, lab.b])), + "oklch" => { + let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col)); + ("oklch", json!([l * 100.0, ch, h])) + } other => return Err(bad(C, format!("unknown model `{other}`"))), }; let de = c.gamut_error(&col); diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 493f569805..cdc774da7f 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -295,6 +295,30 @@ fn convert_query_and_intents() { assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err()); } +/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color; +/// a CMYK color's display color, not its naive separation, sets them. +#[test] +fn convert_to_oklch_answers_lightness_chroma_and_hue() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap(); + assert_eq!(r["model"], "oklch"); + let v: Vec = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}"); + let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]); + assert!(!lowered); + assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000"); + assert_eq!(r["hex"], "#ff0000"); + let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap(); + assert_eq!(gray["values"][2], 0.0, "{gray}"); + let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}); + let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap(); + let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0))); + let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); + let l = cyan["values"][0].as_f64().unwrap() / 100.0; + assert!((l - shown[0]).abs() < 1e-9 && (l - naive[0]).abs() > 0.02, "{cyan} {shown:?} {naive:?}"); +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 943faa4782..965ac671a7 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1324,7 +1324,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 348ac7b881..449b1c7d5d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1759,6 +1759,10 @@ font-technology Variable Променливи Knife Нож Knockout Group Група с изрязване Lab Lab + OKLCH Sliders Плъзгачи OKLCH + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Най-голямата хрома, която sRGB побира при тази светлина и този оттенък + OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство Lab Spot Colors: Спот цветове по Lab: Lab Values Стойности по Lab Landscape Пейзаж @@ -4242,6 +4246,8 @@ axis Both И двете @msg `aspect` must be a number (%) `aspect` трябва да бъде число (%) @msg `at` must be [x, y] `at` трябва да бъде [x, y] @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 `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив @msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3b1a9e001c..028f6d111d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4194,6 +4194,10 @@ axis Both Obje Image Slika Ink Tinta Lab Lab + OKLCH Sliders OKLCH klizači + Chroma Hroma + The largest chroma sRGB holds at this lightness and hue Najveća hroma koju sRGB obuhvata pri ovoj svjetloći i nijansi + OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor Medium Srednje Name Naziv None Ništa @@ -4651,6 +4655,8 @@ imageTrace Outline Obris @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe @msg `view` must be wheel or box `view` mora biti wheel ili box @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 `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 488b46c4f5..2cf6e80150 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2257,6 +2257,10 @@ digits Malayalam Malaiàlam Knife Ganivet Knockout Group Grup knockout Lab Lab + OKLCH Sliders Controls lliscants OKLCH + Chroma Croma + The largest chroma sRGB holds at this lightness and hue El croma més gran que sRGB admet amb aquesta lluminositat i aquest to + OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball Lab Spot Colors Colors directes Lab Lab Spot Colors: Colors directes Lab: Lab Values Valors Lab @@ -5272,6 +5276,8 @@ digits Malayalam Malaiàlam @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` ha de ser wheel o box @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 `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6a57e90e37..177d342c5d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4250,6 +4250,10 @@ axis Both Obě Image Obraz Ink Inkoust Lab Lab + OKLCH Sliders Posuvníky OKLCH + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Největší chroma, kterou sRGB obsáhne při této světlosti a odstínu + OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB Medium Střední Name Název None Žádné @@ -4814,6 +4818,8 @@ imageTrace Outline Obrys @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe @msg `view` must be wheel or box `view` musí být wheel nebo box @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 `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 54a79e38e5..fb2ccac4cd 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3960,6 +3960,10 @@ axis Both Begge Image Billede Ink Blæk Lab Lab + OKLCH Sliders OKLCH-skydere + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Den største kroma, sRGB kan rumme ved denne lyshed og farvetone + OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum Medium Medium Name Navn None Ingen @@ -5640,6 +5644,8 @@ mark-style Japanese Japansk @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` skal være wheel eller box @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 the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ab77cb0dd7..5d6fdfc721 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1821,6 +1821,10 @@ file-filter Templates Vorlagen Knife Messer Knockout Group Aussparungsgruppe Lab Lab + OKLCH Sliders OKLCH-Regler + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Das größte Chroma, das sRGB bei dieser Helligkeit und diesem Farbton enthält + OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum Lab Spot Colors: Lab-Volltonfarben: Lab Values Lab-Werte Landscape Querformat @@ -4427,6 +4431,8 @@ theme Appearance Erscheinungsbild @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein @msg `view` must be wheel or box `view` muss wheel oder box sein @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 `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a1a203a257..551003fcba 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1722,6 +1722,10 @@ font-technology Variable Μεταβλητές Knife Μαχαίρι (Knife) Knockout Group Ομάδα διάτρησης Lab Lab + OKLCH Sliders Ρυθμιστικά OKLCH + Chroma Χρωματική ένταση + The largest chroma sRGB holds at this lightness and hue Η μεγαλύτερη χρωματική ένταση που χωρά το sRGB σε αυτή τη φωτεινότητα και απόχρωση + OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB Lab Spot Colors: Πλακάτα χρώματα Lab: Lab Values Τιμές Lab Landscape Οριζόντιος προσανατολισμός @@ -6098,6 +6102,8 @@ effect Points Σημεία @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe @msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box @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 `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 45fd0d8235..e31262e04a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1815,6 +1815,10 @@ font-technology Variable Variables Knife Cuchilla Knockout Group Grupo de exclusión Lab Lab + OKLCH Sliders Controles deslizantes OKLCH + Chroma Croma + The largest chroma sRGB holds at this lightness and hue El croma más alto que admite sRGB con esta luminosidad y este tono + OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB Lab Spot Colors: Tintas planas Lab: Lab Values Valores Lab Landscape Horizontal @@ -4504,6 +4508,8 @@ axis Both Ambos @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` debe ser wheel o box @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 `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f6db5b8ee1..c3f1c8a1d7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4169,6 +4169,10 @@ axis Both Molemmat Image Kuva Ink Muste Lab Lab + OKLCH Sliders OKLCH-liukusäätimet + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Suurin kroma, jonka sRGB sisältää tällä vaaleudella ja sävyllä + OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi Medium Keskitaso Name Nimi None Ei mitään @@ -6109,6 +6113,8 @@ mark-style Japanese Japanilainen @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe @msg `view` must be wheel or box `view`-arvon on oltava wheel tai box @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 `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ae0bf3b436..b44504a009 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1809,6 +1809,10 @@ font-technology Variable Variables Knife Cutter Knockout Group Groupe perçant Lab Lab + OKLCH Sliders Curseurs OKLCH + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Le plus grand chroma que sRGB contient à cette luminosité et cette teinte + OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB Lab Spot Colors: Tons directs Lab : Lab Values Valeurs Lab Landscape Paysage @@ -4493,6 +4497,8 @@ axis Both Les deux @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` doit valoir wheel ou box @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 `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f38612601c..fd6f9f7419 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -640,6 +640,11 @@ Color Themes રંગ થીમ Color Type: રંગ પ્રકાર: Color Wheel રંગ વ્હીલ + OKLCH Sliders OKLCH સ્લાઇડર્સ + Chroma ક્રોમા + The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા + OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે + Lightness લાઇટનેસ Color blindness – Deuteranopia-type રંગ અંધત્વ – ડ્યુટેરેનોપિયા પ્રકાર Color blindness – Protanopia-type રંગ અંધત્વ – પ્રોટેનોપિયા પ્રકાર Color blindness – Tritanopia-type રંગ અંધત્વ – ટ્રિટેનોપિયા પ્રકાર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 624671acca..ac9184a4ca 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2496,6 +2496,10 @@ antiAlias Sharp शार्प Knife चाकू Knockout Group नॉकआउट समूह Lab Lab + OKLCH Sliders OKLCH स्लाइडर्स + Chroma क्रोमा + The largest chroma sRGB holds at this lightness and hue इस लाइटनेस और ह्यू पर sRGB में आने वाला सबसे अधिक क्रोमा + OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए Lab Spot Colors लैब स्पॉट रंग Lab Spot Colors: लैब स्पॉट रंग: Lab Values लैब मूल्य @@ -6164,6 +6168,8 @@ antiAlias Sharp शार्प @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए @msg `view` must be wheel or box `view` को wheel या box होना चाहिए @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 `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3e8a200697..3d3f95031b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2272,6 +2272,10 @@ file-filter Templates Sablonok Knife Kés Knockout Group Kiütő csoport Lab Lab + OKLCH Sliders OKLCH csúszkák + Chroma Króma + The largest chroma sRGB holds at this lightness and hue A legnagyobb króma, amelyet az sRGB ezen a világosságon és színárnyalaton tartalmaz + OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges Lab Spot Colors Lab-direktszínek Lab Spot Colors: Lab-direktszínek: Lab Values Lab-értékek @@ -4929,6 +4933,8 @@ imageTrace Outline Körvonal @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell @msg `view` must be wheel or box `view`: wheel vagy box kell @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 `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2107a23bf0..8e3944aaae 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3960,6 +3960,10 @@ axis Both Keduanya Image Gambar Ink Tinta Lab Lab + OKLCH Sliders Penggeser OKLCH + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Kroma terbesar yang dapat dimuat sRGB pada kecerahan dan rona ini + OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja Medium Sedang Name Nama None Nihil @@ -5640,6 +5644,8 @@ mark-style Japanese Jepang @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe @msg `view` must be wheel or box `view` harus wheel atau box @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 the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f75dc629db..41cb669d34 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1853,6 +1853,10 @@ file-filter Templates Modelli Knife Coltello Knockout Group Gruppo con foratura Lab Lab + OKLCH Sliders Cursori OKLCH + Chroma Croma + The largest chroma sRGB holds at this lightness and hue Il croma più alto che sRGB contiene con questa luminosità e tonalità + OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB Lab Spot Colors: Colori spot Lab: Lab Values Valori Lab Landscape Orizzontale @@ -4556,6 +4560,8 @@ axis Both Entrambi @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` deve essere wheel o box @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 `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 67072cc8b3..d8739a0800 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3899,6 +3899,10 @@ file-filter Templates テンプレート Keep the pasted color as a new swatch with a numbered name. ペーストしたカラーを、番号付きの名前で新規スウォッチとして残します。 Keep: 保持: Lab Lab + OKLCH Sliders OKLCH スライダー + Chroma クロマ + The largest chroma sRGB holds at this lightness and hue この明度と色相で sRGB に収まる最大のクロマ + OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です Lab Values Lab 値 Large List View 大きいリスト表示 Large Thumbnail View 大きいサムネール表示 @@ -5016,6 +5020,8 @@ swatch Bright Violet ビビッドバイオレット @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください @msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください @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 `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c8513b84c3..28c90166d9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3780,6 +3780,10 @@ axis Both ორივე Image გამოსახულება Ink მელანი Lab Lab + OKLCH Sliders OKLCH სლაიდერები + Chroma ქრომა + The largest chroma sRGB holds at this lightness and hue უდიდესი ქრომა, რომელსაც sRGB იტევს ამ სიღიავესა და ფერის ტონზე + OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება Medium საშუალო Name სახელი None არცერთი @@ -5794,6 +5798,8 @@ imageTrace Outline კონტური @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe @msg `view` must be wheel or box `view` უნდა იყოს wheel ან box @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 this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8aa0bc41ca..f853524c7d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3887,6 +3887,10 @@ file-filter Templates 템플릿 Keep the pasted color as a new swatch with a numbered name. 붙여넣은 색상을 번호가 붙은 이름의 새 견본으로 보관합니다. Keep: 유지: Lab Lab + OKLCH Sliders OKLCH 슬라이더 + Chroma 크로마 + The largest chroma sRGB holds at this lightness and hue 이 명도와 색조에서 sRGB가 담을 수 있는 최대 크로마 + OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 Lab Values Lab 값 Large List View 큰 목록 보기 Large Thumbnail View 큰 축소판 보기 @@ -4943,6 +4947,8 @@ theme Appearance 외관 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다 @msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다 @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 `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index de5b7a3cf6..a73911ae0c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4478,6 +4478,10 @@ axis Both Beide Image Afbeelding Ink Inkt Lab Lab + OKLCH Sliders OKLCH-schuifregelaars + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue De grootste chroma die sRGB bij deze helderheid en tint bevat + OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte Medium Gemiddeld Name Naam None Geen @@ -6217,6 +6221,8 @@ mark-style Japanese Japans @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn @msg `view` must be wheel or box `view` moet wheel of box zijn @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 the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f9bdc664f1..a437403c48 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4091,6 +4091,10 @@ axis Both Obie Image Obraz Ink Farba Lab Lab + OKLCH Sliders Suwaki OKLCH + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Największa chroma, jaką sRGB mieści przy tej jasności i barwie + OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB Medium Średni Name Nazwa None Brak @@ -4638,6 +4642,8 @@ imageTrace Outline Kontur @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe @msg `view` must be wheel or box `view` musi mieć wartość wheel lub box @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 `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 07cd9c6fd6..92fa701cfa 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5039,6 +5039,10 @@ axis Both Ambos @plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincide com {n} atalho padrão|coincide com {n} atalhos padrão @plural {n} part of the file wasn't read|{n} parts of the file weren't read {n} parte do arquivo não foi lida|{n} partes do arquivo não foram lidas Lab Lab + OKLCH Sliders Controles Deslizantes OKLCH + Chroma Croma + The largest chroma sRGB holds at this lightness and hue O maior croma que o sRGB comporta nesta luminosidade e neste tom + OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB Lab Values Valores Lab Large List View Exibição em Lista Grande Large Thumbnail View Exibição em Miniaturas Grandes @@ -6097,6 +6101,8 @@ mark-style Japanese Japonesas @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` deve ser wheel ou box @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 the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fcf44192cd..3e8741e309 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1842,6 +1842,10 @@ file-filter Templates Шаблоны Knife Нож Knockout Group Группа с вырезанием Lab Lab + OKLCH Sliders Ползунки OKLCH + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Наибольшая хрома, которую вмещает sRGB при этой светлоте и оттенке + OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB Lab Spot Colors: Плашечные цвета Lab: Lab Values Значения Lab Landscape Альбомная @@ -4541,6 +4545,8 @@ axis Both Оба @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe @msg `view` must be wheel or box `view` должно быть wheel или box @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 `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d68878734e..8e690f5baf 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1770,6 +1770,10 @@ font-technology Variable Variabla Knife Kniv Knockout Group Utsparningsgrupp Lab Lab + OKLCH Sliders OKLCH-reglage + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Den största kroma som sRGB rymmer vid denna ljushet och nyans + OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd Lab Spot Colors: Lab-dekorfärger: Lab Values Lab-värden Landscape Liggande @@ -6099,6 +6103,8 @@ theme Appearance Utseende @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` måste vara wheel eller box @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 `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b3c88cc563..2d6ebbe2a4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1649,6 +1649,10 @@ font-technology Variable Değişken Knife Bıçak Knockout Group Nakavt Grubu Lab Laboratuvar + OKLCH Sliders OKLCH Kaydırıcıları + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue sRGB'nin bu açıklık ve renk tonunda alabileceği en yüksek kroma + OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir Lab Spot Colors: Laboratuvar Spot Renkleri: Lab Values Laboratuvar Değerleri Landscape Manzara @@ -4261,6 +4265,8 @@ axis Both Her İkisi @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır @msg `view` must be wheel or box `view` wheel veya box olmalıdır @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 `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0ab6257df4..95a58c1e0e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1847,6 +1847,10 @@ file-filter Templates Шаблони Knife Ніж Knockout Group Група з вирізуванням Lab Lab + OKLCH Sliders Повзунки OKLCH + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Найбільша хрома, яку вміщує sRGB за цієї світлоти й відтінку + OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB Lab Spot Colors: Плашкові кольори Lab: Lab Values Значення Lab Landscape Альбомна @@ -4540,6 +4544,8 @@ axis Both Обидві @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe @msg `view` must be wheel or box `view` має бути wheel або box @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 `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 80cc4951cf..f196c0b3e5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2119,6 +2119,10 @@ digits Hindi Hindi Knife Dao Knockout Group Nhóm Knockout Lab Lab + OKLCH Sliders Thanh trượt OKLCH + Chroma Độ tươi màu + The largest chroma sRGB holds at this lightness and hue Độ tươi màu lớn nhất mà sRGB chứa được ở độ sáng và sắc độ này + OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc Lab Spot Colors: Màu đặc Lab: Lab Values Giá trị Lab Landscape Ngang @@ -4589,6 +4593,8 @@ theme Appearance Giao diện @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe @msg `view` must be wheel or box `view` phải là wheel hoặc box @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 `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9561a51baf..024c708e5e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1731,6 +1731,10 @@ file-filter Templates 模板 Knife 刻刀 Knockout Group 挖空组 Lab Lab + OKLCH Sliders OKLCH 滑块 + Chroma 色度 + The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容纳的最大色度 + OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 Lab Spot Colors: Lab 专色: Lab Values Lab 值 Landscape 横向 @@ -4699,6 +4703,8 @@ imageTrace Outline 轮廓 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必须是 wheel 或 box @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 `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7489e3d4d9..0b0c0b61b8 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2413,6 +2413,8 @@ file-filter Templates 範本 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必須是 wheel 或 box @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 `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false @@ -2908,6 +2910,10 @@ file-filter Templates 範本 Knife 美工刀 Knockout Group 去底群組 Lab Lab + OKLCH Sliders OKLCH 滑桿 + Chroma 色度 + The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容納的最大色度 + OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 Lab Spot Colors: Lab 特別色: Lab Values Lab 值 Landscape 橫向 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d36ecae60f..68c48c392f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1325,7 +1325,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 31522578e5..64393be866 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -11,11 +11,17 @@ //! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation, //! Brightness, Red, Green or Blue). The field shows the other two components on the Color //! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`). +//! +//! Panel menu › OKLCH Sliders shows L, C and H rows under the wheel or the box that edit the color +//! by OKLCH lightness, chroma and hue (CSS Color 4: +//! ), while the working RGB space is +//! sRGB. The choice is kept with the preferences too. -use egui::{Ui, UiBuilder, vec2}; +use egui::{Color32, Rect, Stroke, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; +use vectorcraft_color::oklab::{self, CHROMA_FULL}; use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; @@ -23,6 +29,7 @@ use super::color::{Target, apply, wheel_target}; use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::color_picker::Channel; +use crate::theme::Tokens; use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item}; pub const ID: &str = "colorWheel"; @@ -67,6 +74,39 @@ pub struct Settings { pub view: View, #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] pub channel: Channel, + #[serde(deserialize_with = "deserialize_sliders")] + pub sliders: Sliders, +} + +/// The slider rows under the wheel or the box (panel menu, `ui.colorWheel {sliders}`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Sliders { + #[default] + None, + /// OKLCH Sliders: lightness, chroma and hue. + Oklch, +} + +impl Sliders { + pub const ALL: [Sliders; 2] = [Sliders::None, Sliders::Oklch]; + + /// The id `ui.colorWheel` and the preferences use. + pub fn id(self) -> &'static str { + match self { + Sliders::None => "none", + Sliders::Oklch => "oklch", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|v| v.id() == s) + } +} + +fn deserialize_sliders<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(Sliders::parse).unwrap_or_default()) } fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result { @@ -90,11 +130,19 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { - const KEYS: [&str; 2] = ["view", "channel"]; + set(&mut app.ui.color_wheel, p, &cms::active())?; + Ok(json!(app.ui.color_wheel)) +} + +/// Set the keys of `ui.colorWheel` params `p` in `settings`, with the color settings `cms`; on an +/// error `settings` stay as they were. +pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), String> { + const KEYS: [&str; 3] = ["view", "channel", "sliders"]; match p { Value::Null => {} Value::Object(o) => { @@ -104,7 +152,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result return Err(format!("the params must be an object, not {got}")), } - let mut set = app.ui.color_wheel.clone(); + let mut set = settings.clone(); match p.get("view") { None | Some(Value::Null) => {} Some(v) => set.view = v.as_str().and_then(View::parse).ok_or("`view` must be wheel or box")?, @@ -113,11 +161,21 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result {} Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, } - app.ui.color_wheel = set; - Ok(json!(app.ui.color_wheel)) + match p.get("sliders") { + None | Some(Value::Null) => {} + Some(v) => { + let sliders = v.as_str().and_then(Sliders::parse).ok_or("`sliders` must be none or oklch")?; + if sliders == Sliders::Oklch && !cms.rgb_is_srgb() { + return Err(OKLCH_NEEDS_SRGB.to_string()); + } + set.sliders = sliders; + } + } + *settings = set; + Ok(()) } -/// The panel menu: Wheel View and Box View, and Box Channel while the box shows. +/// The panel menu: Wheel View and Box View, Box Channel while the box shows, and OKLCH Sliders. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let set = app.ui.color_wheel.clone(); for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { @@ -134,6 +192,16 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + ui.separator(); + let on = set.sliders == Sliders::Oklch; + // While the rows show, the item stays enabled so that they can be hidden. + let enabled = on || cms::active().rgb_is_srgb(); + if widgets::menu_item_name_hint(ui, tl!("OKLCH Sliders"), enabled, on, tl!("OKLCH needs sRGB as the working RGB space")) { + let sliders = if on { Sliders::None } else { Sliders::Oklch }; + if let Err(e) = app.run("ui.colorWheel", json!({ "sliders": sliders.id() })) { + app.status(e); + } + } } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, @@ -207,6 +275,11 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; +/// Panel state: the OKLCH the slider rows asked for last, the [`Owner`] of the color they stored +/// and its display sRGB. +const OKLCH_MEMORY: &str = "color-wheel-oklch"; +/// The message for OKLCH Sliders while the working RGB space is not sRGB. +const OKLCH_NEEDS_SRGB: &str = "OKLCH needs sRGB as the working RGB space"; /// What the HSB picked last belongs to: the document, the selected objects or text characters, /// the appearance item, the proxy, the gradient stop or freeform point, its paint, and the color @@ -265,7 +338,12 @@ pub(crate) fn remembered_hsb(cms: &Cms, c: &Color, shown: [f32; 3], hsb: [f32; 3 /// model with the color settings. Anything else (no color, a Gray color, a tint of a global swatch) /// becomes a process color in the document's color mode: managed CMYK when `cmyk_doc`, else RGB. pub(crate) fn stored(cms: &Cms, hsb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { - let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(hsb)); + stored_srgb(cms, hsb_to_rgb(hsb), was, cmyk_doc) +} + +/// [`stored`] for a pick of display sRGB `srgb`. +pub(crate) fn stored_srgb(cms: &Cms, srgb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { + let [r, g, b] = cms.srgb_to_rgb(srgb); let rgb = Color::rgb(r, g, b); let cmyk = || { let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent); @@ -299,6 +377,103 @@ fn replaced(app: &VectorcraftApp, tgt: &Target, behind: bool) -> Option { } } +/// The OKLCH `[l, c, h°]` the rows show for `c` through `cms` when `lch` was asked for last and `c` +/// then displayed as the sRGB `shown`: `lch` while `c` still displays as `shown` (a chroma past the +/// gamut and the hue of a gray stay), else `c`'s own. +pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; 3]) -> [f64; 3] { + if cms.display_rgb(c) == shown { lch } else { oklab::to_oklch(cms.display_rgb(c)) } +} + +/// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed. +/// With `max_chroma` (the C track, whose L and H stay fixed) a chroma past it shows the color at +/// that chroma; without it, a color outside sRGB shows clamped to it. +pub(crate) fn oklch_track(lch: [f64; 3], max_chroma: Option) -> Color32 { + let (rgb, outside) = match max_chroma { + Some(m) if lch[1] > m => (oklab::oklch_to_srgb(lch[0], m, lch[2]), true), + Some(_) => (oklab::oklch_to_srgb(lch[0], lch[1], lch[2]), false), + None => { + let exact = oklab::oklch_to_srgb(lch[0], lch[1], lch[2]); + (exact, !oklab::in_srgb(exact)) + } + }; + let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let c = Color32::from_rgb(r, g, b); + if outside { c.gamma_multiply(0.3) } else { c } +} + +/// Where the C track's tick sits, from 0 at its left to 1 at its right: at the largest chroma +/// `max_chroma`, of the track's 0 to 0.4. +pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { + (max_chroma / CHROMA_FULL).clamp(0.0, 1.0) as f32 +} + +/// The L, C and H rows of OKLCH Sliders for the target's `color` through `cms`: lightness from 0 to +/// 100 %, chroma from 0 to 100 % of 0.4 (as CSS reads a chroma percentage) and hue from 0 to 360°. +/// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the +/// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no +/// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow +/// key, a screen reader or a field asks for, and its phase. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], Live)> { + let t = Tokens::get(ui.ctx()); + let enabled = color.is_some() && cms.rgb_is_srgb(); + let lch = match (color, pstate::>(ui.ctx(), OKLCH_MEMORY)) { + (Some(c), Some((owner, shown, lch))) if owner == Owner::of(app, tgt, c) => remembered_oklch(cms, &c, shown, lch), + (Some(c), _) => oklab::to_oklch(cms.display_rgb(&c)), + (None, _) => [0.0; 3], + }; + // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. + let rows = [("L", tl!("Lightness"), 100.0, "%"), ("C", tl!("Chroma"), 100.0, "%"), ("H", tl!("Hue"), 360.0, "°")]; + let shown = [lch[0] * 100.0, lch[1] / CHROMA_FULL * 100.0, lch[2]]; + // The OKLCH with row `i` set to `v` in the row's units. + let with = |i: usize, v: f64| { + let mut out = lch; + match i { + 0 => out[0] = (v / 100.0).clamp(0.0, 1.0), + 1 => out[1] = (v / 100.0 * CHROMA_FULL).clamp(0.0, CHROMA_FULL), + _ => out[2] = v.clamp(0.0, 360.0), + } + out + }; + let mut out = None; + ui.add_enabled_ui(enabled, |ui| { + let field_w = 48.0; + let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); + // The C track's L and H stay fixed, so its largest chroma is found once per frame. + let max_c = if enabled { oklab::max_chroma(lch[0], lch[2]) } else { 0.0 }; + for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() { + ui.horizontal(|ui| { + ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text))); + let v = shown[i].clamp(0.0, max); + let at = |x: f32| with(i, f64::from(x) * max); + let track = |x: f32| if enabled { oklch_track(at(x), (i == 1).then_some(max_c)) } else { t.input }; + let rail = Rect::from_min_size(ui.cursor().min, vec2(slider_w, 22.0)); + let value = SliderValue::field(v, 0.0..=max, suffix, 0); + let (dragged, phase, keyed) = + widgets::color_slider_stepped(ui, ("color-wheel-oklch", i), name, Some(value), (v / max) as f32, slider_w, &track); + if i == 1 && enabled { + // The bar of `color_slider_stepped`'s rail: 4 points in from its left, top and right. + let bar = Rect::from_min_size(rail.min + vec2(4.0, 4.0), vec2(slider_w - 8.0, 7.0)); + let x = bar.left() + chroma_tick(max_c) * bar.width(); + ui.painter().line_segment([pos2(x, bar.top() - 3.0), pos2(x, bar.bottom())], Stroke::new(1.5, t.text)); + let tip = Rect::from_x_y_ranges(x - 3.0..=x + 3.0, bar.top() - 3.0..=bar.bottom()); + ui.interact(tip, ui.scope_id().with("color-wheel-oklch-tick"), egui::Sense::hover()) + .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); + } + if let Some(x) = dragged { + out = Some((at(x), phase)); + } + if let Some(k) = keyed { + out = Some((with(i, k), Live::Released)); + } + if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { + out = Some((with(i, f), Live::Released)); + } + }); + } + }); + out.filter(|_| enabled) +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let tgt = wheel_target(app, ui); let color = tgt.color(); @@ -344,9 +519,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); - let Some((hsb, phase)) = pick else { return }; + let mut picked_lch = None; + if app.ui.color_wheel.sliders == Sliders::Oklch { + ui.add_space(4.0); + picked_lch = oklch_rows(app, ui, &tgt, color, &cms); + } let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); + if let Some((lch, phase)) = picked_lch { + let (srgb, _) = oklab::from_oklch(lch[0], lch[1], lch[2]); + let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); + apply(app, &tgt, c, phase, behind); + if !behind { + set_pstate(ui.ctx(), OKLCH_MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), lch))); + } + return; + } + let Some((hsb, phase)) = pick else { return }; let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 798a842e4c..e07dffa54a 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -11,7 +11,9 @@ use vectorcraft_color::cms::{self, Cms, ColorSettings, delta_e2000}; use vectorcraft_color::{Color, Paint}; use vectorcraft_engine::Session; -use super::color_wheel::{ID, display_hsb, remembered_hsb, show, stored}; +use super::color_wheel::{ + ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_oklch, set, show, stored, +}; use crate::VectorcraftApp; /// An app with a selected rectangle filled with `fill`. @@ -581,3 +583,260 @@ fn the_color_pickers_field_takes_the_arrow_keys() { assert!(near(stepped, [after[0], after[1] + 0.01, after[2]], [1e-3, 1e-4, 1e-4]), "{after:?} → {stepped:?}"); assert!(h.state().ui.dialog.is_some(), "the dialog stays open"); } + +/// The panel with OKLCH Sliders shown, in a flyout tall enough for the rows. +fn oklch_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + oklch_harness_shown(app) +} + +/// The panel in a flyout tall enough for the rows, with the app's settings as they are. +fn oklch_harness_shown(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 420.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +/// The slider row named `name` (its number field has the same name). +fn oklch_slider<'a>(h: &'a Harness<'static, VectorcraftApp>, name: &'a str) -> egui_kittest::Node<'a> { + h.query_all_by_label(name).find(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).expect("a slider row") +} + +/// The point at `t` (0..1) along the bar of a slider row. +fn on_rail(rail: Rect, t: f32) -> Pos2 { + Pos2::new(rail.left() + 4.0 + t * (rail.width() - 8.0), rail.top() + 7.0) +} + +fn fill_oklch(app: &VectorcraftApp) -> [f64; 3] { + vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&fill(app))) +} + +/// `ui.colorWheel {sliders: "oklch"}` shows L, C and H rows with the fill's OKLCH, and the panel +/// keeps the setting with the preferences. +#[test] +fn oklch_sliders_show_the_fills_lightness_chroma_and_hue() { + let h = oklch_harness(app(json!("#ff0000"))); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch); + let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap(); + assert_eq!((value("Lightness"), value("Chroma"), value("Hue")), (63.0, 64.0, 29.0)); + let saved = serde_json::to_value(&h.state().ui).unwrap(); + assert_eq!(saved["color_wheel"]["sliders"], json!("oklch")); +} + +/// A drag on L past the chroma sRGB holds stores the largest chroma that fits at the same hue, and +/// the C row keeps the chroma asked for, so dragging L back brings it back. +#[test] +fn a_drag_on_lightness_keeps_the_chroma_asked_for() { + let mut h = oklch_harness(app(json!("#0000ff"))); + let [l0, c0, h0] = fill_oklch(h.state()); + let rail = oklch_slider(&h, "Lightness").rect(); + drag(&mut h, &[on_rail(rail, l0 as f32), on_rail(rail, 0.9)], Modifiers::NONE); + let [l1, c1, h1] = fill_oklch(h.state()); + assert!((l1 - 0.9).abs() < 0.01 && c1 < c0 - 0.1 && (h1 - h0).abs() < 1.0, "{:?} → {:?}", [l0, c0, h0], [l1, c1, h1]); + let chroma = oklch_slider(&h, "Chroma").accesskit_node().numeric_value().unwrap(); + assert_eq!(chroma, (c0 / 0.4 * 100.0).round(), "the C row keeps the requested chroma"); + drag(&mut h, &[on_rail(rail, 0.9), on_rail(rail, l0 as f32)], Modifiers::NONE); + let [l2, c2, _] = fill_oklch(h.state()); + assert!((l2 - l0).abs() < 0.01 && (c2 - c0).abs() < 0.01, "{:?} → {:?}", [l0, c0], [l2, c2]); +} + +/// A press on a row gives it the keyboard focus, and → raises it by one unit as one undo step. +/// Each row reports its range and the adjust actions to screen readers. +#[test] +fn the_oklch_rows_take_the_arrow_keys_and_screen_readers_actions() { + let mut h = oklch_harness(app(json!("#808080"))); + for (name, max) in [("Lightness", 100.0), ("Chroma", 100.0), ("Hue", 360.0)] { + let node = oklch_slider(&h, name).accesskit_node(); + assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}"); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}"); + } + let rail = oklch_slider(&h, "Lightness").rect(); + let l = fill_oklch(h.state())[0]; + click(&mut h, on_rail(rail, l as f32), Modifiers::NONE); + let before = fill_oklch(h.state())[0]; + let undo = undo_len(h.state()); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + let after = fill_oklch(h.state())[0]; + assert!((after - ((before * 100.0).round() + 1.0) / 100.0).abs() < 0.003, "{before} → {after}"); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + let (target_node, target_tree) = oklch_slider(&h, "Hue").accesskit_node().locate(); + let data = Some(ActionData::NumericValue(200.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + // The frame that takes the request draws the row before it applies it. + h.run_steps(2); + assert_eq!(oklch_slider(&h, "Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step"); +} + +/// Each track dims the colors outside sRGB, and the C track's tick sits at the largest chroma sRGB +/// holds, along the track's 0 to 0.4. +#[test] +fn the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma() { + let (l, h) = (0.7, 150.0); + let max = vectorcraft_color::oklab::max_chroma(l, h); + for max_chroma in [Some(max), None] { + assert_eq!(oklch_track([l, max * 0.5, h], max_chroma).a(), 255, "{max_chroma:?}: inside sRGB"); + assert!(oklch_track([l, 0.4, h], max_chroma).a() < 255, "{max_chroma:?}: outside sRGB is dimmed"); + } + assert!((chroma_tick(max) - (max / 0.4) as f32).abs() < 1e-6 && chroma_tick(max) > 0.1 && chroma_tick(max) < 1.0); + assert_eq!((chroma_tick(0.0), chroma_tick(0.5)), (0.0, 1.0)); +} + +/// After Edit › Color Settings picks a working RGB space other than sRGB, Panel menu › OKLCH Sliders +/// is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows already shown are gray. +#[test] +fn oklch_sliders_are_gray_after_the_working_space_changes() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_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::oklch_sliders_are_gray_after_the_working_space_changes", "--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 mut app = app(json!("#ff0000")); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert_eq!(app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap_err(), "OKLCH needs sRGB as the working RGB space"); + assert_eq!(app.ui.color_wheel.sliders, Sliders::None); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app, + ); + h.run_steps(3); + assert!(h.get_by_label(" OKLCH Sliders").accesskit_node().is_disabled()); + // The color settings stay with the process, so a new app works in Display P3 as well. + let mut app = self::app(json!("#ff0000")); + app.ui.color_wheel.sliders = Sliders::Oklch; + let h = oklch_harness_shown(app); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); +} + +/// A CMYK fill's L, C and H are those of its display color, not of its naive separation. +#[test] +fn a_cmyk_fills_oklch_is_that_of_its_display_color() { + let h = oklch_harness(app(json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}))); + let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0))); + let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); + let lightness = oklch_slider(&h, "Lightness").accesskit_node().numeric_value().unwrap(); + assert_eq!(lightness, (shown[0] * 100.0).round()); + assert_ne!(lightness, (naive[0] * 100.0).round()); +} + +/// Panel menu › OKLCH Sliders shows the rows and, checked, hides them. +#[test] +fn the_panel_menu_shows_and_hides_the_oklch_rows() { + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which hold the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app(json!("#ff0000")), + ); + h.run_steps(3); + h.get_by_label(" OKLCH Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch); + h.get_by_label("✓ OKLCH Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None); +} + +/// In a working RGB space other than sRGB, `sliders: "oklch"` is an error and the rows are gray; +/// the error leaves the settings as they were. +#[test] +fn oklch_sliders_need_srgb_as_the_working_space() { + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let mut settings = Settings::default(); + assert_eq!(set(&mut settings, &json!({"sliders": "oklch"}), &p3).unwrap_err(), "OKLCH needs sRGB as the working RGB space"); + assert_eq!(settings.sliders, Sliders::None); + set(&mut settings, &json!({"sliders": "oklch"}), &Cms::default()).unwrap(); + assert_eq!(settings.sliders, Sliders::Oklch); + set(&mut settings, &json!({"sliders": "none"}), &p3).unwrap(); + assert_eq!(settings.sliders, Sliders::None, "the rows can be hidden in any working space"); + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + let tgt = super::color::wheel_target(app, ui); + let color = tgt.color(); + let _ = oklch_rows(app, ui, &tgt, color, &p3); + }, + app(json!("#ff0000")), + ); + h.run_steps(2); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); + let undo = undo_len(h.state()); + let rail = oklch_slider(&h, "Lightness").rect(); + click(&mut h, on_rail(rail, 0.2), Modifiers::NONE); + assert_eq!(undo_len(h.state()), undo, "a gray row picks nothing"); +} + +/// The rows show what they asked for while the color displays as it did, and the color's own +/// OKLCH after the color settings change its display. +#[test] +fn the_remembered_oklch_follows_a_change_of_working_space() { + let srgb = Cms::default(); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let c = Color::rgb(0.5, 0.3, 0.2); + let asked = [0.5, 0.3, 40.0]; + let shown = srgb.display_rgb(&c); + assert_eq!(remembered_oklch(&srgb, &c, shown, asked), asked); + assert_eq!(remembered_oklch(&p3, &c, shown, asked), vectorcraft_color::oklab::to_oklch(p3.display_rgb(&c))); +} + +/// Saved settings are read key by key: a value this version does not know (one a newer version +/// wrote) gives the default, and the other preferences still load. +#[test] +fn saved_color_wheel_settings_are_read_leniently() { + let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); + saved["color_rgb_percent"] = json!(true); + for (value, sliders) in + [(json!({"sliders": "oklch"}), Sliders::Oklch), (json!({"sliders": "hsl", "view": "box"}), Sliders::None), (json!(5), Sliders::None)] + { + saved["color_wheel"] = value.clone(); + let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!((ui.color_wheel.sliders, ui.color_rgb_percent), (sliders, true), "{value}"); + } +} + +/// `ui.colorWheel {sliders}` sets the rows and keeps the view and the channel, and an unknown +/// `sliders` value is an error that changes nothing. +#[test] +fn ui_color_wheel_sets_and_reads_the_sliders() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap(); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none")); + assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap_err(), "`sliders` must be none or oklch"); + let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + assert_eq!(got, json!({"view": "box", "channel": "red", "sliders": "oklch"})); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hsl"})).unwrap_err(); + assert_eq!(e, "`sliders` must be none or oklch"); + assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index d3866fd5d9..3a4280f533 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,16 +167,16 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"})); - assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"})); - assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"})); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "sliders": "none"})); + assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "sliders": "none"})); + assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green", "sliders": "none"})); let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); assert_eq!(e, "`view` must be wheel or box"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err(); assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, ..Default::default() }, "an error changes nothing"); let ui = crate::control::inspect(&app, &egui::Context::default()); - assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"})); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "sliders": "none"})); } /// The command's errors are translated in the catalogs that translate status and error messages, @@ -211,10 +211,10 @@ fn ui_color_wheel_rejects_other_params() { let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); assert_eq!(e, "the params must be an object, not [1]"); let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); - assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } /// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does, @@ -249,7 +249,11 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() { /// not know reads as the key's default without losing the other preferences. #[test] fn the_settings_are_kept_and_read_leniently() { - let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() }; + let ui = crate::UiState { + color_wheel: Settings { view: View::Box, channel: Channel::Blue, ..Default::default() }, + color_rgb_percent: true, + ..Default::default() + }; let saved = serde_json::to_value(&ui).unwrap(); let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); assert_eq!(back.color_wheel, ui.color_wheel); @@ -262,11 +266,11 @@ fn the_settings_are_kept_and_read_leniently() { let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "box", "channel": 7}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() }); + assert_eq!(back.color_wheel, Settings { view: View::Box, ..Default::default() }); let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue }); + assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue, ..Default::default() }); let mut odd = saved; odd["color_wheel"] = json!("box"); let back: crate::UiState = serde_json::from_value(odd).unwrap(); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d1722e8b72..5c1e98f2d1 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -734,7 +734,7 @@ pub struct UiState { /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub color_rgb_percent: bool, - /// Color Wheel panel: the wheel or the box, and the box's channel (`ui.colorWheel`, + /// Color Wheel panel: the wheel or the box, the box's channel and the slider rows (`ui.colorWheel`, /// [`crate::panels::color_wheel::deserialize_settings`]). #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] pub color_wheel: crate::panels::color_wheel::Settings, diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 2ace2c7a67..e197a24f4a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -27,8 +27,8 @@ pub use blend::{ reference_point_named, }; pub use buttons::{ - SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_name, paint_icon_button, primary_button, - primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, + SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_name, menu_item_name_hint, paint_icon_button, + primary_button, primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, }; pub(crate) use buttons::{button_width, icon_button_info, primary_button_width, secondary_button_width}; #[cfg(test)] diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index a33f7cac84..e2bd87a7e2 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -204,6 +204,16 @@ pub fn menu_item(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool /// [`menu_item`] for a name that is user or file data (a library, a recent URL), never translated. /// Like the menu bar's items, the row lights up under the pointer. pub fn menu_item_name(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool { + menu_row(ui, label, enabled, checked).clicked() +} + +/// [`menu_item_name`] that shows `hint` (already translated) under the pointer while the row is +/// disabled, to say why it is gray. +pub fn menu_item_name_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hint: &str) -> bool { + menu_row(ui, label, enabled, checked).on_disabled_hover_text(hint).clicked() +} + +fn menu_row(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response { let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; - ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)).clicked() + ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bb13e0d5f5..1d9970bf40 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -265,8 +265,9 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?}` shows the wheel or the box (a -color field with a channel strip at its right) and picks the box's channel; it returns the settings, and `ui.inspect` +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, sliders?}` shows the wheel or +the box (a color field with a channel strip at its right), picks the box's channel, and shows or hides OKLCH Sliders +(`sliders: "oklch"` is an error while the working RGB space is not sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ diff --git a/docs/mcp.md b/docs/mcp.md index 12c1f38184..d8b25024ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -623,8 +623,12 @@ and answers true when the fields show in percent. `ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off -the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with -the preferences. +the list return an error and change nothing. The command returns `{view, channel, sliders}`, and the settings are +kept with the preferences. + +`ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or +the box), and `"none"` hides them; `"oklch"` is an error while the working RGB space is not sRGB. `color.convert {"to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB, +and headless MCP reaches it too. 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e34f814534..babcf7be6c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1503,6 +1503,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. + - **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"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. From 3608506214e0ce5229dada21edf09f386b73365b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:27:39 -0800 Subject: [PATCH 02/51] Color Wheel: OKLCH Sliders place the chroma tick on the drawn rail - The C row's tick reads the slider's own rect, so it stays on the bar when the row is taller than the rail. `color_rail_bar` gives the bar for both the rail and the tick. - The L and H tracks show a color outside sRGB at the largest chroma that fits, the color a pick there stores, instead of clamping each channel. - The menu item uses `menu_item_hint`, which translates like `menu_item`, and `menu_item_name` is unchanged. - `color.convert {to: "oklch"}` says that any color outside sRGB (Lab, CMYK, or RGB in a wider working RGB space) is clipped to sRGB first, with a test for a Lab color. - docs/mcp.md wraps the new paragraph; gu.tsv puts the new rows where the other catalogs put them. --- crates/engine/src/cmd/colormgmt.rs | 2 +- crates/engine/src/tests/colormgmt.rs | 6 ++++++ crates/ui-egui/src/i18n/gu.tsv | 10 +++++----- crates/ui-egui/src/panels/color_wheel.rs | 19 ++++++++++--------- .../ui-egui/src/panels/tests_color_wheel.rs | 6 ++++++ crates/ui-egui/src/widgets.rs | 4 ++-- crates/ui-egui/src/widgets/buttons.rs | 16 ++++++++-------- crates/ui-egui/src/widgets/color.rs | 7 ++++++- docs/mcp.md | 5 +++-- 9 files changed, 47 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index c9d4daa0a9..8a7c8d29db 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Convert Color", [], None, - "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; in a working RGB space other than sRGB, a color outside sRGB is clamped to sRGB first", + "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first", always, convert_color ), diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index cdc774da7f..f28bbaf0d3 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -317,6 +317,12 @@ fn convert_to_oklch_answers_lightness_chroma_and_hue() { let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); let l = cyan["values"][0].as_f64().unwrap() / 100.0; assert!((l - shown[0]).abs() < 1e-9 && (l - naive[0]).abs() > 0.02, "{cyan} {shown:?} {naive:?}"); + // A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB. + let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap(); + let w: Vec = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let clipped = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0))); + assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}"); + assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}"); } #[test] diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index fd6f9f7419..e4a519d121 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -640,11 +640,6 @@ Color Themes રંગ થીમ Color Type: રંગ પ્રકાર: Color Wheel રંગ વ્હીલ - OKLCH Sliders OKLCH સ્લાઇડર્સ - Chroma ક્રોમા - The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા - OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે - Lightness લાઇટનેસ Color blindness – Deuteranopia-type રંગ અંધત્વ – ડ્યુટેરેનોપિયા પ્રકાર Color blindness – Protanopia-type રંગ અંધત્વ – પ્રોટેનોપિયા પ્રકાર Color blindness – Tritanopia-type રંગ અંધત્વ – ટ્રિટેનોપિયા પ્રકાર @@ -1852,6 +1847,11 @@ Knife નાઇફ Knockout Group નૉકઆઉટ ગ્રૂપ LZW Compression LZW કમ્પ્રેશન + OKLCH Sliders OKLCH સ્લાઇડર્સ + Chroma ક્રોમા + The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા + OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે + Lightness લાઇટનેસ Lab Spot Colors: Lab સ્પોટ રંગો: Landscape લેન્ડસ્કેપ Language ભાષા diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 64393be866..2a88a3f54a 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -196,7 +196,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let on = set.sliders == Sliders::Oklch; // While the rows show, the item stays enabled so that they can be hidden. let enabled = on || cms::active().rgb_is_srgb(); - if widgets::menu_item_name_hint(ui, tl!("OKLCH Sliders"), enabled, on, tl!("OKLCH needs sRGB as the working RGB space")) { + if widgets::menu_item_hint(ui, tl!("OKLCH Sliders"), enabled, on, tl!("OKLCH needs sRGB as the working RGB space")) { let sliders = if on { Sliders::None } else { Sliders::Oklch }; if let Err(e) = app.run("ui.colorWheel", json!({ "sliders": sliders.id() })) { app.status(e); @@ -385,15 +385,16 @@ pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; } /// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed. -/// With `max_chroma` (the C track, whose L and H stay fixed) a chroma past it shows the color at -/// that chroma; without it, a color outside sRGB shows clamped to it. +/// A color outside sRGB shows at the largest chroma that fits at its L and H, the color a pick +/// there stores. With `max_chroma` (the C track, whose L and H stay fixed) that chroma is given; +/// without it, it is found for each color. pub(crate) fn oklch_track(lch: [f64; 3], max_chroma: Option) -> Color32 { let (rgb, outside) = match max_chroma { Some(m) if lch[1] > m => (oklab::oklch_to_srgb(lch[0], m, lch[2]), true), Some(_) => (oklab::oklch_to_srgb(lch[0], lch[1], lch[2]), false), None => { - let exact = oklab::oklch_to_srgb(lch[0], lch[1], lch[2]); - (exact, !oklab::in_srgb(exact)) + let (rgb, lowered) = oklab::from_oklch(lch[0], lch[1], lch[2]); + (rgb.map(f64::from), lowered) } }; let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); @@ -446,13 +447,13 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: let v = shown[i].clamp(0.0, max); let at = |x: f32| with(i, f64::from(x) * max); let track = |x: f32| if enabled { oklch_track(at(x), (i == 1).then_some(max_c)) } else { t.input }; - let rail = Rect::from_min_size(ui.cursor().min, vec2(slider_w, 22.0)); let value = SliderValue::field(v, 0.0..=max, suffix, 0); let (dragged, phase, keyed) = widgets::color_slider_stepped(ui, ("color-wheel-oklch", i), name, Some(value), (v / max) as f32, slider_w, &track); - if i == 1 && enabled { - // The bar of `color_slider_stepped`'s rail: 4 points in from its left, top and right. - let bar = Rect::from_min_size(rail.min + vec2(4.0, 4.0), vec2(slider_w - 8.0, 7.0)); + // The tick goes on the bar of the rail as the row laid it out. + let rail = (i == 1 && enabled).then(|| ui.ctx().read_response(widgets::id_with(ui.scope_id(), ("color-wheel-oklch", i)))).flatten(); + if let Some(rail) = rail { + let bar = widgets::color_rail_bar(rail.rect); let x = bar.left() + chroma_tick(max_c) * bar.width(); ui.painter().line_segment([pos2(x, bar.top() - 3.0), pos2(x, bar.bottom())], Stroke::new(1.5, t.text)); let tip = Rect::from_x_y_ranges(x - 3.0..=x + 3.0, bar.top() - 3.0..=bar.bottom()); diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index e07dffa54a..407f6ffabe 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -685,6 +685,12 @@ fn the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_c assert_eq!(oklch_track([l, max * 0.5, h], max_chroma).a(), 255, "{max_chroma:?}: inside sRGB"); assert!(oklch_track([l, 0.4, h], max_chroma).a() < 255, "{max_chroma:?}: outside sRGB is dimmed"); } + // Near white, an L or H track shows the color a pick there stores: the largest chroma that fits, + // not each channel clamped on its own. + let (stored, lowered) = vectorcraft_color::oklab::from_oklch(0.98, 0.2, h); + let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(lowered); + assert_eq!(oklch_track([0.98, 0.2, h], None), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); assert!((chroma_tick(max) - (max / 0.4) as f32).abs() < 1e-6 && chroma_tick(max) > 0.1 && chroma_tick(max) < 1.0); assert_eq!((chroma_tick(0.0), chroma_tick(0.5)), (0.0, 1.0)); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index e197a24f4a..d481984f58 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -27,7 +27,7 @@ pub use blend::{ reference_point_named, }; pub use buttons::{ - SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_name, menu_item_name_hint, paint_icon_button, + SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_hint, menu_item_name, paint_icon_button, primary_button, primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, }; pub(crate) use buttons::{button_width, icon_button_info, primary_button_width, secondary_button_width}; @@ -39,7 +39,7 @@ pub use color::{ color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_square, segment_color, segmented_wheel, stepped_area, }; -pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase}; +pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, hex_text, pointer_phase}; pub use drag::{ PanelDrag, RowClick, SwatchRows, apply_row_click, art_drop, doc_preview, drag_ghost, drag_source, drop_target_outline, ghost_row, row_click, }; diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index e2bd87a7e2..7ddf88bda5 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -204,16 +204,16 @@ pub fn menu_item(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool /// [`menu_item`] for a name that is user or file data (a library, a recent URL), never translated. /// Like the menu bar's items, the row lights up under the pointer. pub fn menu_item_name(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool { - menu_row(ui, label, enabled, checked).clicked() + let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; + ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)).clicked() } -/// [`menu_item_name`] that shows `hint` (already translated) under the pointer while the row is -/// disabled, to say why it is gray. -pub fn menu_item_name_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hint: &str) -> bool { - menu_row(ui, label, enabled, checked).on_disabled_hover_text(hint).clicked() -} - -fn menu_row(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response { +/// [`menu_item`] that shows `hint` under the pointer while the row is disabled, to say why it is +/// gray. +pub fn menu_item_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hint: &str) -> bool { + let label = tl!(label); let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) + .on_disabled_hover_text(tl!(hint)) + .clicked() } diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index f7c1d9365b..eb5f11d150 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -265,6 +265,11 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Rect { + Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(rect.width() - 8.0, 7.0)) +} + /// The rail of [`color_slider_valued`] with the id `id`: its response, the new value from 0 to 1 /// that a click or drag gives and the phase. fn color_rail( @@ -278,7 +283,7 @@ fn color_rail( ) -> (Response, Option, Live) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); - let bar = Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(width - 8.0, 7.0)); + let bar = color_rail_bar(rect); let resp = ui.interact(rect, id, Sense::click_and_drag()); gradient_strip(ui, bar, (bar.width() / 2.0).ceil().max(2.0) as usize, false, track); ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); diff --git a/docs/mcp.md b/docs/mcp.md index d8b25024ff..3734007f6d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -627,8 +627,9 @@ the list return an error and change nothing. The command returns `{view, channel kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or -the box), and `"none"` hides them; `"oklch"` is an error while the working RGB space is not sRGB. `color.convert {"to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB, -and headless MCP reaches it too. +the box), and `"none"` hides them; `"oklch"` is an error while the working RGB space is not sRGB. +`color.convert {"to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. A color outside sRGB +(a Lab or CMYK color, or an RGB color in a wider working RGB space) is clipped to sRGB first. 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 f5e9840333bf2362e2daa06f03e537c48e33a6d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:49:32 -0800 Subject: [PATCH 03/51] Color Wheel: HSL Sliders edit a color by hue, saturation and lightness MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #978. The Color Wheel panel menu gains HSL Sliders, shown in place of OKLCH Sliders: H (0 to 360°), S and L (0 to 100 %) rows under the wheel or the box that edit the hue, saturation and lightness of the color's display sRGB, as CSS Color 4 defines HSL (https://www.w3.org/TR/css-color-4/#the-hsl-notation). A pick goes into the working RGB space as the wheel's picks do, the rows keep the hue of a gray, and they take the arrow keys and report their names, values and ranges to screen readers as the OKLCH rows do. - vectorcraft-color: rgb_to_hsl and hsl_to_rgb follow the conversions in CSS Color 4 sections 7.1 and 7.2, with Color::to_hsl and Color::from_hsl beside to_hsb and from_hsb. - ui.colorWheel takes sliders: "hsl"; an unknown value now answers "`sliders` must be none, oklch or hsl". - Docs: docs/mcp.md, docs/control-protocol.md and the Color Wheel evidence in docs/target-app-parity.md. --- crates/color/src/lib.rs | 100 +++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 3 +- crates/ui-egui/src/i18n/bs.tsv | 3 +- crates/ui-egui/src/i18n/ca.tsv | 3 +- crates/ui-egui/src/i18n/cs.tsv | 3 +- crates/ui-egui/src/i18n/da.tsv | 3 +- crates/ui-egui/src/i18n/de.tsv | 3 +- crates/ui-egui/src/i18n/el.tsv | 3 +- crates/ui-egui/src/i18n/es.tsv | 3 +- crates/ui-egui/src/i18n/fi.tsv | 3 +- crates/ui-egui/src/i18n/fr.tsv | 3 +- crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 3 +- crates/ui-egui/src/i18n/hu.tsv | 3 +- crates/ui-egui/src/i18n/id.tsv | 3 +- crates/ui-egui/src/i18n/it.tsv | 3 +- crates/ui-egui/src/i18n/ja.tsv | 3 +- crates/ui-egui/src/i18n/ka.tsv | 3 +- crates/ui-egui/src/i18n/ko.tsv | 3 +- crates/ui-egui/src/i18n/nl.tsv | 3 +- crates/ui-egui/src/i18n/pl.tsv | 3 +- crates/ui-egui/src/i18n/pt-br.tsv | 3 +- crates/ui-egui/src/i18n/ru.tsv | 3 +- crates/ui-egui/src/i18n/sv.tsv | 3 +- crates/ui-egui/src/i18n/tr.tsv | 3 +- crates/ui-egui/src/i18n/uk.tsv | 3 +- crates/ui-egui/src/i18n/vi.tsv | 3 +- crates/ui-egui/src/i18n/zh-hans.tsv | 3 +- crates/ui-egui/src/i18n/zh-hant.tsv | 3 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 125 ++++++++++-- .../ui-egui/src/panels/tests_color_wheel.rs | 192 +++++++++++++++++- docs/control-protocol.md | 6 +- docs/mcp.md | 2 + docs/target-app-parity.md | 1 + 36 files changed, 461 insertions(+), 51 deletions(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 846dadb940..8180f1c459 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -151,6 +151,15 @@ impl Color { let [r, g, b] = hsb_to_rgb([h, s, v]); Color::Rgb { r, g, b } } + /// HSL with hue in degrees 0..360, saturation and lightness 0..1 ([`rgb_to_hsl`] of the + /// display color). + pub fn to_hsl(&self) -> [f32; 3] { + rgb_to_hsl(self.to_rgb()) + } + pub fn from_hsl(h: f32, s: f32, l: f32) -> Self { + let [r, g, b] = hsl_to_rgb([h, s, l]); + Color::Rgb { r, g, b } + } /// `#rrggbb` (display RGB). pub fn to_hex(&self) -> String { let [r, g, b, _] = self.to_rgba8(1.0); @@ -341,6 +350,48 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] { [r + m, g + m, b + m] } +/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color +/// conversion, as CSS Color 4 converts sRGB to HSL +/// (). The hue is 0 while the saturation is +/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in +/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001 +/// below 1, or a saturation of 0.00001 or less reads as a gray. +pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] { + const EPSILON: f32 = 1e-5; + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let d = max - min; + let l = (max + min) / 2.0; + if d <= 0.0 { + return [0.0, 0.0, l]; + } + let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) }; + let mut h = rgb_to_hsb([r, g, b])[0]; + if s < 0.0 { + h += 180.0; + s = -s; + } + if s <= EPSILON { + return [0.0, 0.0, l]; + } + let h = h.rem_euclid(360.0); + [if h >= 360.0 { 0.0 } else { h }, s, l] +} + +/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS +/// Color 4 converts HSL to sRGB (): the inverse of +/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range, so -120° gives the color of 240°. +/// The specification's sample code uses JavaScript's remainder operator and gives a different +/// color for a negative hue. +pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] { + let a = s * l.min(1.0 - l); + let f = |n: f32| { + let k = (n + h / 30.0).rem_euclid(12.0); + l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0) + }; + [f(0.0), f(8.0), f(4.0)] +} + /// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations /// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from. pub fn keep_model(orig: Color, new: Color) -> Color { @@ -500,6 +551,55 @@ mod tests { } } + /// The HSL examples of CSS Color 4, section 7 (), + /// the first six rows, and two hues outside 0..360 that wrap into that range. + #[test] + fn hsl_follows_css_color_4() { + for (hsl, hex) in [ + ([0.0, 1.0, 0.5], "#ff0000"), + ([120.0, 1.0, 0.5], "#00ff00"), + ([120.0, 1.0, 0.25], "#008000"), + ([120.0, 1.0, 0.75], "#80ff80"), + ([240.0, 1.0, 0.5], "#0000ff"), + ([60.0, 1.0, 0.5], "#ffff00"), + ([360.0, 1.0, 0.5], "#ff0000"), + ([-120.0, 1.0, 0.5], "#0000ff"), + ] { + assert_eq!(Color::from_hsl(hsl[0], hsl[1], hsl[2]).to_hex(), hex, "{hsl:?}"); + } + let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]); + assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}"); + let [h, s, l] = Color::rgb8(255, 128, 0).to_hsl(); + assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}"); + // A gray has no hue: the hue is 0 and the saturation 0, at any lightness. + for v in [0.0, 0.25, 0.5, 1.0] { + assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]); + } + // Black and white keep any hue and saturation they are given. + assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]); + assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]); + // A color past the gamut that gives a negative saturation turns its hue by 180°. + let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]); + assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}"); + } + + /// The 216 web colors go to HSL and back to the same 8-bit color. + #[test] + fn hsl_roundtrip() { + let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff]; + for r in steps { + for g in steps { + for b in steps { + let c = Color::rgb8(r, g, b); + let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated()); + assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex()); + let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8); + assert_eq!(back, [r, g, b], "{}", c.to_hex()); + } + } + } + } + #[test] fn cmyk_conversions() { assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ae517a6b7b..14671dbe78 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1354,7 +1354,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ab505f121b..96082641cc 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1765,6 +1765,7 @@ font-technology Variable Променливи Knockout Group Група с изрязване Lab Lab OKLCH Sliders Плъзгачи OKLCH + HSL Sliders Плъзгачи HSL Chroma Хрома The largest chroma sRGB holds at this lightness and hue Най-голямата хрома, която sRGB побира при тази светлина и този оттенък OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство @@ -4264,7 +4265,7 @@ axis Both И двете @msg `aspect` must be a number (%) `aspect` трябва да бъде число (%) @msg `at` must be [x, y] `at` трябва да бъде [x, y] @msg `color` must be a colour `color` трябва да бъде цвят -@msg `sliders` must be none or oklch `sliders` трябва да бъде none или oklch +@msg `sliders` must be none, oklch or hsl `sliders` трябва да бъде none, oklch или hsl @msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство @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 13731ee514..8a31e4b028 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4213,6 +4213,7 @@ axis Both Obje Ink Tinta Lab Lab OKLCH Sliders OKLCH klizači + HSL Sliders HSL klizači Chroma Hroma The largest chroma sRGB holds at this lightness and hue Najveća hroma koju sRGB obuhvata pri ovoj svjetloći i nijansi OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor @@ -4673,7 +4674,7 @@ imageTrace Outline Obris @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe @msg `view` must be wheel or box `view` mora biti wheel ili box @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 `sliders` must be none, oklch or hsl `sliders` mora biti none, oklch ili hsl @msg OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor @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 66e580261c..9517f4a375 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2263,6 +2263,7 @@ digits Malayalam Malaiàlam Knockout Group Grup knockout Lab Lab OKLCH Sliders Controls lliscants OKLCH + HSL Sliders Controls lliscants HSL Chroma Croma The largest chroma sRGB holds at this lightness and hue El croma més gran que sRGB admet amb aquesta lluminositat i aquest to OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball @@ -5294,7 +5295,7 @@ digits Malayalam Malaiàlam @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` ha de ser wheel o box @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 `sliders` must be none, oklch or hsl `sliders` ha de ser none, oklch o hsl @msg OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball @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 be19b2b1f0..e7b438f8e8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4269,6 +4269,7 @@ axis Both Obě Ink Inkoust Lab Lab OKLCH Sliders Posuvníky OKLCH + HSL Sliders Posuvníky HSL Chroma Chroma The largest chroma sRGB holds at this lightness and hue Největší chroma, kterou sRGB obsáhne při této světlosti a odstínu OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB @@ -4836,7 +4837,7 @@ imageTrace Outline Obrys @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe @msg `view` must be wheel or box `view` musí být wheel nebo box @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 `sliders` must be none, oklch or hsl `sliders` musí být none, oklch nebo hsl @msg OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB @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 4e49d32782..48e4c5cd03 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4588,6 +4588,7 @@ axis Both Begge Ink Blæk Lab Lab OKLCH Sliders OKLCH-skydere + HSL Sliders HSL-skydere Chroma Kroma The largest chroma sRGB holds at this lightness and hue Den største kroma, sRGB kan rumme ved denne lyshed og farvetone OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum @@ -6272,7 +6273,7 @@ mark-style Japanese Japansk @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` skal være wheel eller box @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 `sliders` must be none, oklch or hsl `sliders` skal være none, oklch eller hsl @msg OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum @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 2bdb11e926..2402fea14b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1827,6 +1827,7 @@ file-filter Templates Vorlagen Knockout Group Aussparungsgruppe Lab Lab OKLCH Sliders OKLCH-Regler + HSL Sliders HSL-Regler Chroma Chroma The largest chroma sRGB holds at this lightness and hue Das größte Chroma, das sRGB bei dieser Helligkeit und diesem Farbton enthält OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum @@ -4449,7 +4450,7 @@ theme Appearance Erscheinungsbild @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein @msg `view` must be wheel or box `view` muss wheel oder box sein @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 `sliders` must be none, oklch or hsl `sliders` muss none, oklch oder hsl sein @msg OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum @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 8714c99bc4..4be5c75096 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1728,6 +1728,7 @@ font-technology Variable Μεταβλητές Knockout Group Ομάδα διάτρησης Lab Lab OKLCH Sliders Ρυθμιστικά OKLCH + HSL Sliders Ρυθμιστικά HSL Chroma Χρωματική ένταση The largest chroma sRGB holds at this lightness and hue Η μεγαλύτερη χρωματική ένταση που χωρά το sRGB σε αυτή τη φωτεινότητα και απόχρωση OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB @@ -6123,7 +6124,7 @@ effect Points Σημεία @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe @msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box @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 `sliders` must be none, oklch or hsl Το `sliders` πρέπει να είναι none, oklch ή hsl @msg OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB @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 4302320f81..f44c51605f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1821,6 +1821,7 @@ font-technology Variable Variables Knockout Group Grupo de exclusión Lab Lab OKLCH Sliders Controles deslizantes OKLCH + HSL Sliders Controles deslizantes HSL Chroma Croma The largest chroma sRGB holds at this lightness and hue El croma más alto que admite sRGB con esta luminosidad y este tono OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB @@ -4526,7 +4527,7 @@ axis Both Ambos @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` debe ser wheel o box @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 `sliders` must be none, oklch or hsl `sliders` debe ser none, oklch o hsl @msg OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB @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 be85c4b560..ac35ad665d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4188,6 +4188,7 @@ axis Both Molemmat Ink Muste Lab Lab OKLCH Sliders OKLCH-liukusäätimet + HSL Sliders HSL-liukusäätimet Chroma Kroma The largest chroma sRGB holds at this lightness and hue Suurin kroma, jonka sRGB sisältää tällä vaaleudella ja sävyllä OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi @@ -6134,7 +6135,7 @@ mark-style Japanese Japanilainen @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe @msg `view` must be wheel or box `view`-arvon on oltava wheel tai box @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 `sliders` must be none, oklch or hsl `sliders` on oltava none, oklch tai hsl @msg OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi @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 620508ac05..5975b5f957 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1815,6 +1815,7 @@ font-technology Variable Variables Knockout Group Groupe perçant Lab Lab OKLCH Sliders Curseurs OKLCH + HSL Sliders Curseurs HSL Chroma Chroma The largest chroma sRGB holds at this lightness and hue Le plus grand chroma que sRGB contient à cette luminosité et cette teinte OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB @@ -4515,7 +4516,7 @@ axis Both Les deux @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` doit valoir wheel ou box @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 `sliders` must be none, oklch or hsl `sliders` doit valoir none, oklch ou hsl @msg OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB @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 32c652dd0c..5ac1a3004e 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1853,6 +1853,7 @@ Knockout Group નૉકઆઉટ ગ્રૂપ LZW Compression LZW કમ્પ્રેશન OKLCH Sliders OKLCH સ્લાઇડર્સ + HSL Sliders HSL સ્લાઇડર્સ Chroma ક્રોમા The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 83a994aa31..04c8ead6f3 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2502,6 +2502,7 @@ antiAlias Sharp शार्प Knockout Group नॉकआउट समूह Lab Lab OKLCH Sliders OKLCH स्लाइडर्स + HSL Sliders HSL स्लाइडर्स Chroma क्रोमा The largest chroma sRGB holds at this lightness and hue इस लाइटनेस और ह्यू पर sRGB में आने वाला सबसे अधिक क्रोमा OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए @@ -6186,7 +6187,7 @@ antiAlias Sharp शार्प @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए @msg `view` must be wheel or box `view` को wheel या box होना चाहिए @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 `sliders` must be none, oklch or hsl `sliders` none, oklch या hsl होना चाहिए @msg OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए @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 440a1502ce..bbbc9dcb08 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2278,6 +2278,7 @@ file-filter Templates Sablonok Knockout Group Kiütő csoport Lab Lab OKLCH Sliders OKLCH csúszkák + HSL Sliders HSL csúszkák Chroma Króma The largest chroma sRGB holds at this lightness and hue A legnagyobb króma, amelyet az sRGB ezen a világosságon és színárnyalaton tartalmaz OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges @@ -4951,7 +4952,7 @@ imageTrace Outline Körvonal @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell @msg `view` must be wheel or box `view`: wheel vagy box kell @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 `sliders` must be none, oklch or hsl A `sliders` értéke none, oklch vagy hsl lehet @msg OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges @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 cafd55eb3b..7247ddb603 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3979,6 +3979,7 @@ axis Both Keduanya Ink Tinta Lab Lab OKLCH Sliders Penggeser OKLCH + HSL Sliders Penggeser HSL Chroma Kroma The largest chroma sRGB holds at this lightness and hue Kroma terbesar yang dapat dimuat sRGB pada kecerahan dan rona ini OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja @@ -5662,7 +5663,7 @@ mark-style Japanese Jepang @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe @msg `view` must be wheel or box `view` harus wheel atau box @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 `sliders` must be none, oklch or hsl `sliders` harus none, oklch, atau hsl @msg OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja @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 7bdc9e209b..927e633748 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1859,6 +1859,7 @@ file-filter Templates Modelli Knockout Group Gruppo con foratura Lab Lab OKLCH Sliders Cursori OKLCH + HSL Sliders Cursori HSL Chroma Croma The largest chroma sRGB holds at this lightness and hue Il croma più alto che sRGB contiene con questa luminosità e tonalità OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB @@ -4578,7 +4579,7 @@ axis Both Entrambi @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` deve essere wheel o box @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 `sliders` must be none, oklch or hsl `sliders` deve essere none, oklch o hsl @msg OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB @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 afdd3199b9..dcbf8bac90 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3917,6 +3917,7 @@ file-filter Templates テンプレート Keep: 保持: Lab Lab OKLCH Sliders OKLCH スライダー + HSL Sliders HSL スライダー Chroma クロマ The largest chroma sRGB holds at this lightness and hue この明度と色相で sRGB に収まる最大のクロマ OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です @@ -5039,7 +5040,7 @@ swatch Bright Violet ビビッドバイオレット @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください @msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください @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 `sliders` must be none, oklch or hsl `sliders` には none、oklch、hsl のいずれかを指定してください @msg OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です @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 943314c94e..834ebf3333 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3799,6 +3799,7 @@ axis Both ორივე Ink მელანი Lab Lab OKLCH Sliders OKLCH სლაიდერები + HSL Sliders HSL სლაიდერები Chroma ქრომა The largest chroma sRGB holds at this lightness and hue უდიდესი ქრომა, რომელსაც sRGB იტევს ამ სიღიავესა და ფერის ტონზე OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება @@ -5819,7 +5820,7 @@ imageTrace Outline კონტური @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe @msg `view` must be wheel or box `view` უნდა იყოს wheel ან box @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 `sliders` must be none, oklch or hsl `sliders` უნდა იყოს none, oklch ან hsl @msg OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება @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 575b9832f1..d79e7eb9ed 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3905,6 +3905,7 @@ file-filter Templates 템플릿 Keep: 유지: Lab Lab OKLCH Sliders OKLCH 슬라이더 + HSL Sliders HSL 슬라이더 Chroma 크로마 The largest chroma sRGB holds at this lightness and hue 이 명도와 색조에서 sRGB가 담을 수 있는 최대 크로마 OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 @@ -4966,7 +4967,7 @@ theme Appearance 외관 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다 @msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다 @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 `sliders` must be none, oklch or hsl `sliders`는 none, oklch 또는 hsl이어야 합니다 @msg OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 @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 b9253f4126..24102c783c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4497,6 +4497,7 @@ axis Both Beide Ink Inkt Lab Lab OKLCH Sliders OKLCH-schuifregelaars + HSL Sliders HSL-schuifregelaars Chroma Chroma The largest chroma sRGB holds at this lightness and hue De grootste chroma die sRGB bij deze helderheid en tint bevat OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte @@ -8060,7 +8061,7 @@ mark-style Japanese Japans @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn @msg `view` must be wheel or box `view` moet wheel of box zijn @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 `sliders` must be none, oklch or hsl `sliders` moet none, oklch of hsl zijn @msg OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte @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 0bc13e2719..56c090925b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4110,6 +4110,7 @@ axis Both Obie Ink Farba Lab Lab OKLCH Sliders Suwaki OKLCH + HSL Sliders Suwaki HSL Chroma Chroma The largest chroma sRGB holds at this lightness and hue Największa chroma, jaką sRGB mieści przy tej jasności i barwie OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB @@ -4660,7 +4661,7 @@ imageTrace Outline Kontur @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe @msg `view` must be wheel or box `view` musi mieć wartość wheel lub box @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 `sliders` must be none, oklch or hsl `sliders` musi mieć wartość none, oklch lub hsl @msg OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB @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 1930951832..cdab6fb420 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5059,6 +5059,7 @@ axis Both Ambos @plural {n} part of the file wasn't read|{n} parts of the file weren't read {n} parte do arquivo não foi lida|{n} partes do arquivo não foram lidas Lab Lab OKLCH Sliders Controles Deslizantes OKLCH + HSL Sliders Controles Deslizantes HSL Chroma Croma The largest chroma sRGB holds at this lightness and hue O maior croma que o sRGB comporta nesta luminosidade e neste tom OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB @@ -6121,7 +6122,7 @@ mark-style Japanese Japonesas @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` deve ser wheel ou box @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 `sliders` must be none, oklch or hsl `sliders` deve ser none, oklch ou hsl @msg OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB @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 f3837f3b39..21fc4784fe 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1848,6 +1848,7 @@ file-filter Templates Шаблоны Knockout Group Группа с вырезанием Lab Lab OKLCH Sliders Ползунки OKLCH + HSL Sliders Ползунки HSL Chroma Хрома The largest chroma sRGB holds at this lightness and hue Наибольшая хрома, которую вмещает sRGB при этой светлоте и оттенке OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB @@ -4563,7 +4564,7 @@ axis Both Оба @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe @msg `view` must be wheel or box `view` должно быть wheel или box @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 `sliders` must be none, oklch or hsl `sliders` должен быть none, oklch или hsl @msg OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB @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 4179e375c2..4b9f7e1422 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1776,6 +1776,7 @@ font-technology Variable Variabla Knockout Group Utsparningsgrupp Lab Lab OKLCH Sliders OKLCH-reglage + HSL Sliders HSL-reglage Chroma Kroma The largest chroma sRGB holds at this lightness and hue Den största kroma som sRGB rymmer vid denna ljushet och nyans OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd @@ -6123,7 +6124,7 @@ theme Appearance Utseende @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` måste vara wheel eller box @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 `sliders` must be none, oklch or hsl `sliders` måste vara none, oklch eller hsl @msg OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd @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/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3ebb0cda79..812dbdfe27 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1655,6 +1655,7 @@ font-technology Variable Değişken Knockout Group Nakavt Grubu Lab Laboratuvar OKLCH Sliders OKLCH Kaydırıcıları + HSL Sliders HSL Kaydırıcıları Chroma Kroma The largest chroma sRGB holds at this lightness and hue sRGB'nin bu açıklık ve renk tonunda alabileceği en yüksek kroma OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir @@ -4292,7 +4293,7 @@ axis Both Her İkisi @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır @msg `view` must be wheel or box `view` wheel veya box olmalıdır @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 `sliders` must be none, oklch or hsl `sliders` none, oklch veya hsl olmalıdır @msg OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir @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 ce6a9ddb66..0dfa7631f1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1853,6 +1853,7 @@ file-filter Templates Шаблони Knockout Group Група з вирізуванням Lab Lab OKLCH Sliders Повзунки OKLCH + HSL Sliders Повзунки HSL Chroma Хрома The largest chroma sRGB holds at this lightness and hue Найбільша хрома, яку вміщує sRGB за цієї світлоти й відтінку OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB @@ -4562,7 +4563,7 @@ axis Both Обидві @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe @msg `view` must be wheel or box `view` має бути wheel або box @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 `sliders` must be none, oklch or hsl `sliders` має бути none, oklch або hsl @msg OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB @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 9b0db7ab99..4f22b35a01 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2125,6 +2125,7 @@ digits Hindi Hindi Knockout Group Nhóm Knockout Lab Lab OKLCH Sliders Thanh trượt OKLCH + HSL Sliders Thanh trượt HSL Chroma Độ tươi màu The largest chroma sRGB holds at this lightness and hue Độ tươi màu lớn nhất mà sRGB chứa được ở độ sáng và sắc độ này OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc @@ -4611,7 +4612,7 @@ theme Appearance Giao diện @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe @msg `view` must be wheel or box `view` phải là wheel hoặc box @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 `sliders` must be none, oklch or hsl `sliders` phải là none, oklch hoặc hsl @msg OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc @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 c1393ec92c..7bf214053a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1737,6 +1737,7 @@ file-filter Templates 模板 Knockout Group 挖空组 Lab Lab OKLCH Sliders OKLCH 滑块 + HSL Sliders HSL 滑块 Chroma 色度 The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容纳的最大色度 OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 @@ -4722,7 +4723,7 @@ imageTrace Outline 轮廓 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必须是 wheel 或 box @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 `sliders` must be none, oklch or hsl `sliders` 必须是 none、oklch 或 hsl @msg OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 @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 4a7b55f335..8f2a9186e4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2419,7 +2419,7 @@ file-filter Templates 範本 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必須是 wheel 或 box @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 `sliders` must be none, oklch or hsl `sliders` 必須是 none、oklch 或 hsl @msg OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @@ -2918,6 +2918,7 @@ file-filter Templates 範本 Knockout Group 去底群組 Lab Lab OKLCH Sliders OKLCH 滑桿 + HSL Sliders HSL 滑桿 Chroma 色度 The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容納的最大色度 OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index afb4c70d1d..31e6b1a23d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1355,7 +1355,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 2a88a3f54a..0b3549311f 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -15,14 +15,17 @@ //! Panel menu › OKLCH Sliders shows L, C and H rows under the wheel or the box that edit the color //! by OKLCH lightness, chroma and hue (CSS Color 4: //! ), while the working RGB space is -//! sRGB. The choice is kept with the preferences too. +//! sRGB. Panel menu › HSL Sliders shows H, S and L rows in their place that edit the color by the +//! hue, saturation and lightness of CSS Color 4's HSL +//! (). The choice is kept with the +//! preferences too. use egui::{Color32, Rect, Stroke, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; use vectorcraft_color::oklab::{self, CHROMA_FULL}; -use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; +use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl}; use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; @@ -86,16 +89,19 @@ pub enum Sliders { None, /// OKLCH Sliders: lightness, chroma and hue. Oklch, + /// HSL Sliders: hue, saturation and lightness. + Hsl, } impl Sliders { - pub const ALL: [Sliders; 2] = [Sliders::None, Sliders::Oklch]; + pub const ALL: [Sliders; 3] = [Sliders::None, Sliders::Oklch, Sliders::Hsl]; /// The id `ui.colorWheel` and the preferences use. pub fn id(self) -> &'static str { match self { Sliders::None => "none", Sliders::Oklch => "oklch", + Sliders::Hsl => "hsl", } } @@ -131,9 +137,9 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { set(&mut app.ui.color_wheel, p, &cms::active())?; Ok(json!(app.ui.color_wheel)) @@ -164,7 +170,7 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S match p.get("sliders") { None | Some(Value::Null) => {} Some(v) => { - let sliders = v.as_str().and_then(Sliders::parse).ok_or("`sliders` must be none or oklch")?; + let sliders = v.as_str().and_then(Sliders::parse).ok_or("`sliders` must be none, oklch or hsl")?; if sliders == Sliders::Oklch && !cms.rgb_is_srgb() { return Err(OKLCH_NEEDS_SRGB.to_string()); } @@ -175,7 +181,8 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S Ok(()) } -/// The panel menu: Wheel View and Box View, Box Channel while the box shows, and OKLCH Sliders. +/// The panel menu: Wheel View and Box View, Box Channel while the box shows, HSL Sliders and OKLCH +/// Sliders. 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)] { @@ -193,6 +200,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); ui.separator(); + let on = set.sliders == Sliders::Hsl; + if menu_item(ui, tl!("HSL Sliders"), true, on) { + let sliders = if on { Sliders::None } else { Sliders::Hsl }; + if let Err(e) = app.run("ui.colorWheel", json!({ "sliders": sliders.id() })) { + app.status(e); + } + } let on = set.sliders == Sliders::Oklch; // While the rows show, the item stays enabled so that they can be hidden. let enabled = on || cms::active().rgb_is_srgb(); @@ -280,6 +294,9 @@ const MEMORY: &str = "color-wheel-hsb"; const OKLCH_MEMORY: &str = "color-wheel-oklch"; /// The message for OKLCH Sliders while the working RGB space is not sRGB. const OKLCH_NEEDS_SRGB: &str = "OKLCH needs sRGB as the working RGB space"; +/// Panel state: the HSL the slider rows asked for last, the [`Owner`] of the color they stored and +/// its display sRGB. +const HSL_MEMORY: &str = "color-wheel-hsl"; /// What the HSB picked last belongs to: the document, the selected objects or text characters, /// the appearance item, the proxy, the gradient stop or freeform point, its paint, and the color @@ -475,6 +492,75 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: out.filter(|_| enabled) } +/// The HSL `[h°, s, l]` the rows show for `c` through `cms` when `hsl` was asked for last and `c` +/// then displayed as the sRGB `shown`: `hsl` while `c` still displays as `shown` (the hue of a gray +/// and the saturation of black and white stay), else `c`'s own. +pub(crate) fn remembered_hsl(cms: &Cms, c: &Color, shown: [f32; 3], hsl: [f32; 3]) -> [f32; 3] { + if cms.display_rgb(c) == shown { hsl } else { rgb_to_hsl(cms.display_rgb(c)) } +} + +/// The color a track shows at HSL `hsl`. +fn hsl32(hsl: [f32; 3]) -> Color32 { + let [r, g, b] = hsl_to_rgb(hsl).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + Color32::from_rgb(r, g, b) +} + +/// The H, S and L rows of HSL Sliders for the target's `color` through `cms`: hue from 0 to 360°, +/// saturation and lightness from 0 to 100 %, CSS Color 4's HSL of the display sRGB. Each track +/// shows the colors its slider reaches. The rows are gray with no color to edit. Returns the HSL a +/// drag, an arrow key, a screen reader or a field asks for, and its phase. +pub(crate) fn hsl_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f32; 3], Live)> { + let t = Tokens::get(ui.ctx()); + let enabled = color.is_some(); + let hsl = match (color, pstate::>(ui.ctx(), HSL_MEMORY)) { + (Some(c), Some((owner, shown, hsl))) if owner == Owner::of(app, tgt, c) => remembered_hsl(cms, &c, shown, hsl), + (Some(c), _) => rgb_to_hsl(cms.display_rgb(&c)), + (None, _) => [0.0; 3], + }; + // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. The + // names start with "HSL" so that they differ from the box strip's HSB Hue and Saturation. + let hsl_name = |name: &str| format!("HSL {name}"); + let rows = + [("H", hsl_name(tl!("Hue")), 360.0, "°"), ("S", hsl_name(tl!("Saturation")), 100.0, "%"), ("L", hsl_name(tl!("Lightness")), 100.0, "%")]; + let shown = [f64::from(hsl[0]), f64::from(hsl[1]) * 100.0, f64::from(hsl[2]) * 100.0]; + // The HSL with row `i` set to `v` in the row's units. + let with = |i: usize, v: f64| { + let mut out = hsl; + match i { + 0 => out[0] = v.clamp(0.0, 360.0) as f32, + 1 => out[1] = (v / 100.0).clamp(0.0, 1.0) as f32, + _ => out[2] = (v / 100.0).clamp(0.0, 1.0) as f32, + } + out + }; + let mut out = None; + ui.add_enabled_ui(enabled, |ui| { + let field_w = 48.0; + let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); + for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() { + ui.horizontal(|ui| { + ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text))); + let v = shown[i].clamp(0.0, max); + let at = |x: f32| with(i, f64::from(x) * max); + let track = |x: f32| if enabled { hsl32(at(x)) } else { t.input }; + let value = SliderValue::field(v, 0.0..=max, suffix, 0); + let (dragged, phase, keyed) = + widgets::color_slider_stepped(ui, ("color-wheel-hsl", i), &name, Some(value), (v / max) as f32, slider_w, &track); + if let Some(x) = dragged { + out = Some((at(x), phase)); + } + if let Some(k) = keyed { + out = Some((with(i, k), Live::Released)); + } + if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-hsl-field", i), Some(&name), v, suffix, 0, field_w) { + out = Some((with(i, f), Live::Released)); + } + }); + } + }); + out.filter(|_| enabled) +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let tgt = wheel_target(app, ui); let color = tgt.color(); @@ -520,13 +606,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); - let mut picked_lch = None; - if app.ui.color_wheel.sliders == Sliders::Oklch { - ui.add_space(4.0); - picked_lch = oklch_rows(app, ui, &tgt, color, &cms); + let (mut picked_lch, mut picked_hsl) = (None, None); + match app.ui.color_wheel.sliders { + Sliders::None => {} + Sliders::Oklch => { + ui.add_space(4.0); + picked_lch = oklch_rows(app, ui, &tgt, color, &cms); + } + Sliders::Hsl => { + ui.add_space(4.0); + picked_hsl = hsl_rows(app, ui, &tgt, color, &cms); + } } let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); + if let Some((hsl, phase)) = picked_hsl { + let c = stored_srgb(&cms, hsl_to_rgb(hsl), replaced(app, &tgt, behind).as_ref(), cmyk_doc); + apply(app, &tgt, c, phase, behind); + if !behind { + set_pstate(ui.ctx(), HSL_MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), hsl))); + } + return; + } if let Some((lch, phase)) = picked_lch { let (srgb, _) = oklab::from_oklch(lch[0], lch[1], lch[2]); let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 407f6ffabe..7cba14af3a 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -12,7 +12,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_engine::Session; use super::color_wheel::{ - ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_oklch, set, show, stored, + ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_hsl, remembered_oklch, set, show, stored, }; use crate::VectorcraftApp; @@ -817,15 +817,193 @@ fn the_remembered_oklch_follows_a_change_of_working_space() { assert_eq!(remembered_oklch(&p3, &c, shown, asked), vectorcraft_color::oklab::to_oklch(p3.display_rgb(&c))); } +/// The panel with HSL Sliders shown, in a flyout tall enough for the rows. `oklch_slider` and +/// `oklch_harness_shown` find and draw any slider row, the HSL rows included. +fn hsl_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap(); + oklch_harness_shown(app) +} + +fn fill_hsl(app: &VectorcraftApp) -> [f32; 3] { + vectorcraft_color::rgb_to_hsl(cms::active().display_rgb(&fill(app))) +} + +/// Sets the slider row named `name` to `v` as a screen reader does. +fn set_slider_value(h: &mut Harness<'static, VectorcraftApp>, name: &str, v: f64) { + let (target_node, target_tree) = oklch_slider(h, name).accesskit_node().locate(); + let data = Some(ActionData::NumericValue(v)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + // The frame that takes the request draws the row before it applies it. + h.run_steps(2); +} + +/// `ui.colorWheel {sliders: "hsl"}` shows H, S and L rows with the fill's HSL, CSS Color 4's +/// `hsl()` of its display sRGB, and the panel keeps the setting with the preferences. +#[test] +fn hsl_sliders_show_the_fills_hue_saturation_and_lightness() { + let h = hsl_harness(app(json!("#ff8000"))); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl); + let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap(); + assert_eq!((value("HSL Hue"), value("HSL Saturation"), value("HSL Lightness")), (30.0, 100.0, 50.0)); + assert!(h.query_by_label("Chroma").is_none(), "OKLCH Sliders are hidden"); + let saved = serde_json::to_value(&h.state().ui).unwrap(); + assert_eq!(saved["color_wheel"]["sliders"], json!("hsl")); +} + +/// In Box View with the Saturation channel, screen readers tell the box strip's HSB saturation +/// from the S row's HSL saturation by their names. +#[test] +fn the_hsl_rows_names_differ_from_the_box_strips() { + let mut app = app(json!("#996633")); + app.run("ui.colorWheel", json!({"view": "box", "channel": "saturation"})).unwrap(); + let h = hsl_harness(app); + let sliders = |name: &str| h.query_all_by_label(name).filter(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).count(); + assert_eq!((sliders("Saturation"), sliders("HSL Saturation")), (1, 1)); + let strip = oklch_slider(&h, "Saturation").accesskit_node().numeric_value().unwrap(); + let row = oklch_slider(&h, "HSL Saturation").accesskit_node().numeric_value().unwrap(); + assert_ne!(strip, row, "HSB and HSL saturation differ for this color"); +} + +/// A drag on L changes the lightness and keeps the hue and the saturation. +#[test] +fn a_drag_on_hsl_lightness_keeps_the_hue_and_saturation() { + let mut h = hsl_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "HSL Lightness").rect(); + let undo = undo_len(h.state()); + drag(&mut h, &[on_rail(rail, 0.5), on_rail(rail, 0.25)], Modifiers::NONE); + assert!(near(fill_hsl(h.state()), [30.0, 1.0, 0.25], [1.0, 0.01, 0.01]), "{:?}", fill_hsl(h.state())); + assert_eq!(undo_len(h.state()), undo + 1, "a drag is one undo step"); +} + +/// A press on S gives it the keyboard focus, and → raises it by 1 % as one undo step. Each row +/// reports its range and the adjust actions to screen readers. +#[test] +fn the_hsl_rows_take_the_arrow_keys_and_screen_readers_actions() { + let mut h = hsl_harness(app(json!("#996633"))); + for (name, max) in [("HSL Hue", 360.0), ("HSL Saturation", 100.0), ("HSL Lightness", 100.0)] { + let node = oklch_slider(&h, name).accesskit_node(); + assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}"); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}"); + } + let rail = oklch_slider(&h, "HSL Saturation").rect(); + let s = fill_hsl(h.state())[1]; + click(&mut h, on_rail(rail, s), Modifiers::NONE); + let before = fill_hsl(h.state()); + let undo = undo_len(h.state()); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + let after = fill_hsl(h.state()); + let raised = ((before[1] * 100.0).round() + 1.0) / 100.0; + assert!(near(after, [before[0], raised, before[2]], [1.0, 0.008, 0.003]), "{before:?} → {after:?}"); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); +} + +/// A gray has no hue: a hue given to it stays on the H row while the color is unchanged, and a +/// saturation picked next uses that hue. +#[test] +fn a_gray_keeps_the_hsl_hue_it_was_given() { + let mut h = hsl_harness(app(json!("#808080"))); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + set_slider_value(&mut h, "HSL Hue", 200.0); + assert_eq!(oklch_slider(&h, "HSL Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step"); + set_slider_value(&mut h, "HSL Saturation", 60.0); + let got = fill_hsl(h.state()); + assert!(near(got, [200.0, 0.6, 0.5], [1.0, 0.01, 0.01]), "{got:?}"); +} + +/// In a working RGB space wider than sRGB, an HSL pick goes from display sRGB into that space +/// through the color settings: the fill displays the HSL asked for, and its stored RGB numbers are +/// those of the working space, not the sRGB numbers of that HSL. +#[test] +fn an_hsl_pick_in_display_p3_goes_into_the_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_HSL_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::an_hsl_pick_in_display_p3_goes_into_the_working_space", "--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 mut app = app(json!("#996633")); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + let mut h = hsl_harness(app); + let [hue, sat, _] = fill_hsl(h.state()); + let undo = undo_len(h.state()); + set_slider_value(&mut h, "HSL Lightness", 60.0); + let asked = [hue, sat, 0.6]; + assert!(near(fill_hsl(h.state()), asked, [0.5, 0.005, 0.005]), "{asked:?} → {:?}", fill_hsl(h.state())); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + let Color::Rgb { r, g, b } = fill(h.state()) else { panic!("an RGB fill stays RGB") }; + let srgb = vectorcraft_color::hsl_to_rgb(asked); + assert!((0..3).any(|i| ([r, g, b][i] - srgb[i]).abs() > 0.01), "{:?} is stored as the sRGB numbers {srgb:?}", [r, g, b]); +} + +/// Panel menu › HSL Sliders shows the H, S and L rows in place of OKLCH Sliders and, checked, +/// hides them; it is offered in any working RGB space. +#[test] +fn the_panel_menu_shows_and_hides_the_hsl_rows() { + let mut fonts = false; + let mut app = app(json!("#ff0000")); + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which hold the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app, + ); + h.run_steps(3); + h.get_by_label(" HSL Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl); + assert!(h.query_by_label("✓ OKLCH Sliders").is_none(), "the two slider sets show one at a time"); + h.get_by_label("✓ HSL Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let mut settings = Settings::default(); + set(&mut settings, &json!({"sliders": "hsl"}), &p3).unwrap(); + assert_eq!(settings.sliders, Sliders::Hsl, "HSL needs no particular working space"); +} + +/// The rows show what they asked for while the color displays as it did, and the color's own HSL +/// after the color settings change its display. +#[test] +fn the_remembered_hsl_follows_a_change_of_working_space() { + let srgb = Cms::default(); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let c = Color::rgb(0.5, 0.3, 0.2); + let asked = [20.0, 0.43, 0.35]; + let shown = srgb.display_rgb(&c); + assert_eq!(remembered_hsl(&srgb, &c, shown, asked), asked); + assert_eq!(remembered_hsl(&p3, &c, shown, asked), vectorcraft_color::rgb_to_hsl(p3.display_rgb(&c))); +} + /// Saved settings are read key by key: a value this version does not know (one a newer version /// wrote) gives the default, and the other preferences still load. #[test] fn saved_color_wheel_settings_are_read_leniently() { let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); saved["color_rgb_percent"] = json!(true); - for (value, sliders) in - [(json!({"sliders": "oklch"}), Sliders::Oklch), (json!({"sliders": "hsl", "view": "box"}), Sliders::None), (json!(5), Sliders::None)] - { + for (value, sliders) in [ + (json!({"sliders": "oklch"}), Sliders::Oklch), + (json!({"sliders": "hsl"}), Sliders::Hsl), + (json!({"sliders": "hwb", "view": "box"}), Sliders::None), + (json!(5), Sliders::None), + ] { saved["color_wheel"] = value.clone(); let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); assert_eq!((ui.color_wheel.sliders, ui.color_rgb_percent), (sliders, true), "{value}"); @@ -839,10 +1017,10 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap(); assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none")); - assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap_err(), "`sliders` must be none or oklch"); + assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hwb"})).unwrap_err(), "`sliders` must be none, oklch or hsl"); let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); assert_eq!(got, json!({"view": "box", "channel": "red", "sliders": "oklch"})); - let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hsl"})).unwrap_err(); - assert_eq!(e, "`sliders` must be none or oklch"); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hwb"})).unwrap_err(); + assert_eq!(e, "`sliders` must be none, oklch or hsl"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1f3e8c45ee..8136585625 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -266,9 +266,9 @@ Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a sa pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, sliders?}` shows the wheel or -the box (a color field with a channel strip at its right), picks the box's channel, and shows or hides OKLCH Sliders -(`sliders: "oklch"` is an error while the working RGB space is not sRGB); it returns the settings, and `ui.inspect` -reports them as `ui.color_wheel`. +the box (a color field with a channel strip at its right), picks the box's channel, and shows OKLCH Sliders, HSL +Sliders or neither (`sliders: "oklch"`, `"hsl"` or `"none"`; `"oklch"` is an error while the working RGB space is not +sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, diff --git a/docs/mcp.md b/docs/mcp.md index 58e7ea3a0c..f34952f048 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -634,6 +634,8 @@ kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or the box), and `"none"` hides them; `"oklch"` is an error while the working RGB space is not sRGB. +`ui.colorWheel {"sliders": "hsl"}` shows HSL Sliders in their place: H, S and L rows with the hue (0 to 360°), +saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color 4's `hsl()` defines them. `color.convert {"to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. A color outside sRGB (a Lab or CMYK color, or an RGB color in a wider working RGB space) is clipped to sRGB first. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 17be7b4c6c..cbd747051a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1556,6 +1556,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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. - **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. + - **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. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. From 4d9fa0a2c26791f49f5a7d66b57513ff025635c7 Mon Sep 17 00:00:00 2001 From: haseeb Date: Tue, 17 Nov 2026 11:05:11 +0300 Subject: [PATCH 04/51] Show full room and solid scrollbar in dropdown popups --- crates/ui-egui/src/widgets/dropdowns.rs | 7 +- crates/ui-egui/src/widgets/look_tests.rs | 90 ++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 7f088f25ef..d77333e7d6 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -148,10 +148,15 @@ fn combo_atoms_named<'a, R>( .show(ui, |ui| { let button_id = combo_button_id(ui, &id); let enter_for_combo = ui.memory(|m| m.has_focus(button_id)) || craft_ui::ComboBox::is_open(ui.ctx(), button_id); + let max_height = (ui.ctx().content_rect().height() - MENU_GAP).max(ui.spacing().combo_height); let response = craft_ui::ComboBox::from_id_salt(HashOnly(&id)) .selected_text(current) .width(width - 4.0) - .height(ui.spacing().combo_height) + .height(max_height) + .popup_style(egui::style::StyleModifier::new(|style| { + egui::containers::menu::menu_style(style); + style.spacing.scroll = list_scroll_style(); + })) .show_ui(ui, list); // The button or open list handles Enter before the modal can accept it. if enter_for_combo { diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 274861386b..210d707d81 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -524,3 +524,93 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { assert_eq!(typed(automatic, "(1,5)"), Some(SpinPick::Value(1.5)), "a decimal comma, automatic: {automatic}"); } } + +/// Long dropdown lists use the window's room instead of stopping at `combo_height` (200 pt), and +/// show a solid scroll bar without hovering when the list still overflows. +#[test] +fn a_long_dropdown_uses_window_room_and_shows_its_scroll_bar_when_clipped() { + let items: Vec = (0..20).map(|i| format!("Format {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let run = |win_h: f32| { + let ctx = themed(Default::default()); + let button_rect = std::cell::Cell::new(Rect::NOTHING); + let mut draw = |ui: &mut Ui| { + ui.add_space(16.0); + ui.horizontal(|ui| { + ui.add_space(16.0); + let before = ui.next_widget_position(); + let _ = dropdown_names(ui, "long-formats", labels[0], &labels, 160.0); + button_rect.set(Rect::from_min_size(before, vec2(160.0, 26.0))); + }); + }; + let mut step = |time: f64, events: Vec| { + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, win_h))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, &mut draw); + out.textures_delta.clear(); + out.shapes + }; + step(0.0, vec![]); + let at = button_rect.get().center(); + let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + step(0.1, vec![egui::Event::PointerMoved(at), click(true)]); + step(0.2, vec![click(false)]); + // Move the pointer away so the scroll bar is dormant, not hovered, and let the popup settle. + step(0.3, vec![egui::Event::PointerMoved(pos2(350.0, 10.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = step(f64::from(i) * 0.1, vec![]); + } + (ctx, clipped) + }; + + // In a tall window, all 20 items show without stopping at the 200 pt cap. + let (_tall_ctx, tall_shapes) = run(720.0); + let mut texts = vec![]; + fn collect_text(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| collect_text(s, out)), + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + _ => {} + } + } + for c in &tall_shapes { + collect_text(&c.shape, &mut texts); + } + assert!(texts.iter().any(|t| t == "Format 19"), "the 20th option is shown without scrolling: {texts:?}"); + + // In a short window where the list overflows, a solid scroll bar is drawn even while dormant. + let (short_ctx, short_shapes) = run(220.0); + let mut short_texts = vec![]; + for c in &short_shapes { + collect_text(&c.shape, &mut short_texts); + } + assert!(!short_texts.iter().any(|t| t == "Format 19"), "the list overflows the 220 pt window"); + let popup = short_ctx + .memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + .expect("the popup is open"); + let mut bar_rects = vec![]; + fn collect_rects(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| collect_rects(s, out)), + egui::Shape::Rect(r) => out.push(r.clone()), + _ => {} + } + } + for c in &short_shapes { + collect_rects(&c.shape, &mut bar_rects); + } + let has_scroll_bar = bar_rects.iter().any(|r| { + r.fill != Color32::TRANSPARENT + && r.rect.width() <= list_scroll_style().bar_width + 1.0 + && r.rect.height() >= 12.0 + && r.rect.height() < popup.height() + && r.rect.right() <= popup.right() + && r.rect.left() >= popup.right() - list_scroll_style().allocated_width() - 8.0 + }); + assert!(has_scroll_bar, "the overflowing dropdown draws its scroll bar without hover in {popup:?}"); +} From 7c9fc950c4dcbbdf1dcf34a150f71e2d6aae5ae3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:05:44 -0800 Subject: [PATCH 05/51] Brushes: Add original Paint library --- crates/engine/src/cmd/brushlib.rs | 40 +++++++++++++++++++ crates/engine/src/tests/brushlib.rs | 39 ++++++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 5 +++ crates/ui-egui/src/i18n/bs.tsv | 5 +++ crates/ui-egui/src/i18n/ca.tsv | 5 +++ crates/ui-egui/src/i18n/cs.tsv | 5 +++ crates/ui-egui/src/i18n/da.tsv | 5 +++ crates/ui-egui/src/i18n/de.tsv | 5 +++ crates/ui-egui/src/i18n/el.tsv | 5 +++ crates/ui-egui/src/i18n/es.tsv | 5 +++ crates/ui-egui/src/i18n/fi.tsv | 5 +++ crates/ui-egui/src/i18n/fr.tsv | 5 +++ crates/ui-egui/src/i18n/gu.tsv | 5 +++ crates/ui-egui/src/i18n/hi.tsv | 5 +++ crates/ui-egui/src/i18n/hu.tsv | 5 +++ crates/ui-egui/src/i18n/id.tsv | 5 +++ crates/ui-egui/src/i18n/it.tsv | 5 +++ crates/ui-egui/src/i18n/ja.tsv | 5 +++ crates/ui-egui/src/i18n/ka.tsv | 5 +++ crates/ui-egui/src/i18n/ko.tsv | 5 +++ crates/ui-egui/src/i18n/nl.tsv | 5 +++ crates/ui-egui/src/i18n/pl.tsv | 5 +++ crates/ui-egui/src/i18n/pt-br.tsv | 5 +++ crates/ui-egui/src/i18n/ru.tsv | 5 +++ crates/ui-egui/src/i18n/sv.tsv | 5 +++ crates/ui-egui/src/i18n/tests.rs | 3 +- crates/ui-egui/src/i18n/tr.tsv | 5 +++ crates/ui-egui/src/i18n/uk.tsv | 5 +++ crates/ui-egui/src/i18n/vi.tsv | 5 +++ crates/ui-egui/src/i18n/zh-hans.tsv | 5 +++ crates/ui-egui/src/i18n/zh-hant.tsv | 5 +++ .../src/panels/tests_brush_libraries.rs | 12 ++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 34 files changed, 233 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 34becd7c02..fed29ea06f 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -173,6 +173,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash }, BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, + BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, @@ -457,6 +458,45 @@ fn spacer(r: Rect) -> Node { } /// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles. +/// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one +/// stroke stretched along the path, with an intentionally different edge and paint distribution. +fn paint() -> BrushLibrary { + let flat_sweep = group(vec![ + black(band(100.0, 5.0, 64, |x| 0.8 * (x / 100.0 * std::f64::consts::TAU).sin())), + black(polygon(&[(0.0, -2.5), (7.0, -3.8), (18.0, -2.5)])), + black(polygon(&[(78.0, 2.5), (94.0, 4.0), (100.0, 2.5)])), + ]); + let mut dry_drag = vec![]; + for (y, shift) in [(-5.0, 0.0), (-3.2, 4.0), (-1.3, 1.0), (0.8, 6.0), (2.8, 3.0), (4.8, 8.0)] { + dry_drag.push(black(shapes::rectangle(Rect::new(2.0 + shift, y, 35.0 + shift, y + 0.8)))); + dry_drag.push(black(shapes::rectangle(Rect::new(40.0 + shift, y, 75.0 - shift / 2.0, y + 0.8)))); + dry_drag.push(black(shapes::rectangle(Rect::new(80.0 - shift / 2.0, y, 98.0, y + 0.8)))); + } + let mut loaded_stroke = vec![black(band(100.0, 6.0, 64, |x| 1.2 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin()))]; + for (x, r) in [(12.0, 4.2), (39.0, 3.6), (64.0, 4.8), (88.0, 3.9)] { + loaded_stroke.push(black(shapes::ellipse(Rect::new(x - r, -r - 1.5, x + r, r + 1.5)))); + } + let mut fan_sweep = vec![]; + for i in -2..=2 { + let offset = i as f64; + fan_sweep.push(black(band(100.0, 1.2, 48, |x| offset * (1.4 + x * 0.045) + 0.3 * (x / 100.0 * std::f64::consts::TAU).sin()))); + } + let paint_art = |name: &str, art: Node| Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { art, width: 150.0, colorization: Colorization::Tints, ..Default::default() }), + }; + built( + "Paint", + Document::new(100.0, 100.0), + vec![ + paint_art("Flat Sweep", flat_sweep), + paint_art("Dry Drag", group(dry_drag)), + paint_art("Loaded Stroke", group(loaded_stroke)), + paint_art("Fan Sweep", group(fan_sweep)), + ], + ) +} + fn pattern_borders() -> BrushLibrary { let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)])); let beads = group(vec![black(shapes::rectangle(Rect::new(0.0, -0.3, 8.0, 0.3))), black(shapes::ellipse(Rect::new(1.5, -2.5, 6.5, 2.5)))]); diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 4f0b739951..50964bb3a0 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -111,6 +111,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "ink-and-wash", "calligraphic-nibs", "bristle-brushes", + "paint", "pattern-borders", "scatter-shapes", "game-trails", @@ -131,19 +132,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[6]["count"].as_u64(), Some(4)); + assert_eq!(libs[7]["count"].as_u64(), Some(4)); let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); assert_eq!( beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] ); - assert_eq!(libs[7]["count"].as_u64(), Some(4)); + assert_eq!(libs[8]["count"].as_u64(), Some(4)); let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"})); assert_eq!( dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); - assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4))); + assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4))); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); @@ -155,6 +156,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("ink-and-wash", "art"), ("calligraphic-nibs", "calligraphic"), ("bristle-brushes", "bristle"), + ("paint", "art"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), ("game-trails", "art"), @@ -299,6 +301,37 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn paint_brushes_draw_distinct_marks_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Paint").unwrap(); + let names = ["Flat Sweep", "Dry Drag", "Loaded Stroke", "Fan Sweep"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + let mut curve = line_to(20.0); + curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0)); + for b in &lib.brushes { + let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) }; + assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints); + assert_eq!(art.width, 150.0); + for line in [line_to(2.0), line_to(180.0), curve.clone()] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke()); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "paint", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + /// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two /// translucent washes, with names of their own and a few paths of art each. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..cd22397872 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7237,3 +7237,8 @@ breakText Glyphs Глифи @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Paint Боя + Flat Sweep Плосък замах + Dry Drag Сухо влачене + Loaded Stroke Плътен мазок + Fan Sweep Ветрилообразен замах diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..14f63f8989 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7291,3 +7291,8 @@ shape Open Otvoren @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Paint Boja + Flat Sweep Ravni potez + Dry Drag Suhi potez + Loaded Stroke Bogati potez + Fan Sweep Lepezasti potez diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..d61e9f991a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8126,3 +8126,8 @@ breakText Glyphs Glifs @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Paint Pintura + Flat Sweep Traç pla + Dry Drag Arrossegament sec + Loaded Stroke Traç carregat + Fan Sweep Traç en ventall diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..f6ba8d3996 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9917,3 +9917,8 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Paint Malba + Flat Sweep Plochý tah + Dry Drag Suchý tah + Loaded Stroke Sytý tah + Fan Sweep Vějířový tah diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..cad239d70d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10025,3 +10025,8 @@ breakText Glyphs Glyffer @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Paint Maling + Flat Sweep Fladt strøg + Dry Drag Tørt træk + Loaded Stroke Fyldigt strøg + Fan Sweep Viftestrøg diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..7db1bdd21c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9516,3 +9516,8 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Paint Farbe + Flat Sweep Flacher Schwung + Dry Drag Trockener Zug + Loaded Stroke Satter Pinselstrich + Fan Sweep Fächerschwung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..2d4a38b47a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8100,3 +8100,8 @@ breakText Glyphs Γλύφοι @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Paint Ζωγραφική + Flat Sweep Επίπεδη πινελιά + Dry Drag Στεγνό σύρσιμο + Loaded Stroke Γεμάτη πινελιά + Fan Sweep Βεντάλια diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..ee042d3021 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8087,3 +8087,8 @@ breakText Glyphs Glifos @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Paint Pintura + Flat Sweep Barrido plano + Dry Drag Arrastre seco + Loaded Stroke Trazo cargado + Fan Sweep Barrido en abanico diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..261ef086f5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8183,3 +8183,8 @@ breakText Glyphs Merkit @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Paint Maalaus + Flat Sweep Tasainen veto + Dry Drag Kuiva veto + Loaded Stroke Runsas siveltimenveto + Fan Sweep Viuhkaveto diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..4a9f0140ea 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9902,3 +9902,8 @@ breakText Glyphs Glyphes @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Paint Peinture + Flat Sweep Balayage plat + Dry Drag Traînée sèche + Loaded Stroke Trait chargé + Fan Sweep Balayage en éventail diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..1462bace7a 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4987,3 +4987,8 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Paint રંગકામ + Flat Sweep સપાટ લસરકો + Dry Drag સૂકો ઘસારો + Loaded Stroke ઘાટો પીંછીનો ઘસારો + Fan Sweep પંખા જેવો લસરકો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..ca12681a52 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9524,3 +9524,8 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Paint चित्रकारी + Flat Sweep सपाट फेरा + Dry Drag सूखा घिसाव + Loaded Stroke गाढ़ा ब्रश स्ट्रोक + Fan Sweep पंखे जैसा फेरा diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..ce8e5c2907 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9905,3 +9905,8 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Paint Festék + Flat Sweep Lapos húzás + Dry Drag Száraz húzás + Loaded Stroke Telített ecsetvonás + Fan Sweep Legyezővonás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..e47d5a98bb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7252,3 +7252,8 @@ breakText Glyphs Glif @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Paint Cat + Flat Sweep Sapuan Datar + Dry Drag Tarikan Kering + Loaded Stroke Sapuan Tebal + Fan Sweep Sapuan Kipas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..2566851956 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9550,3 +9550,8 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Paint Pittura + Flat Sweep Passata piatta + Dry Drag Trascinamento secco + Loaded Stroke Tratto carico + Fan Sweep Passata a ventaglio diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..94e50cdc74 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9617,3 +9617,8 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Paint ペイント + Flat Sweep 平筆の一掃き + Dry Drag ドライドラッグ + Loaded Stroke 厚塗りストローク + Fan Sweep 扇形の一掃き diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..03a3c344ac 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10285,3 +10285,8 @@ font-script Japanese იაპონური @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არაბეჭდვად შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Paint საღებავი + Flat Sweep ბრტყელი მოსმა + Dry Drag მშრალი მოსმა + Loaded Stroke სქელი მონასმი + Fan Sweep მარაოსებრი მოსმა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..2807a61dd9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9514,3 +9514,8 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Paint 페인트 + Flat Sweep 평평한 붓질 + Dry Drag 마른 붓질 + Loaded Stroke 두터운 붓질 + Fan Sweep 부채꼴 붓질 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..0663cb82b6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9953,3 +9953,8 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Paint Verf + Flat Sweep Vlakke streek + Dry Drag Droge sleep + Loaded Stroke Dikke verfstreek + Fan Sweep Waaierstreek diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..d0de53fc6c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9770,3 +9770,8 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Paint Farba + Flat Sweep Płaskie pociągnięcie + Dry Drag Suche przeciągnięcie + Loaded Stroke Grube pociągnięcie + Fan Sweep Wachlarzowy ślad diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..2ac8fa3915 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9988,3 +9988,8 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Paint Pintura + Flat Sweep Pincelada plana + Dry Drag Arrasto seco + Loaded Stroke Traço carregado + Fan Sweep Pincelada em leque diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..cece3bfbcf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10011,3 +10011,8 @@ shape Open Открытый @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Paint Краска + Flat Sweep Плоский мазок + Dry Drag Сухой протяг + Loaded Stroke Густой мазок + Fan Sweep Веерный мазок diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..e292b118cf 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9601,3 +9601,8 @@ digits Hindi Hindi @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Paint Färg + Flat Sweep Platt penseldrag + Dry Drag Torrt drag + Loaded Stroke Fylligt penseldrag + Fan Sweep Solfjädersdrag diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 97fccd9167..bf6fa61a89 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -501,8 +501,9 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { .flat_map(|(_, lib)| lib.brushes.iter().map(|b| b.name.clone()).collect::>()) .collect(); names.sort(); + let duplicates: Vec<&str> = names.windows(2).filter(|pair| pair[0] == pair[1]).map(|pair| pair[0].as_str()).collect(); + assert_eq!(duplicates, ["Zigzag"], "only the established Pattern Borders / Game Trails name is shared"); names.dedup(); - assert_eq!(names.len(), 46, "{names:?}"); let mut bad = vec![]; for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { let missing: Vec<&String> = names.iter().filter(|n| lang.catalog().plain(n).is_none()).collect(); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..b11502fb7f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9875,3 +9875,8 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Paint Boya + Flat Sweep Düz fırça izi + Dry Drag Kuru sürükleme + Loaded Stroke Yoğun fırça izi + Fan Sweep Yelpaze izi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..cdde39fcce 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9526,3 +9526,8 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Paint Фарба + Flat Sweep Плоский мазок + Dry Drag Сухий протяг + Loaded Stroke Густий мазок + Fan Sweep Віяловий мазок diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..081dedde4c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7759,3 +7759,8 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Paint Sơn + Flat Sweep Nét quét phẳng + Dry Drag Nét kéo khô + Loaded Stroke Nét cọ đậm + Fan Sweep Nét quét hình quạt diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..4c7fe63028 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9758,3 +9758,8 @@ breakText Glyphs 字形 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Paint 绘画 + Flat Sweep 平刷 + Dry Drag 干拖 + Loaded Stroke 厚涂笔触 + Fan Sweep 扇形笔触 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..3c3afe5861 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9568,3 +9568,8 @@ breakText Glyphs 字符 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Paint 繪畫 + Flat Sweep 平刷 + Dry Drag 乾拖 + Loaded Stroke 厚塗筆觸 + Fan Sweep 扇形筆觸 diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 87fe34953f..8cb564e242 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -196,6 +196,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("ink-and-wash"), json!("calligraphic-nibs"), json!("bristle-brushes"), + json!("paint"), json!("pattern-borders"), json!("scatter-shapes"), json!("game-trails"), @@ -232,6 +233,17 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Paint"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("paint"), Some(4))); + let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); + let undo = undo_len(&app); + click(&mut app, &ctx, "Flat Sweep", Modifiers::NONE, 3.0); + assert!(has(&app, "Flat Sweep") && !has(&app, "Dry Drag")); + assert_eq!(undo_len(&app), undo + 1); + assert_eq!( + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), + Some("Flat Sweep") + ); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..8348f967b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5035,8 +5035,8 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: ten generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle -Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and +Brush libraries are read-only sets of brushes: eleven generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle +Brushes with one bristle brush for each tip shape, Paint with Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..8e539775c9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1102,6 +1102,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. + - **Paint library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Paint offers Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep. These original art brushes stretch broad, broken, loaded and fanned vector marks along a path and take the stroke color as tints. The public source describes the Paint category's varied thickness, textured edges and natural effects; the preset designs and names are VectorCraft's own. Evidence: `paint_brushes_draw_distinct_marks_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers finite output on short, long and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. From c1139c7a2d60351f9cf8701587cf944a61711c67 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:36:09 -0800 Subject: [PATCH 06/51] Tools: a Three-Point Arc tool draws an arc between two ends and a third point The Three-Point Arc tool, after the Arc tool in the Line Segment tool's group, places two ends by a drag or two clicks, then a third point. The arc passes through the third point, or with Third Point Sets Direction on it leaves the first end heading toward it, or with Alt arrives at the second end along the line from it. The setting is in the tool's Tool Options (a double-click on the tool), and ] switches it while drawing. The tool previews the arc, its center and radius, and shows "Arc too large" where no arc fits. shape.threePointArc {start, end, through | toward, at?} draws the open arc in one undo step and refuses points with no arc, malformed points, both or neither of through and toward, an at other than start or end, and an at given with through. Part of #7178. --- ASSETS.md | 1 + ROADMAP.md | 1 + assets/icons/dc-arc-three-point.svg | 1 + crates/engine/src/cmd/create.rs | 53 +++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/three_point_arc.rs | 200 ++++++++++++ crates/geom/src/shapes.rs | 275 ++++++++++++++++ crates/tools/src/catalog.rs | 1 + crates/tools/src/lib.rs | 2 + crates/tools/src/settings.rs | 1 + crates/tools/src/three_point_arc.rs | 307 ++++++++++++++++++ crates/tools/src/three_point_arc/tests.rs | 259 +++++++++++++++ crates/ui-egui/src/dialogs.rs | 2 + .../src/dialogs/three_point_arc_options.rs | 84 +++++ crates/ui-egui/src/i18n/bg.tsv | 8 + crates/ui-egui/src/i18n/bs.tsv | 8 + crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/gu.tsv | 8 + crates/ui-egui/src/i18n/hi.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/icon_data.rs | 1 + crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/toolbar.rs | 4 +- docs/mcp.md | 31 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 1 + 49 files changed, 1450 insertions(+), 2 deletions(-) create mode 100644 assets/icons/dc-arc-three-point.svg create mode 100644 crates/engine/src/tests/three_point_arc.rs create mode 100644 crates/tools/src/three_point_arc.rs create mode 100644 crates/tools/src/three_point_arc/tests.rs create mode 100644 crates/ui-egui/src/dialogs/three_point_arc_options.rs diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..a21a052f9b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-anchor-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-appearance.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arc.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-arc-three-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Three-Point Arc tool: an arc through its two ends and a third point | | `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline | diff --git a/ROADMAP.md b/ROADMAP.md index 4358817b60..e43e64ae14 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -151,6 +151,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/assets/icons/dc-arc-three-point.svg b/assets/icons/dc-arc-three-point.svg new file mode 100644 index 0000000000..479a9a5930 --- /dev/null +++ b/assets/icons/dc-arc-three-point.svg @@ -0,0 +1 @@ + diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 013b373d19..3c437e8c43 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -85,6 +85,15 @@ pub fn specs() -> Vec { has_doc, arc ), + cmd!( + "shape.threePointArc", + "Three-Point Arc", + [], + None, + "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn", + has_doc, + three_point_arc + ), cmd!( "shape.rectangularGrid", "Rectangular Grid", @@ -760,6 +769,50 @@ fn arc(s: &mut Session, p: &Value) -> Result { insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true) } +/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or +/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is. +fn three_point_arc(s: &mut Session, p: &Value) -> Result { + const C: &str = "shape.threePointArc"; + let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]"))); + let (start, end) = (point("start")?, point("end")?); + let from_end = match p.get("at") { + None => false, + Some(Value::String(v)) if v == "start" || v == "end" => v == "end", + Some(_) => return Err(bad(C, "`at` must be \"start\" or \"end\"")), + }; + // The arc, and the point it passes through (an anchor of the path, so the path meets it exactly). + let (arc, via) = match (p.get("through"), p.get("toward")) { + (Some(_), None) if p.get("at").is_some() => return Err(bad(C, "give `at` only with `toward`")), + (Some(_), None) => { + let through = point("through")?; + (shapes::CircularArc::through(start, end, through), Some(through)) + } + (None, Some(_)) if from_end => { + let toward = point("toward")?; + (shapes::CircularArc::arriving(start, end, end - toward), None) + } + (None, Some(_)) => { + let toward = point("toward")?; + (shapes::CircularArc::leaving(start, toward - start, end), None) + } + _ => return Err(bad(C, "give exactly one of `through` and `toward`")), + }; + let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?; + let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v)); + let look = s.new_art_look( + vectorcraft_color::Paint::None, + if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, + s.paint.stroke_width.max(0.1), + ); + // Not pixel-aligned: the ends stay on the given points. + let mut out = insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, 0.0, false)?; + out["cx"] = json!(arc.center.x); + out["cy"] = json!(arc.center.y); + out["radius"] = json!(arc.radius); + out["sweep"] = json!(arc.sweep.to_degrees()); + Ok(out) +} + /// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the /// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group /// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle). diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 6a0caf4cd6..579d28156b 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -558,6 +558,7 @@ pub(super) const ALLOWED: &[&str] = &[ "shape.rectangularGrid", "shape.spiral", "shape.star", + "shape.threePointArc", "shapeBuilder.merge", "shapeBuilder.regions", "shaper.expand", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e6c622963a..a9bca8d47d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -203,6 +203,7 @@ mod targeting; mod textcombos; mod textedit; pub(super) mod textimport; +mod three_point_arc; mod tileedge; mod tints; mod toolsettings; diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs new file mode 100644 index 0000000000..8a7a349220 --- /dev/null +++ b/crates/engine/src/tests/three_point_arc.rs @@ -0,0 +1,200 @@ +//! `shape.threePointArc`: an open circular arc between two ends, through a third point or +//! leaving an end toward it, and the Three-Point Arc tool's clicks that run it. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::Point; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +const C: &str = "shape.threePointArc"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// The largest distance of `points` from the path of `id`. +fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 { + let n = node(s, id); + let path = n.path_data().unwrap(); + points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max) +} + +/// The arc from (0, 0) to (80, 0) through (40, -40) is the upper half of the circle about +/// (40, 0) with radius 40: an open path from one end to the other, through the third point, with +/// no fill and a stroke, selected, and one undo step. +#[test] +fn the_arc_through_a_third_point_is_an_open_path_and_one_undo_step() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "through": [40, -40]})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}"); + // From (0, 0) over the top to (80, 0): clockwise on the page. + assert!((out["sweep"].as_f64().unwrap() - 180.0).abs() < 1e-9, "{out}"); + let id = id_of(&out); + let n = node(&s, id); + let NodeKind::Path { path, live: None, .. } = &n.kind else { panic!("not a plain path: {:?}", n.kind) }; + let sp = &path.subpaths[0]; + assert!(!sp.closed && path.subpaths.len() == 1); + assert_eq!((sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)), (Some(Point::ORIGIN), Some(Point::new(80.0, 0.0)))); + assert!(farthest_from_path(&s, id, &[Point::new(40.0, -40.0)]) < 1e-9); + assert!(n.appearance.fill_paint().is_none(), "no fill"); + assert!(!n.appearance.stroke_paint().is_none(), "a stroke"); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).is_none()); + // A third point between the quarter turns is an anchor too, so the path meets it exactly. + let via = Point::new(1000.0 * 20f64.to_radians().cos(), 1000.0 * 20f64.to_radians().sin()); + let out = s.execute(C, &json!({"start": [1000, 0], "end": [0, 1000], "through": [via.x, via.y]})).unwrap(); + let id = id_of(&out); + assert!(node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().any(|a| a.p == via)); + assert!(farthest_from_path(&s, id, &[via]) < 1e-9); +} + +/// With `toward`, the arc leaves `start` heading at the point (its first handle points there), +/// or with `at: "end"` arrives at `end` along the line from the point to `end` (run backward, the +/// arc leaves `end` heading at the point). +#[test] +fn the_arc_toward_a_point_has_that_tangent_at_its_end() { + let mut s = session(); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [30, -30]})).unwrap(); + let n = node(&s, id_of(&out)); + let first = n.path_data().unwrap().subpaths[0].anchors[0]; + let d = (first.h_out - first.p).normalize(); + assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, -1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}"); + // A quarter turn's tangent: the center is at (40, 40) and the radius √3200. + assert!((out["radius"].as_f64().unwrap() - 3200f64.sqrt()).abs() < 1e-9, "{out}"); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [50, -30], "at": "end"})).unwrap(); + let n = node(&s, id_of(&out)); + let last = *n.path_data().unwrap().subpaths[0].anchors.last().unwrap(); + let d = (last.p - last.h_in).normalize(); + assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, 1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}"); + // The direction from the start and from the end mirror each other. + assert!((out["cx"].as_f64().unwrap() - 40.0).abs() < 1e-9 && (out["cy"].as_f64().unwrap() - 40.0).abs() < 1e-9, "{out}"); +} + +/// Points that are the same, a third point on the line through the ends, and an arc reaching past +/// the canvas are refused with a message; nothing is drawn and no undo step is added. +#[test] +fn points_with_no_arc_are_refused() { + let mut s = session(); + let (undo, count) = (undo_len(&s), object_count(&s)); + for p in [ + json!({"start": [0, 0], "end": [0, 0], "through": [10, 10]}), + json!({"start": [0, 0], "end": [80, 0], "through": [40, 0]}), + json!({"start": [0, 0], "end": [80, 0], "through": [120, 0]}), + json!({"start": [0, 0], "end": [80, 0], "through": [80, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [0, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [-50, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [40, 0], "at": "end"}), + json!({"start": [0, 0], "end": [0, 0], "toward": [10, 10]}), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("no arc fits these points"), "{p}: {e}"); + } + // Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt down the page, and the + // arc goes round the far side of it. + let far = json!({"start": [0, 0], "end": [80, 0], "through": [200, 0.001]}); + let e = s.execute(C, &far).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{e}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Missing or malformed points, both or neither of `through` and `toward`, an `at` that is not +/// "start" or "end", and an `at` with `through` are errors; nothing is drawn. +#[test] +fn malformed_params_are_refused() { + let mut s = session(); + let count = object_count(&s); + for (p, want) in [ + (json!({"end": [80, 0], "through": [40, 40]}), "`start` must be [x, y]"), + (json!({"start": [0, 0], "end": [80], "through": [40, 40]}), "`end` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, "a"]}), "`through` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "through": null}), "`through` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "toward": [10, 0, 0]}), "`toward` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0]}), "give exactly one of `through` and `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "toward": [0, 40]}), "give exactly one of `through` and `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": "middle"}), "`at` must be \"start\" or \"end\""), + (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": null}), "`at` must be \"start\" or \"end\""), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "end"}), "give `at` only with `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "start"}), "give `at` only with `toward`"), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(object_count(&s), count); +} + +/// With Align New Objects to Pixel Grid on, the ends stay on the given points. +#[test] +fn the_arc_is_not_moved_onto_the_pixel_grid() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let id = id_of(&s.execute(C, &json!({"start": [0.3, 0.2], "end": [80.6, 0.1], "through": [40.4, -39.7]})).unwrap()); + let n = node(&s, id); + let sp = &n.path_data().unwrap().subpaths[0]; + assert_eq!(sp.anchors.first().map(|a| a.p), Some(Point::new(0.3, 0.2))); + assert_eq!(sp.anchors.last().map(|a| a.p), Some(Point::new(80.6, 0.1))); + assert!(!n.extras().pixel_aligned); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +fn click(s: &mut Session, x: f64, y: f64) { + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(Mods::default()), view()).unwrap(); + } +} + +/// With the Three-Point Arc tool, three clicks draw the arc in one undo step; `]` before the third +/// click makes the third point give the direction instead. Escape drops the ends. +#[test] +fn three_clicks_with_the_tool_draw_the_arc() { + let mut s = session(); + s.select_tool("threePointArc", view()).unwrap(); + let (undo, count) = (undo_len(&s), object_count(&s)); + click(&mut s, 100.0, 200.0); + click(&mut s, 180.0, 200.0); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two ends draw nothing yet"); + click(&mut s, 140.0, 160.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(farthest_from_path(&s, id, &[Point::new(100.0, 200.0), Point::new(140.0, 160.0), Point::new(180.0, 200.0)]) < 1e-9); + // Escape after the ends: the next clicks start afresh. + click(&mut s, 0.0, 0.0); + click(&mut s, 10.0, 300.0); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 180.0, 300.0); + s.tool_key(ToolKey::BracketRight, Mods::default(), view()).unwrap(); + let undo = undo_len(&s); + // Straight up from the first end: the upper half circle about (140, 300). + click(&mut s, 100.0, 250.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9); +} diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 76b9b71798..27568147b9 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -468,6 +468,143 @@ pub fn arc(a: Point, b: Point, slope: f64, closed: bool, _base_along_x: bool) -> PathData::single(SubPath::new(anchors, closed)) } +/// A circular arc from `start` to `end`: its circle's `center` and `radius`, and the turn from +/// `start` to `end` about the center in radians, positive the way the angle `atan2(y, x)` grows +/// (clockwise on the y-down page). The turn is never 0 and never a whole turn. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CircularArc { + pub start: Point, + pub end: Point, + pub center: Point, + pub radius: f64, + pub sweep: f64, +} + +impl CircularArc { + /// The arc from `start` to `end` that passes through `through`. `None` when two of the points + /// are the same or the three lie on one line ([`circle_through`]). + pub fn through(start: Point, end: Point, through: Point) -> Option { + let (center, radius) = circle_through(start, end, through)?; + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let a = angle(start); + let to_end = (angle(end) - a).rem_euclid(TAU); + let to_through = (angle(through) - a).rem_euclid(TAU); + // The turn that goes past `through` on its way to `end`. + let sweep = if to_through < to_end { to_end } else { to_end - TAU }; + Self::checked(start, end, center, radius, sweep) + } + + /// The arc that leaves `start` heading along `direction` (its tangent there) and ends at + /// `end`. `None` when `start` and `end` are the same, `direction` is zero, or `end` lies on the + /// line through `start` along `direction` (no circle touches that line at `start` and passes + /// through `end`). The same test as [`circle_through`] decides that: twice the area of the + /// triangle `start`, `end` and `start + direction` scaled to the chord's length is at most + /// 10⁻¹⁰ of the chord's length squared. + pub fn leaving(start: Point, direction: Vec2, end: Point) -> Option { + let len = direction.hypot(); + let chord = end - start; + let c2 = chord.hypot2(); + if !(len.is_finite() && len > 0.0 && c2.is_finite() && c2 > 0.0) { + return None; + } + let t = direction / len; + // Twice the triangle's area with the tangent as long as the chord. + let cross = t.cross(chord); + if cross.is_nan() || (cross * c2.sqrt()).abs() <= 1e-10 * c2 { + return None; + } + // The center lies on the normal at `start` on the side `end` is: `start + n * s` with + // `|n * s - chord| = |s|`, so `s = |chord|² / (2 n·chord)`. + let n = Vec2::new(-t.y, t.x); + let s = c2 / (2.0 * n.dot(chord)); + let center = start + n * s; + let radius = s.abs(); + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let a = angle(start); + let to_end = (angle(end) - a).rem_euclid(TAU); + // Leaving along `t`: the turn grows when `t` points the way the angle grows at `start`. + let grows = Vec2::new(-(start.y - center.y), start.x - center.x).dot(t) > 0.0; + let sweep = if grows { to_end } else { to_end - TAU }; + Self::checked(start, end, center, radius, sweep) + } + + /// The arc that ends at `end` arriving along `direction` and starts at `start`: [`Self::leaving`] + /// from `end` back along `-direction`, turned round. + pub fn arriving(start: Point, end: Point, direction: Vec2) -> Option { + let back = Self::leaving(end, -direction, start)?; + Some(Self { start, end, center: back.center, radius: back.radius, sweep: -back.sweep }) + } + + fn checked(start: Point, end: Point, center: Point, radius: f64, sweep: f64) -> Option { + let ok = center.is_finite() && radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep != 0.0 && sweep.abs() < TAU; + ok.then_some(Self { start, end, center, radius, sweep }) + } + + /// The point at `t` (0 at `start`, 1 at `end`) along the arc. + pub fn at(&self, t: f64) -> Point { + let a = (self.start.y - self.center.y).atan2(self.start.x - self.center.x) + self.sweep * t; + Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin()) + } + + /// The open path of the arc: an anchor at `start`, at `end`, and between them as many smooth + /// anchors, evenly spaced, as keep each cubic piece to a quarter turn at most. The ends are the + /// given points exactly. + pub fn to_path(&self) -> PathData { + let quarter = std::f64::consts::FRAC_PI_2; + // A quarter turn and a hair more is still one piece. + let pieces = ((self.sweep.abs() / quarter) - 1e-9).ceil().clamp(1.0, 4.0) as u32; + let step = self.sweep / f64::from(pieces); + // The handle length of a cubic that follows a circle through the turn `step`, per unit + // of radius; negative when the arc runs the other way. + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let a0 = (self.start.y - self.center.y).atan2(self.start.x - self.center.x); + let mut anchors = Vec::with_capacity(pieces as usize + 1); + for i in 0..=pieces { + let a = a0 + step * f64::from(i); + let p = if i == 0 { + self.start + } else if i == pieces { + self.end + } else { + Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin()) + }; + // The handle along the tangent the way the arc runs. + let d = Vec2::new(-a.sin(), a.cos()) * (self.radius * k); + let h_in = if i == 0 { p } else { p - d }; + let h_out = if i == pieces { p } else { p + d }; + let kind = if i == 0 || i == pieces { AnchorKind::Corner } else { AnchorKind::Smooth }; + anchors.push(Anchor { p, h_in, h_out, kind }); + } + PathData::single(SubPath::new(anchors, false)) + } + + /// [`Self::to_path`] with a smooth anchor at `via`, a point on the arc such as the one + /// [`Self::through`] passes through, so the path passes through it exactly: the arc to `via` + /// and the arc on from it, each cut into quarter turns at most. A `via` at an end, or off the + /// stretch between the ends, gives [`Self::to_path`]. + pub fn to_path_via(&self, via: Point) -> PathData { + let angle = |p: Point| (p.y - self.center.y).atan2(p.x - self.center.x); + let turn = (angle(via) - angle(self.start)).rem_euclid(TAU); + // The turn from `start` to `via` the way the arc runs. + let to_via = if self.sweep > 0.0 { turn } else { turn - TAU }; + let share = to_via / self.sweep; + if !(share > 0.0 && share < 1.0) || via == self.start || via == self.end { + return self.to_path(); + } + let first = Self { end: via, sweep: to_via, ..*self }.to_path(); + let second = Self { start: via, sweep: self.sweep - to_via, ..*self }.to_path(); + let (Some(a), Some(b)) = (first.subpaths.into_iter().next(), second.subpaths.into_iter().next()) else { return self.to_path() }; + let mut anchors: Vec = a.anchors.iter().copied().collect(); + let mut rest = b.anchors.iter().copied(); + if let (Some(joint), Some(next)) = (anchors.last_mut(), rest.next()) { + joint.h_out = next.h_out; + joint.kind = AnchorKind::Smooth; + } + anchors.extend(rest); + PathData::single(SubPath::new(anchors, false)) + } +} + /// Logarithmic spiral with decay per full wind (`segments` quarter turns). pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clockwise: bool) -> PathData { let decay = (decay_percent / 100.0).clamp(0.05, 0.9999); @@ -744,6 +881,144 @@ mod tests { assert!(c.distance(Point::new(4.0, 3.0) + far) < 1e-6 && (radius - 5.0).abs() < 1e-6, "{c:?} {radius}"); } + /// Every point of `path`'s cubics lies on the arc's circle (to 3·10⁻⁴ of the radius, the + /// quarter-turn cubic's error), and the path runs from the arc's start to its end. + fn assert_on_circle(arc: &CircularArc) { + use kurbo::ParamCurve; + let path = arc.to_path(); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.first().map(|a| a.p), Some(arc.start)); + assert_eq!(sp.anchors.last().map(|a| a.p), Some(arc.end)); + for seg in path.to_bezpath().segments() { + for i in 0..=8 { + let p = seg.eval(f64::from(i) / 8.0); + assert!((p.distance(arc.center) - arc.radius).abs() <= 3e-4 * arc.radius, "{p:?} off the circle"); + } + } + } + + /// The arc through a third point: from (0, 0) to (8, 0) through (4, -2) (above the chord on the + /// page) bulges up; through (4, 2) it bulges down; each has the circle through the three points + /// and goes past the third point. Through (4, 10) it is the larger part of its circle. + #[test] + fn the_arc_through_a_point_passes_through_it() { + let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0)); + for (c, major) in + [(Point::new(4.0, -2.0), false), (Point::new(4.0, 2.0), false), (Point::new(4.0, 10.0), true), (Point::new(-1.0, -3.0), true)] + { + let arc = CircularArc::through(a, b, c).unwrap(); + let (center, radius) = circle_through(a, b, c).unwrap(); + assert!(arc.center.distance(center) < 1e-12 && (arc.radius - radius).abs() < 1e-12); + assert_eq!(arc.sweep.abs() > PI, major, "{c:?}: {}", arc.sweep); + // The third point is on the arc: some point along it is the third point. + let nearest = (0..=10_000).map(|i| arc.at(f64::from(i) / 10_000.0).distance(c)).fold(f64::INFINITY, f64::min); + assert!(nearest < 0.01, "{c:?}: {nearest}"); + assert!(arc.at(0.0).distance(a) < 1e-12 && arc.at(1.0).distance(b) < 1e-9); + assert_on_circle(&arc); + } + // A half circle: two pieces, its middle anchor at the third point. + let arc = CircularArc::through(a, b, Point::new(4.0, -4.0)).unwrap(); + let path = arc.to_path(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert!(path.subpaths[0].anchors[1].p.distance(Point::new(4.0, -4.0)) < 1e-12); + assert_eq!(path.subpaths[0].anchors[1].kind, AnchorKind::Smooth); + // Almost a whole circle: four pieces. + let arc = CircularArc::through(a, Point::new(0.0, 0.01), Point::new(8.0, 0.0)).unwrap(); + assert_eq!(arc.to_path().subpaths[0].anchors.len(), 5); + assert_on_circle(&arc); + } + + /// With an anchor at the third point, the path passes through it exactly, whichever way the + /// arc runs, even where one cubic would miss it (a quarter turn of radius 1000 misses a point + /// 20° along by about 0.27). Each part keeps to a quarter turn, the anchor there is smooth, and + /// a point at an end leaves the path as `to_path` makes it. + #[test] + fn the_path_via_the_third_point_passes_through_it_exactly() { + let center = Point::new(0.0, 0.0); + let on = |deg: f64| Point::new(1000.0 * deg.to_radians().cos(), 1000.0 * deg.to_radians().sin()); + for (a, b, c) in [(0.0, 90.0, 20.0), (90.0, 0.0, 20.0), (0.0, 300.0, 170.0), (300.0, 0.0, 10.0)] { + let arc = CircularArc::through(on(a), on(b), on(c)).unwrap(); + assert!(arc.center.distance(center) < 1e-6); + let path = arc.to_path_via(on(c)); + let sp = &path.subpaths[0]; + let joint = sp.anchors.iter().find(|x| x.p == on(c)).expect("an anchor at the third point"); + assert_eq!(joint.kind, AnchorKind::Smooth); + assert_eq!((sp.anchors.first().map(|x| x.p), sp.anchors.last().map(|x| x.p)), (Some(arc.start), Some(arc.end))); + // No piece turns more than a quarter turn. + let points: Vec = sp.anchors.iter().map(|x| x.p).collect(); + for w in points.windows(2) { + let (u, v) = (w[0] - arc.center, w[1] - arc.center); + assert!(u.cross(v).atan2(u.dot(v)).abs() <= std::f64::consts::FRAC_PI_2 + 1e-9, "{a} {b} {c}"); + } + use kurbo::ParamCurve; + for seg in path.to_bezpath().segments() { + for i in 0..=8 { + let p = seg.eval(f64::from(i) / 8.0); + assert!((p.distance(arc.center) - arc.radius).abs() <= 0.3, "{p:?} off the circle"); + } + } + } + // A third point a hair from an end is still an anchor. + let near = Point::new(1000.0, 0.0000005); + let arc = CircularArc::through(on(0.0), on(90.0), near).unwrap(); + assert!(arc.to_path_via(near).subpaths[0].anchors.iter().any(|x| x.p == near)); + let arc = CircularArc::through(on(0.0), on(90.0), on(20.0)).unwrap(); + assert_eq!(arc.to_path_via(on(0.0)), arc.to_path()); + assert_eq!(arc.to_path_via(on(180.0)), arc.to_path()); + } + + /// The arc that leaves its start along a direction: from (0, 0) heading up the page (-y) to + /// (8, 0) is the upper half circle about (4, 0); heading down, the lower one. Its tangent at the + /// start is the direction, and arriving at the end mirrors it. + #[test] + fn the_arc_leaving_along_a_direction_has_that_tangent() { + let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0)); + let up = CircularArc::leaving(a, Vec2::new(0.0, -3.0), b).unwrap(); + assert!(up.center.distance(Point::new(4.0, 0.0)) < 1e-12 && (up.radius - 4.0).abs() < 1e-12); + assert!(up.at(0.5).distance(Point::new(4.0, -4.0)) < 1e-9, "{:?}", up.at(0.5)); + let down = CircularArc::leaving(a, Vec2::new(0.0, 3.0), b).unwrap(); + assert!(down.at(0.5).distance(Point::new(4.0, 4.0)) < 1e-9, "{:?}", down.at(0.5)); + // Leaving at 45° up and right: a quarter circle, tangent along the direction. + for d in [Vec2::new(1.0, -1.0), Vec2::new(1.0, 1.0), Vec2::new(-1.0, -0.2), Vec2::new(-1.0, 3.0)] { + let arc = CircularArc::leaving(a, d, b).unwrap(); + let first = &arc.to_path().subpaths[0].anchors[0]; + let tangent = first.h_out - first.p; + assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}"); + assert_on_circle(&arc); + // Arriving along a direction at the end: the tangent into the end is the direction. + let arc = CircularArc::arriving(a, b, d).unwrap(); + let last = arc.to_path().subpaths[0].anchors.last().copied().unwrap(); + let tangent = last.p - last.h_in; + assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}"); + assert_eq!((arc.start, arc.end), (a, b)); + assert_on_circle(&arc); + } + } + + /// No arc for points that are the same, a third point on the chord's line, a zero or not + /// finite direction, or a direction along the chord's line. + #[test] + fn degenerate_points_give_no_arc() { + let (a, b) = (Point::new(1.0, 2.0), Point::new(5.0, 7.0)); + assert_eq!(CircularArc::through(a, a, b), None); + assert_eq!(CircularArc::through(a, b, b), None); + assert_eq!(CircularArc::through(a, b, a.midpoint(b)), None); + assert_eq!(CircularArc::through(a, b, a + (b - a) * 3.0), None); + assert_eq!(CircularArc::through(a, b, Point::new(f64::INFINITY, 0.0)), None); + assert_eq!(CircularArc::leaving(a, Vec2::new(1.0, 0.0), a), None); + assert_eq!(CircularArc::leaving(a, Vec2::ZERO, b), None); + assert_eq!(CircularArc::leaving(a, Vec2::new(f64::NAN, 1.0), b), None); + assert_eq!(CircularArc::leaving(a, b - a, b), None); + assert_eq!(CircularArc::leaving(a, a - b, b), None); + assert_eq!(CircularArc::arriving(a, b, b - a), None); + // Off the line by 10⁻⁴ over a chord of 2000 still makes an arc. + let (p, q) = (Point::new(-1000.0, 0.0), Point::new(1000.0, 0.0)); + assert!(CircularArc::leaving(p, Vec2::new(2000.0, 1e-4), q).is_some()); + // Off the line by 10⁻¹² of the chord is in line: no arc, rather than a circle 10¹² chords wide. + assert_eq!(CircularArc::leaving(p, Vec2::new(1.0, 1e-12), q), None); + } + /// Two points that are the same, or three on one line, give no circle. #[test] fn coincident_or_collinear_points_give_no_circle() { diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 529aa80d18..3c754efcdf 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -48,6 +48,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[ t("lineSegment", "Line Segment Tool", Some("\\"), "tool-line"), t("arc", "Arc Tool", None, "tool-arc"), + t(crate::three_point_arc::ID, "Three-Point Arc Tool", None, "tool-three-point-arc"), t("spiral", "Spiral Tool", None, "tool-spiral"), t("rectangularGrid", "Rectangular Grid Tool", None, "tool-rect-grid"), t("polarGrid", "Polar Grid Tool", None, "tool-polar-grid"), diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7526717665..e08d4fdb6f 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -43,6 +43,7 @@ pub mod shaperwidget; pub mod slice; pub mod symbolism; pub mod text; +pub mod three_point_arc; pub mod touchtype; pub mod typewidget; pub mod xform; @@ -366,6 +367,7 @@ pub fn create(id: &str) -> Box { "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "lineSegment" => Box::new(shape::ShapeTool::new(id)), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), + three_point_arc::ID => Box::new(three_point_arc::ThreePointArcTool::default()), other => symbolism::create(other) .or_else(|| builder::create(other)) .or_else(|| draw2::create(other)) diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..f33a0456b1 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -27,6 +27,7 @@ const ROWS: &[Row] = &[ (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), + (&[crate::three_point_arc::ID], None, &["direction"]), (&["spiral"], None, &["decay", "segments", "clockwise"]), // The grids' Tool Options: the dividers and switches the drag uses, the Default Size and // Reference Point a click's dialog opens with. diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs new file mode 100644 index 0000000000..67ce63e03f --- /dev/null +++ b/crates/tools/src/three_point_arc.rs @@ -0,0 +1,307 @@ +//! The Three-Point Arc tool draws an open circular arc between two ends it is given +//! (`shape.threePointArc`). +//! +//! The ends come first: a drag from one to the other, or a click on each. Shift keeps the second +//! end at 45° steps from the first (from General › Constrain Angle). A third point then shapes the +//! arc, placed by a click or by a press dragged to it: the arc passes through it, or, with the +//! `direction` option on, the arc leaves the first end heading toward it (Alt: the arc arrives at +//! the second end along the line from that end to the point, and Shift keeps the line at 45° +//! steps). `direction` is set in the tool's Tool Options and kept with the preferences; `]` (with +//! or without Shift) switches it while the ends are placed. Every point snaps to Smart Guides. +//! Until the third point is placed, the tool shows the arc as a dashed outline with its ends, its +//! center as a small cross, the direction line in direction mode and, with Measurement Labels on, +//! the radius by the pointer. Where no arc fits (the third point lies on the line through the +//! ends) or the arc would reach past the canvas, the tool shows "Arc too large" by the pointer +//! (nothing while the pointer is on an end) and a click there draws nothing. The arc is one undo +//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop +//! the ends; a second click on the first end (a double-click) places nothing. + +use serde_json::{Value, json}; +use vectorcraft_doc::MAX_COORD; +use vectorcraft_geom::shapes::CircularArc; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::guides::{DrawSnap, Leave}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "threePointArc"; + +/// How far (screen points) the pointer travels from a press before the press counts as a drag. +const DRAG_PX: f64 = 2.0; +/// Half the length (screen points) of each arm of the cross at the arc's center. +const CROSS_PX: f64 = 4.0; +/// How near (screen points) the first end a second click counts as a click on it. +const REACH_PX: f64 = 3.0; +/// The label the tool shows by the pointer where no arc fits. +pub const TOO_LARGE: &str = "Arc too large"; + +/// The press in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Press { + /// The first end, pressed at `at`: a release after a drag places the second end there. + Start { at: Point, dragged: bool }, + /// The second end, pressed after a click placed the first: the release places it. + End, + /// The third point, pressed once both ends are placed: the release draws the arc. + Third, +} + +#[derive(Default)] +pub struct ThreePointArcTool { + snap: DrawSnap, + /// The third point gives the arc's direction at an end instead of a point it passes through. + direction: bool, + start: Option, + end: Option, + press: Option, + /// Where the pointer is, snapped: the point the next press or release places. + pointer: Option, + /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. + at_end: bool, + /// Where the pressed pointer was at its last event, before snapping. + raw: Option, +} + +/// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through +/// `third`, or with `direction`, heading toward `third` from `start` (or, with `at_end`, arriving +/// at `end` along the line from `end` to `third`). None where no arc fits or the arc would reach +/// past the canvas. With it, the path the command draws. +pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> Option<(CircularArc, PathData)> { + let (arc, path) = match (direction, at_end) { + (false, _) => CircularArc::through(start, end, third).map(|arc| (arc, arc.to_path_via(third))), + (true, false) => CircularArc::leaving(start, third - start, end).map(|arc| (arc, arc.to_path())), + (true, true) => CircularArc::arriving(start, end, end - third).map(|arc| (arc, arc.to_path())), + }?; + let on_canvas = path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].iter().all(|q| q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD)); + on_canvas.then_some((arc, path)) +} + +/// The command the tool runs for the arc from `start` to `end` shaped by `third`. +fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> (String, Value) { + let pair = |p: Point| json!([p.x, p.y]); + let params = if direction { + json!({ "start": pair(start), "end": pair(end), "toward": pair(third), "at": if at_end { "end" } else { "start" } }) + } else { + json!({ "start": pair(start), "end": pair(end), "through": pair(third) }) + }; + ("shape.threePointArc".into(), params) +} + +impl ThreePointArcTool { + fn clear(&mut self) { + self.start = None; + self.end = None; + self.press = None; + self.pointer = None; + self.snap.clear(); + } + + /// How the point being placed keeps to the points before it: the second end to the first, and + /// in direction mode the third point to the end its direction line starts from. + fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { + match (self.start, self.end) { + (Some(a), None) => Some(Leave::segment(cx, a, mods.shift)), + (Some(a), Some(b)) if self.direction => Some(Leave::segment(cx, if mods.alt { b } else { a }, mods.shift)), + _ => None, + } + } + + /// The pressed pointer moved to `ev`: the point being placed follows it. + fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) { + self.raw = Some(ev.pos); + match &mut self.press { + Some(Press::Start { at, dragged }) => { + *dragged |= ev.pos.distance(*at) >= cx.tol(DRAG_PX); + let leave = Leave::segment(cx, *at, ev.mods.shift); + self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); + } + Some(Press::End | Press::Third) => { + let leave = self.leave(cx, ev.mods); + self.pointer = Some(self.snap.drag(cx, ev.pos, leave.as_ref())); + } + None => {} + } + } + + /// The arc as the tool shows it now, and its path: both ends placed and the pointer on a point + /// that fits. + fn arc(&self) -> Option<(CircularArc, PathData)> { + arc_of(self.start?, self.end?, self.pointer?, self.direction, self.at_end) + } +} + +impl Tool for ThreePointArcTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + if self.end.is_some() { + self.at_end = ev.mods.alt; + } + match ev.kind { + PointerKind::Move => { + let leave = self.leave(cx, ev.mods); + self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref())); + vec![] + } + PointerKind::Down => { + self.raw = Some(ev.pos); + let leave = self.leave(cx, ev.mods); + match (self.start, self.end) { + (None, _) => { + let at = self.snap.press(cx, ev.pos, &[], None); + self.start = Some(at); + self.press = Some(Press::Start { at, dragged: false }); + self.pointer = Some(at); + } + (Some(a), None) => { + let at = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + // The second click of a double-click lands on the first end. + if at.distance(a) <= cx.tol(REACH_PX) { + self.press = None; + return vec![]; + } + self.press = Some(Press::End); + self.pointer = Some(at); + } + (Some(_), Some(_)) => { + self.pointer = Some(self.snap.press(cx, ev.pos, &[], leave.as_ref())); + self.press = Some(Press::Third); + } + } + vec![] + } + PointerKind::Drag => { + self.follow(cx, ev); + vec![] + } + PointerKind::Up => { + // A release away from the last drag event places the point where it is let go. + if self.press.is_some() && self.raw != Some(ev.pos) { + self.follow(cx, ev); + } + match (self.press.take(), self.start, self.pointer) { + (Some(Press::Start { at, dragged: true }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), + (Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b), + (Some(Press::Third), Some(a), Some(c)) => { + let Some(b) = self.end else { return vec![] }; + // Where no arc fits, nothing is drawn and the ends stay for another try. + if self.arc().is_none() { + self.snap.clear(); + return vec![]; + } + let (name, params) = command(a, b, c, self.direction, self.at_end); + self.clear(); + return vec![Action::Exec(name, params)]; + } + _ => {} + } + // A placed end: the guides of the press go. + self.snap.clear(); + vec![] + } + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape => self.clear(), + ToolKey::BracketRight if self.start.is_some() => self.direction = !self.direction, + _ => {} + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + matches!(key, ToolKey::Escape | ToolKey::BracketRight) && self.start.is_some() + } + + /// An end placed: Escape drops it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.start.is_some() + } + + fn busy(&self) -> bool { + self.start.is_some() + } + + /// A dropped press (a second finger, a canceled touch) drops the ends placed so far. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.pointer = None; + self.snap.clear(); + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops the ends. + fn history_moved(&mut self) { + self.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + let color = crate::draw2::FEEDBACK; + match (self.start, self.end, self.pointer) { + // Placing the second end: the chord so far. + (Some(a), None, Some(b)) if b != a => o.push(Overlay::Line { a, b, color, dashed: true }), + (Some(a), Some(b), Some(p)) => { + if self.direction { + o.push(Overlay::Line { a: if self.at_end { b } else { a }, b: p, color, dashed: false }); + } + match self.arc() { + Some((arc, path)) => { + o.push(Overlay::Path { path: path.to_bezpath(), color, width: 1.0, dashed: true }); + let (c, arm) = (arc.center, cx.tol(CROSS_PX)); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); + if cx.measurement_labels { + o.push(Overlay::Measure { p, text: format!("R: {}", cx.len(arc.radius)) }); + } + } + // A pointer on an end gives no third point yet, so no label. + None if p.distance(a) <= cx.tol(REACH_PX) || p.distance(b) <= cx.tol(REACH_PX) => {} + None => o.push(Overlay::Label { p, text: TOO_LARGE.into(), color }), + } + } + _ => {} + } + for p in self.start.iter().chain(self.end.iter()) { + o.push(Overlay::Anchor { p: *p, color, filled: true, size: 6.0 }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({ "direction": self.direction }) + } + + fn set_option(&mut self, key: &str, value: &Value) { + if key == "direction" + && let Some(on) = value.as_bool() + { + self.direction = on; + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs new file mode 100644 index 0000000000..88e63dc1b4 --- /dev/null +++ b/crates/tools/src/three_point_arc/tests.rs @@ -0,0 +1,259 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; +use vectorcraft_geom::Rect; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +fn click_with(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, mods)); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, mods))); + acts +} + +fn click(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64)) -> Vec { + click_with(t, cx, p, Mods::default()) +} + +fn hover(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) { + assert!(t.pointer(cx, &ev(PointerKind::Move, p, mods)).is_empty()); +} + +/// A press at `from`, dragged through `path` and let go at its last point. +fn drag(t: &mut ThreePointArcTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods)); + for p in path { + acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods))); + } + let end = path.last().copied().unwrap_or(from); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods))); + acts +} + +fn through(start: (f64, f64), end: (f64, f64), via: (f64, f64)) -> Vec { + let pair = |(x, y): (f64, f64)| json!([x, y]); + vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "through": pair(via) }))] +} + +fn toward(start: (f64, f64), end: (f64, f64), to: (f64, f64), at: &str) -> Vec { + let pair = |(x, y): (f64, f64)| json!([x, y]); + vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "toward": pair(to), "at": at }))] +} + +/// The dashed arc the tool shows: its bounding box. +fn preview(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) +} + +fn too_large(o: &[Overlay]) -> bool { + o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == TOO_LARGE)) +} + +/// A drag places the two ends; a click on a third point then draws the arc through it. Until +/// then, nothing is drawn. +#[test] +fn a_drag_and_a_click_draw_the_arc_through_the_third_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 300.0), (380.0, 300.0)], Mods::default()).is_empty()); + assert!(t.busy() && t.ends_on_escape(&cx)); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); + assert!(!t.busy() && t.overlays(&cx).is_empty(), "the tool starts afresh"); +} + +/// Two clicks place the ends. Between the second click and the third, the tool shows the arc +/// through the pointer (a half circle here, bulging up the page), its center cross and its +/// radius; the third click draws it. +#[test] +fn three_clicks_draw_the_arc_and_the_tool_shows_it_on_the_way() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(click(&mut t, &cx, (300.0, 300.0)).is_empty()); + hover(&mut t, &cx, (380.0, 300.0), Mods::default()); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Line { dashed: true, .. })), "the chord so far"); + assert!(click(&mut t, &cx, (380.0, 300.0)).is_empty()); + hover(&mut t, &cx, (340.0, 260.0), Mods::default()); + let o = t.overlays(&cx); + let b = preview(&o).expect("the arc"); + assert!((b.x0 - 300.0).abs() < 0.1 && (b.x1 - 380.0).abs() < 0.1 && (b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); + let radius = format!("R: {}", cx.len(40.0)); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == radius)), "{o:?}"); + // The center cross at (340, 300). + assert!(o.iter().any(|o| matches!(o, Overlay::Line { a, b, dashed: false, .. } if a.midpoint(*b).distance(Point::new(340.0, 300.0)) < 1e-9))); + let quiet = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); +} + +/// A third point on the line through the ends, an arc reaching past the canvas, or a third point +/// on an end gives no arc: a click draws nothing and keeps the ends, and a click on a point that +/// fits then draws the arc. The tool shows "Arc too large" by the pointer, except on an end. +#[test] +fn a_third_point_in_line_with_the_ends_draws_nothing() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + // Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt away. + for (bad, label) in [((420.0, 300.0), true), ((250.0, 300.0), true), ((340.0, 300.0), true), ((500.0, 300.001), true), ((380.0, 300.0), false)] { + hover(&mut t, &cx, bad, Mods::default()); + let o = t.overlays(&cx); + assert!(too_large(&o) == label && preview(&o).is_none(), "{bad:?}: {o:?}"); + assert!(click(&mut t, &cx, bad).is_empty(), "{bad:?}"); + assert!(t.busy()); + } + assert_eq!(click(&mut t, &cx, (340.0, 340.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 340.0))); +} + +/// In direction mode, Shift keeps the direction line at 45° steps from the end it starts at. +#[test] +fn shift_keeps_the_direction_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let shift = Mods { shift: true, ..Mods::default() }; + let acts = click_with(&mut t, &cx, (303.0, 250.0), shift); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}"); + // With Alt, from the second end. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let both = Mods { shift: true, alt: true, ..Mods::default() }; + let acts = click_with(&mut t, &cx, (383.0, 250.0), both); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 380.0).abs() < 1e-9) && params["at"] == "end", "{params}"); +} + +/// With the `direction` option, the third point gives the direction the arc leaves its first +/// end in, and the tool shows the line from that end to the pointer. Alt moves the direction to +/// the second end. `]` switches the option while the ends are placed, and only then. +#[test] +fn in_direction_mode_the_third_point_sets_the_tangent_at_an_end() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(!t.claims_key(&cx, ToolKey::BracketRight), "no ends: ] is left to the app"); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.options(), json!({ "direction": false })); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + assert!(t.claims_key(&cx, ToolKey::BracketRight)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.options(), json!({ "direction": true })); + // Straight up the page from (300, 300): the upper half circle about (340, 300). + hover(&mut t, &cx, (300.0, 250.0), Mods::default()); + let o = t.overlays(&cx); + let b = preview(&o).expect("the arc"); + assert!((b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); + // The direction line: solid, from the end it starts at. + let line = |o: &[Overlay], from: Point| o.iter().any(|o| matches!(o, Overlay::Line { a, dashed: false, .. } if *a == from)); + assert!(line(&o, Point::new(300.0, 300.0)), "{o:?}"); + assert_eq!(click(&mut t, &cx, (300.0, 250.0)), toward((300.0, 300.0), (380.0, 300.0), (300.0, 250.0), "start")); + // Alt: the direction line starts at the second end. + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let alt = Mods { alt: true, ..Mods::default() }; + hover(&mut t, &cx, (380.0, 250.0), alt); + assert!(line(&t.overlays(&cx), Point::new(380.0, 300.0))); + assert!(preview(&t.overlays(&cx)).is_some()); + assert_eq!(click_with(&mut t, &cx, (380.0, 250.0), alt), toward((300.0, 300.0), (380.0, 300.0), (380.0, 250.0), "end")); + // ] switches back to passing through the third point. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); +} + +/// The `direction` option takes a bool; anything else leaves it as it was. +#[test] +fn the_direction_option_takes_a_bool() { + let mut t = ThreePointArcTool::default(); + t.set_option("direction", &json!(true)); + for v in [json!("false"), json!(0), json!(null)] { + t.set_option("direction", &v); + assert_eq!(t.options(), json!({ "direction": true }), "{v}"); + } + t.set_option("direction", &json!(false)); + assert_eq!(t.options(), json!({ "direction": false })); +} + +/// A release away from the last drag event places the point where the pointer is let go, for +/// the second end and for the third point. +#[test] +fn a_point_is_placed_where_the_press_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let none = Mods::default(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Drag, (340.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none)); + assert_eq!(t.end, Some(Point::new(380.0, 300.0))); + t.pointer(&cx, &ev(PointerKind::Down, (340.0, 250.0), none)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (340.0, 260.0), none)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); + // A press that only moves when it is let go still counts as a drag for the ends. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none)); + assert_eq!(t.end, Some(Point::new(380.0, 300.0))); +} + +/// Shift keeps the second end at 45° steps from the first. +#[test] +fn shift_keeps_the_second_end_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 303.0), (380.0, 306.0)], shift); + assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end); +} + +/// Escape, an edit made outside the tool and a dropped press drop the ends; a second click on +/// the first end (a double-click) places nothing. +#[test] +fn escape_history_and_a_double_click_drop_or_keep_the_ends() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.busy() && !t.claims_key(&cx, ToolKey::Escape)); + click(&mut t, &cx, (300.0, 300.0)); + assert!(click(&mut t, &cx, (300.5, 300.0)).is_empty()); + assert_eq!((t.start, t.end), (Some(Point::new(300.0, 300.0)), None), "the double-click's second click places nothing"); + click(&mut t, &cx, (380.0, 300.0)); + t.history_moved(); + assert!(!t.busy()); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.drop_press(&cx); + assert!(!t.busy() && t.overlays(&cx).is_empty()); +} + +/// The catalog lists the tool in the Line Segment tool's group, after the Arc tool, with no +/// default shortcut, and `create` makes it. +#[test] +fn the_tool_is_in_the_line_segment_group_after_the_arc_tool() { + let group = crate::TOOL_GROUPS.iter().find(|g| g.iter().any(|t| t.id == ID)).expect("in a toolbar group"); + let ids: Vec<_> = group.iter().map(|t| t.id).collect(); + let arc = ids.iter().position(|id| *id == "arc").expect("the Arc tool's group"); + assert_eq!(ids.first(), Some(&"lineSegment")); + assert_eq!(ids.get(arc + 1), Some(&ID)); + let info = crate::tool_info(ID).expect("catalogued"); + assert_eq!((info.label, info.shortcut), ("Three-Point Arc Tool", None)); + assert_eq!(crate::create(ID).id(), ID); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..98e6cfe0cf 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -141,6 +141,7 @@ mod text_export; pub mod text_import; mod three_d_classic; pub(crate) mod three_d_materials; +pub mod three_point_arc_options; mod tiff_bmp_tga; pub mod tile_edge_color; mod tools; @@ -449,6 +450,7 @@ registry! { FreehandOptions: [freehand::KIND] => freehand::SPEC, ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, + ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, diff --git a/crates/ui-egui/src/dialogs/three_point_arc_options.rs b/crates/ui-egui/src/dialogs/three_point_arc_options.rs new file mode 100644 index 0000000000..6d0eee96d1 --- /dev/null +++ b/crates/ui-egui/src/dialogs/three_point_arc_options.rs @@ -0,0 +1,84 @@ +//! Three-Point Arc Tool Options (double-click the Three-Point Arc tool, or `tool.options`): +//! Third Point Sets Direction, the tool's `direction` option. With it on, the third point gives the +//! direction the arc leaves an end in; with it off, the arc passes through the third point. OK +//! sets it with `tool.setOption {tool: "threePointArc", values: {direction}}`; it lasts across +//! tool switches and is saved with the preferences. `]` also switches it while an arc is drawn. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::three_point_arc::ID as TOOL; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Three-Point Arc Tool Options. +pub const KIND: &str = "threePointArcOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 280.0, ..DialogSpec::FORM }; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let on = app.session.tool_options_of(TOOL).get("direction").and_then(Value::as_bool).unwrap_or(false); + let mut fields = Map::new(); + fields.insert("direction".into(), json!(on)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let on = d.bool("direction"); + if widgets::check(ui, tl!("Third Point Sets Direction"), on, true) { + d.fields.insert("direction".into(), json!(!on)); + } + false +} + +/// OK: set the tool's `direction`. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": { "direction": d.bool("direction") } })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_the_direction() { + let mut app = app(); + assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(false)); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in ["Three-Point Arc Tool Options", "Third Point Sets Direction", "OK", "Cancel"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert!(!d.bool("direction")); + d.fields.insert("direction".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(true)); + // It lasts while another tool is chosen, and the dialog opens on it again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("direction")); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..73b82cc903 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -217,6 +217,10 @@ font-technology Variable Променливи Arc Дъга Arc Lower… Дъга надолу… Arc Tool Инструмент „Дъга“ + Three-Point Arc Tool Инструмент „Дъга през три точки“ + Three-Point Arc Дъга през три точки + Arc too large Дъгата е твърде голяма + Third Point Sets Direction Третата точка задава посоката Arc Upper… Дъга нагоре… Arch… Извиване… Arc… Дъга… @@ -7237,3 +7241,7 @@ breakText Glyphs Глифи @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" +@msg `at` must be "start" or "end" `at` трябва да е "start" или "end" +@msg give exactly one of `through` and `toward` посочете точно едно от `through` и `toward` +@msg no arc fits these points: two are the same or all three lie on one line няма дъга през тези точки: две съвпадат или и трите лежат на една права +@msg give `at` only with `toward` задайте `at` само заедно с `toward` diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..3259fa3dd8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1404,6 +1404,10 @@ lighting Light Svjetlo Add Anchor Point Tool Alat za dodavanje sidrene tačke Anchor Point Tool Alat sidrena tačka Arc Tool Alat luk + Three-Point Arc Tool Alat luk kroz tri tačke + Three-Point Arc Luk kroz tri tačke + Arc too large Luk je prevelik + Third Point Sets Direction Treća tačka određuje smjer Area Graph Tool Alat za površinski grafikon Area Type Tool Alat za tekst u području Artboard Tool Alat radna ploča @@ -7291,3 +7295,7 @@ shape Open Otvoren @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" +@msg `at` must be "start" or "end" `at` mora biti "start" ili "end" +@msg give exactly one of `through` and `toward` navedite tačno jedno od `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line nijedan luk ne odgovara ovim tačkama: dvije su iste ili sve tri leže na jednoj pravoj +@msg give `at` only with `toward` navedite `at` samo uz `toward` diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..c66c35daa1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -338,6 +338,10 @@ antiAlias Sharp Nítid Arc Lower… Arc inferior… Arc Segment Tool Options Opcions de l’eina de segment d’arc Arc Tool Eina d’arc + Three-Point Arc Tool Eina d’arc per tres punts + Three-Point Arc Arc per tres punts + Arc too large Arc massa gran + Third Point Sets Direction El tercer punt indica la direcció Arc Upper… Arc superior… Arch… Arqueja… Arc… Arc… @@ -6152,6 +6156,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg `points` must be three [x, y] pairs of numbers `points` han de ser tres parells de nombres [x, y] @msg direct-select three anchor points, or give `points` seleccioneu directament tres punts d’ancoratge o indiqueu `points` @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta +@msg `at` must be "start" or "end" `at` ha de ser "start" o "end" +@msg give exactly one of `through` and `toward` indiqueu exactament un de `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line cap arc no s’ajusta a aquests punts: dos són iguals o tots tres són en una mateixa recta +@msg give `at` only with `toward` indiqueu `at` només amb `toward` @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers @msg no artboard no hi ha tauler @msg no artboard {i} (0-based; the document has {_1}) no hi ha el tauler {i} (basat en 0; el document en té {_1}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..96b00951be 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1430,6 +1430,10 @@ lighting Light Světlo Add Anchor Point Tool Nástroj Přidat kotevní bod Anchor Point Tool Nástroj Kotevní bod Arc Tool Nástroj Oblouk + Three-Point Arc Tool Nástroj Oblouk třemi body + Three-Point Arc Oblouk třemi body + Arc too large Oblouk je příliš velký + Third Point Sets Direction Třetí bod určuje směr Area Graph Tool Nástroj Plošný graf Area Type Tool Nástroj Text v oblasti Artboard Tool Nástroj Pracovní plocha @@ -5317,6 +5321,10 @@ liquify-list-end {0}, {1} {0} a {1} @msg `points` must be three [x, y] pairs of numbers `points` musí být tři dvojice čísel [x, y] @msg direct-select three anchor points, or give `points` vyberte přímým výběrem tři kotevní body, nebo zadejte `points` @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce +@msg `at` must be "start" or "end" `at` musí být "start" nebo "end" +@msg give exactly one of `through` and `toward` zadejte právě jeden z parametrů `through` a `toward` +@msg no arc fits these points: two are the same or all three lie on one line těmto bodům neodpovídá žádný oblouk: dva jsou stejné nebo všechny tři leží na jedné přímce +@msg give `at` only with `toward` parametr `at` zadejte jen s `toward` @msg no app to open files here zde chybí aplikace pro otevírání souborů @msg no artboard žádná pracovní plocha @msg no artboard {i} (0-based; the document has {_1}) pracovní plocha {i} neexistuje (číslováno od 0; dokument jich má {_1}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..04009d2ee7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4030,6 +4030,10 @@ lighting Light Lys Add Anchor Point Tool Tilføj ankerpunkt-værktøj Anchor Point Tool Ankerpunktværktøj Arc Tool Bueværktøj + Three-Point Arc Tool Værktøj til bue gennem tre punkter + Three-Point Arc Bue gennem tre punkter + Arc too large Buen er for stor + Third Point Sets Direction Tredje punkt angiver retningen Area Graph Tool Områdediagramværktøj Area Type Tool Områdetekstværktøj Artboard Tool Tegnebrætværktøj @@ -7506,6 +7510,10 @@ imageTrace Outline Kontur @msg `points` must be three [x, y] pairs of numbers `points` skal være tre talpar [x, y] @msg direct-select three anchor points, or give `points` direkte markér tre ankerpunkter, eller angiv `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje +@msg `at` must be "start" or "end" `at` skal være "start" eller "end" +@msg give exactly one of `through` and `toward` angiv præcis én af `through` og `toward` +@msg no arc fits these points: two are the same or all three lie on one line ingen bue passer til disse punkter: to er ens, eller alle tre ligger på én linje +@msg give `at` only with `toward` angiv kun `at` sammen med `toward` @msg no app to open files here ingen app til at åbne filer her @msg no artboard ingen tegneflade @msg no artboard {i} (0-based; the document has {_1}) ingen tegneflade {i} (0-baseret; dokumentet har {_1}) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..84f56dacb8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -208,6 +208,10 @@ font-technology Variable Variabel Arc Bogen Arc Lower… Bogen unten… Arc Tool Bogen-Werkzeug + Three-Point Arc Tool Dreipunkt-Bogen-Werkzeug + Three-Point Arc Dreipunkt-Bogen + Arc too large Bogen zu groß + Third Point Sets Direction Dritter Punkt gibt die Richtung an Arc Upper… Bogen oben… Arch… Torbogen… Arc… Bogen… @@ -4918,6 +4922,10 @@ liquify-list-end {0}, {1} {0} und {1} @msg `points` must be three [x, y] pairs of numbers `points` muss aus drei Zahlenpaaren [x, y] bestehen @msg direct-select three anchor points, or give `points` wählen Sie drei Ankerpunkte direkt aus oder geben Sie `points` an @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie +@msg `at` must be "start" or "end" `at` muss „start“ oder „end“ sein +@msg give exactly one of `through` and `toward` geben Sie genau eines von `through` und `toward` an +@msg no arc fits these points: two are the same or all three lie on one line zu diesen Punkten passt kein Bogen: zwei sind gleich oder alle drei liegen auf einer Linie +@msg give `at` only with `toward` geben Sie `at` nur zusammen mit `toward` an @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien @msg no artboard keine Zeichenfläche @msg no artboard {i} (0-based; the document has {_1}) keine Zeichenfläche {i} (Zählung ab 0; das Dokument hat {_1}) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..47c73809f3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -210,6 +210,10 @@ font-technology Variable Μεταβλητές Arc Τόξο Arc Lower… Κάτω τόξο… Arc Tool Τόξο (Arc Tool) + Three-Point Arc Tool Εργαλείο τόξου τριών σημείων + Three-Point Arc Τόξο τριών σημείων + Arc too large Το τόξο είναι πολύ μεγάλο + Third Point Sets Direction Το τρίτο σημείο ορίζει την κατεύθυνση Arc Upper… Πάνω τόξο… Arch… Αψίδα… Arc… Τόξο… @@ -4976,6 +4980,10 @@ digits Malayalam Μαλαγιάλαμ @msg `points` must be three [x, y] pairs of numbers το `points` πρέπει να είναι τρία ζεύγη αριθμών [x, y] @msg direct-select three anchor points, or give `points` επιλέξτε άμεσα τρία σημεία αγκύρωσης ή δώστε `points` @msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία +@msg `at` must be "start" or "end" το `at` πρέπει να είναι "start" ή "end" +@msg give exactly one of `through` and `toward` δώστε ακριβώς ένα από τα `through` και `toward` +@msg no arc fits these points: two are the same or all three lie on one line κανένα τόξο δεν ταιριάζει σε αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία +@msg give `at` only with `toward` δώστε το `at` μόνο μαζί με το `toward` @msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ @msg no artboard δεν υπάρχει πίνακας σχεδίασης @msg no artboard {i} (0-based; the document has {_1}) δεν υπάρχει πίνακας σχεδίασης {i} (αρίθμηση από 0· το έγγραφο περιέχει {_1}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..55f8679f6b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -231,6 +231,10 @@ font-technology Variable Variables Arc Arco Arc Lower… Arco inferior… Arc Tool Herramienta Arco + Three-Point Arc Tool Herramienta Arco por tres puntos + Three-Point Arc Arco por tres puntos + Arc too large Arco demasiado grande + Third Point Sets Direction El tercer punto indica la dirección Arc Upper… Arco superior… Arch… Arcada… Arc… Arco… @@ -5022,6 +5026,10 @@ liquify-list-end {0}, {1} {0}, {1} @msg `points` must be three [x, y] pairs of numbers `points` debe ser tres pares de números [x, y] @msg direct-select three anchor points, or give `points` seleccione directamente tres puntos de ancla o indique `points` @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea +@msg `at` must be "start" or "end" `at` debe ser "start" o "end" +@msg give exactly one of `through` and `toward` indique exactamente uno de `through` y `toward` +@msg no arc fits these points: two are the same or all three lie on one line ningún arco se ajusta a estos puntos: dos son iguales o los tres están en una misma línea +@msg give `at` only with `toward` indique `at` solo junto con `toward` @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos @msg no artboard no hay mesa de trabajo @msg no artboard {i} (0-based; the document has {_1}) no existe la mesa de trabajo {i} (contando desde 0; el documento tiene {_1}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..584a7e2b38 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1406,6 +1406,10 @@ lighting Light Valo Add Anchor Point Tool Lisää ankkuripiste -työkalu Anchor Point Tool Ankkuripistetyökalu Arc Tool Kaarityökalu + Three-Point Arc Tool Kolmen pisteen kaaren työkalu + Three-Point Arc Kolmen pisteen kaari + Arc too large Kaari on liian suuri + Third Point Sets Direction Kolmas piste määrää suunnan Area Graph Tool Aluekaaviotyökalu Area Type Tool Aluetekstityökalu Artboard Tool Piirtoalustatyökalu @@ -5246,6 +5250,10 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `points` must be three [x, y] pairs of numbers `points` on annettava kolmena lukuparina [x, y] @msg direct-select three anchor points, or give `points` valitse suoraan kolme ankkuripistettä tai anna `points` @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla +@msg `at` must be "start" or "end" `at` on oltava "start" tai "end" +@msg give exactly one of `through` and `toward` anna täsmälleen yksi parametreista `through` ja `toward` +@msg no arc fits these points: two are the same or all three lie on one line näihin pisteisiin ei sovi kaarta: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla +@msg give `at` only with `toward` anna `at` vain yhdessä parametrin `toward` kanssa @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen @msg no artboard ei piirtoalustaa @msg no artboard {i} (0-based; the document has {_1}) ei piirtoalustaa {i} (0-pohjainen; asiakirjassa on {_1}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..6486babbde 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -232,6 +232,10 @@ font-technology Variable Variables Arc Arc Arc Lower… Arc inférieur… Arc Tool Outil Arc + Three-Point Arc Tool Outil Arc par trois points + Three-Point Arc Arc par trois points + Arc too large Arc trop grand + Third Point Sets Direction Le troisième point indique la direction Arc Upper… Arc supérieur… Arch… Arche… Arc… Arc… @@ -4984,6 +4988,10 @@ liquify-list-end {0}, {1} {0} et {1} @msg `points` must be three [x, y] pairs of numbers `points` doit contenir trois paires de nombres [x, y] @msg direct-select three anchor points, or give `points` sélectionnez trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés +@msg `at` must be "start" or "end" `at` doit valoir "start" ou "end" +@msg give exactly one of `through` and `toward` indiquez exactement un seul de `through` et `toward` +@msg no arc fits these points: two are the same or all three lie on one line aucun arc ne correspond à ces points : deux sont identiques ou les trois sont alignés +@msg give `at` only with `toward` indiquez `at` uniquement avec `toward` @msg no app to open files here aucune application pour ouvrir des fichiers ici @msg no artboard aucun plan de travail @msg no artboard {i} (0-based; the document has {_1}) aucun plan de travail {i} (numérotation à partir de 0 ; le document en a {_1}) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..5d82f47415 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -275,6 +275,10 @@ Arc Lower… નીચે આર્ક… Arc Segment Tool Options આર્ક સેગમેન્ટ ટૂલ વિકલ્પો Arc Tool આર્ક ટૂલ + Three-Point Arc Tool ત્રણ-પૉઇન્ટ આર્ક ટૂલ + Three-Point Arc ત્રણ-પૉઇન્ટ આર્ક + Arc too large આર્ક ખૂબ મોટો છે + Third Point Sets Direction ત્રીજો પૉઇન્ટ દિશા નક્કી કરે છે Arc Upper… ઉપર આર્ક… Arch… કમાન… Arc… આર્ક… @@ -4987,3 +4991,7 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" +@msg `at` must be "start" or "end" `at` "start" અથવા "end" હોવું જોઈએ +@msg give exactly one of `through` and `toward` `through` અને `toward` માંથી બરાબર એક આપો +@msg no arc fits these points: two are the same or all three lie on one line આ પૉઇન્ટ્સમાં કોઈ આર્ક બેસતો નથી: બે એકસરખા છે અથવા ત્રણેય એક જ રેખા પર છે +@msg give `at` only with `toward` `at` ફક્ત `toward` સાથે જ આપો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..65d42fc13c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -391,6 +391,10 @@ antiAlias Sharp शार्प Arc Lower… निचला आर्क… Arc Segment Tool Options आर्क सेगमेंट टूल ऑप्शन्स Arc Tool आर्क टूल + Three-Point Arc Tool थ्री-पॉइंट आर्क टूल + Three-Point Arc थ्री-पॉइंट आर्क + Arc too large आर्क बहुत बड़ा है + Third Point Sets Direction तीसरा पॉइंट दिशा तय करता है Arc Upper… ऊपरी आर्क… Arc… आर्क… Arch… मेहराब… @@ -7634,6 +7638,10 @@ liquify-list-end {0}, {1} {0} और {1} @msg `points` must be three [x, y] pairs of numbers `points` में संख्याओं के तीन [x, y] जोड़े होने चाहिए @msg direct-select three anchor points, or give `points` तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें @msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं +@msg `at` must be "start" or "end" `at` को "start" या "end" होना चाहिए। +@msg give exactly one of `through` and `toward` `through` और `toward` में से ठीक एक दें +@msg no arc fits these points: two are the same or all three lie on one line इन पॉइंट्स पर कोई आर्क फ़िट नहीं होता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं +@msg give `at` only with `toward` `at` केवल `toward` के साथ दें @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @msg no artboard कोई आर्टबोर्ड नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..dd38f6dc7f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -315,6 +315,10 @@ font-technology Variable Változó Arc Ív Arc Lower… Alsó ív… Arc Tool Ív + Three-Point Arc Tool Hárompontos ív eszköz + Three-Point Arc Hárompontos ív + Arc too large Az ív túl nagy + Third Point Sets Direction A harmadik pont adja meg az irányt Arc Upper… Felső ív… Arch… Boltív… Arc… Ív… @@ -5685,6 +5689,10 @@ liquify-list-end {0}, {1} {0} és {1} @msg `points` must be three [x, y] pairs of numbers a `points` három [x, y] számpár legyen @msg direct-select three anchor points, or give `points` jelölj ki közvetlen kijelöléssel három horgonypontot, vagy add meg a `points` értéket @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van +@msg `at` must be "start" or "end" `at`: "start" vagy "end" kell +@msg give exactly one of `through` and `toward` pontosan egyet adjon meg a `through` és a `toward` közül +@msg no arc fits these points: two are the same or all three lie on one line ezekre a pontokra nem illeszkedik ív: kettő egybeesik, vagy mindhárom egy egyenesen van +@msg give `at` only with `toward` az `at` csak a `toward` mellett adható meg @msg no app to open files here itt nincs fájlmegnyitó alkalmazás @msg no artboard nincs rajztábla @msg no artboard {i} (0-based; the document has {_1}) nincs ilyen sorszámú rajztábla: {i} (0-tól számozva; a dokumentumban ennyi van: {_1}) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..131b42d7dc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1331,6 +1331,10 @@ lighting Light Cahaya Add Anchor Point Tool Alat tambah titik jangkar Anchor Point Tool Alat titik jangkar Arc Tool Alat busur + Three-Point Arc Tool Alat busur tiga titik + Three-Point Arc Busur tiga titik + Arc too large Busur terlalu besar + Third Point Sets Direction Titik ketiga menentukan arah Area Graph Tool Alat grafik area Area Type Tool Alat teks area Artboard Tool Alat artboard @@ -7252,3 +7256,7 @@ breakText Glyphs Glif @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" +@msg `at` must be "start" or "end" `at` harus "start" atau "end" +@msg give exactly one of `through` and `toward` berikan tepat satu dari `through` dan `toward` +@msg no arc fits these points: two are the same or all three lie on one line tidak ada busur yang cocok dengan titik-titik ini: dua titik sama atau ketiganya segaris +@msg give `at` only with `toward` berikan `at` hanya bersama `toward` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..4c433d9170 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -233,6 +233,10 @@ font-technology Variable Variabili Arc Arco Arc Lower… Arco inferiore… Arc Tool Strumento Arco + Three-Point Arc Tool Strumento Arco per tre punti + Three-Point Arc Arco per tre punti + Arc too large Arco troppo grande + Third Point Sets Direction Il terzo punto indica la direzione Arc Upper… Arco superiore… Arch… Arcata… Arc… Arco… @@ -5052,6 +5056,10 @@ liquify-list-end {0}, {1} {0} e {1} @msg `points` must be three [x, y] pairs of numbers `points` deve essere composto da tre coppie di numeri [x, y] @msg direct-select three anchor points, or give `points` seleziona con Selezione diretta tre punti di ancoraggio oppure indica `points` @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati +@msg `at` must be "start" or "end" `at` deve essere "start" o "end" +@msg give exactly one of `through` and `toward` indicare esattamente uno tra `through` e `toward` +@msg no arc fits these points: two are the same or all three lie on one line nessun arco si adatta a questi punti: due coincidono oppure tutti e tre sono allineati +@msg give `at` only with `toward` indicare `at` solo insieme a `toward` @msg no app to open files here nessuna app per aprire file qui @msg no artboard nessuna tavola da disegno @msg no artboard {i} (0-based; the document has {_1}) nessuna tavola da disegno {i} (a partire da 0; il documento ne ha {_1}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..77827e1efa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1142,6 +1142,10 @@ antiAlias Sharp シャープ @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) すべてに適用 (ほかに {n} 個が見つかりません) Arc 円弧 Arc Tool 円弧ツール + Three-Point Arc Tool 3 点円弧ツール + Three-Point Arc 3 点円弧 + Arc too large 円弧が大きすぎます + Third Point Sets Direction 3 点目で方向を指定 Area / Path Type エリア内文字/パス上文字 Area Graph Tool 面グラフツール Area Type Tool エリア内文字ツール @@ -4846,6 +4850,10 @@ swatch Bright Violet ビビッドバイオレット @msg `points` must be three [x, y] pairs of numbers `points` は 3 組の数値 [x, y] にしてください @msg direct-select three anchor points, or give `points` アンカーポイントを 3 つダイレクト選択するか、`points` を指定してください @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります +@msg `at` must be "start" or "end" `at` には "start" または "end" を指定してください +@msg give exactly one of `through` and `toward` `through` と `toward` のどちらか一方だけを指定してください +@msg no arc fits these points: two are the same or all three lie on one line これらの点に合う円弧はありません: 2 つの点が同じか、3 点すべてが一直線上にあります +@msg give `at` only with `toward` `at` は `toward` と一緒にだけ指定してください @msg select at least two objects オブジェクトを 2 つ以上選択してください @msg exit isolation mode first 先に分離モードを終了してください @msg no saved presets 保存したプリセットはありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..42f7301bc3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3483,6 +3483,10 @@ lighting Light სინათლე Add Anchor Point Tool საყრდენი წერტილის დამატების ხელსაწყო Anchor Point Tool საყრდენი წერტილის ხელსაწყო Arc Tool რკალის ხელსაწყო + Three-Point Arc Tool სამწერტილიანი რკალის ხელსაწყო + Three-Point Arc სამწერტილიანი რკალი + Arc too large რკალი ზედმეტად დიდია + Third Point Sets Direction მესამე წერტილი მიმართულებას განსაზღვრავს Area Graph Tool ფართობითი დიაგრამის ხელსაწყო Area Type Tool არის ტექსტის ხელსაწყო Artboard Tool სამუშაო დაფის ხელსაწყო @@ -6831,6 +6835,10 @@ font-technology Variable ცვლადი @msg `points` must be three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების სამი [x, y] წყვილი @msg direct-select three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ სამი საყრდენი წერტილი ან მიუთითეთ `points` @msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს +@msg `at` must be "start" or "end" `at` უნდა იყოს "start" ან "end" +@msg give exactly one of `through` and `toward` მიუთითეთ ზუსტად ერთი: `through` ან `toward` +@msg no arc fits these points: two are the same or all three lie on one line ამ წერტილებს რკალი არ ერგება: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს +@msg give `at` only with `toward` `at` მიუთითეთ მხოლოდ `toward`-თან ერთად @msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის @msg no artboard სამუშაო დაფა არ არის @msg no artboard {i} (0-based; the document has {_1}) სამუშაო დაფა {i} არ არსებობს (0-დან ითვლება; დოკუმენტს აქვს {_1}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..37db37b4b6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1132,6 +1132,10 @@ antiAlias Sharp 날카롭게 @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 모두에 적용(누락 {n}개 더 있음) Arc 호 Arc Tool 호 도구 + Three-Point Arc Tool 3점 호 도구 + Three-Point Arc 3점 호 + Arc too large 호가 너무 큽니다 + Third Point Sets Direction 세 번째 점으로 방향 지정 Area / Path Type 영역/패스 문자 Area Graph Tool 영역 그래프 도구 Area Type Tool 영역 문자 도구 @@ -4773,6 +4777,10 @@ theme Appearance 외관 @msg `points` must be three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 세 개여야 합니다 @msg direct-select three anchor points, or give `points` 앵커 포인트 세 개를 직접 선택하거나 `points`를 지정하세요 @msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 +@msg `at` must be "start" or "end" `at`은(는) "start" 또는 "end"여야 합니다 +@msg give exactly one of `through` and `toward` `through`와 `toward` 중 정확히 하나만 지정하세요 +@msg no arc fits these points: two are the same or all three lie on one line 이 점들에 맞는 호가 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 +@msg give `at` only with `toward` `at`은(는) `toward`와 함께만 지정하세요 @msg select at least two objects 개체를 두 개 이상 선택하세요 @msg exit isolation mode first 먼저 격리 모드를 종료하세요 @msg no saved presets 저장된 프리셋이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..89d7e0835a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1904,6 +1904,10 @@ lighting Light Licht Add Anchor Point Tool Ankerpunt toevoegen Anchor Point Tool Ankerpunt-gereedschap Arc Tool Boog-gereedschap + Three-Point Arc Tool Driepuntsboog-gereedschap + Three-Point Arc Driepuntsboog + Arc too large Boog te groot + Third Point Sets Direction Derde punt geeft de richting aan Area Graph Tool Vlakdiagram-gereedschap Area Type Tool Vlaktype-gereedschap Artboard Tool Tekengebied-gereedschap @@ -5379,6 +5383,10 @@ imageTrace Outline Contour @msg `points` must be three [x, y] pairs of numbers `points` moet uit drie getallenparen [x, y] bestaan @msg direct-select three anchor points, or give `points` selecteer met directe selectie drie ankerpunten of geef `points` op @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn +@msg `at` must be "start" or "end" `at` moet "start" of "end" zijn +@msg give exactly one of `through` and `toward` geef precies één van `through` en `toward` +@msg no arc fits these points: two are the same or all three lie on one line er past geen boog bij deze punten: twee zijn gelijk of alle drie liggen op één lijn +@msg give `at` only with `toward` geef `at` alleen samen met `toward` @msg no app to open files here hier is geen app om bestanden mee te openen @msg no artboard geen tekengebied @msg no artboard {i} (0-based; the document has {_1}) geen tekengebied {i} (vanaf 0; het document heeft er {_1}) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..21d511ffa2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1356,6 +1356,10 @@ lighting Light Światło Add Anchor Point Tool Narzędzie Dodaj punkt kontrolny Anchor Point Tool Narzędzie Punkt kontrolny Arc Tool Narzędzie Łuk + Three-Point Arc Tool Narzędzie Łuk przez trzy punkty + Three-Point Arc Łuk przez trzy punkty + Arc too large Łuk jest za duży + Third Point Sets Direction Trzeci punkt wyznacza kierunek Area Graph Tool Narzędzie Wykres warstwowy Area Type Tool Narzędzie Tekst akapitowy Artboard Tool Narzędzie Obszar kompozycji @@ -5140,6 +5144,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg `points` must be three [x, y] pairs of numbers `points` musi zawierać trzy pary liczb [x, y] @msg direct-select three anchor points, or give `points` zaznacz bezpośrednio trzy punkty kontrolne lub podaj `points` @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej +@msg `at` must be "start" or "end" `at` musi mieć wartość "start" lub "end" +@msg give exactly one of `through` and `toward` podaj dokładnie jeden z parametrów `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line żaden łuk nie pasuje do tych punktów: dwa są takie same albo wszystkie trzy leżą na jednej prostej +@msg give `at` only with `toward` podaj `at` tylko razem z `toward` @msg no app to open files here brak aplikacji do otwierania plików @msg no artboard brak obszaru kompozycji @msg no artboard {i} (0-based; the document has {_1}) brak obszaru kompozycji {i} (numeracja od 0; dokument ma {_1}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..f9851ce49b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -226,6 +226,10 @@ antiAlias Sharp Nítido Arc Arco Arc Lower… Arco Inferior… Arc Tool Ferramenta Arco + Three-Point Arc Tool Ferramenta Arco por três pontos + Three-Point Arc Arco por três pontos + Arc too large Arco grande demais + Third Point Sets Direction O terceiro ponto indica a direção Arc Upper… Arco Superior… Arch… Abóbada… Arc… Arco… @@ -4326,6 +4330,10 @@ axis Both Ambos @msg `points` must be three [x, y] pairs of numbers `points` deve ter três pares de números [x, y] @msg direct-select three anchor points, or give `points` selecione diretamente três pontos de ancoragem ou informe `points` @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta +@msg `at` must be "start" or "end" `at` deve ser "start" ou "end" +@msg give exactly one of `through` and `toward` informe exatamente um entre `through` e `toward` +@msg no arc fits these points: two are the same or all three lie on one line nenhum arco se ajusta a esses pontos: dois são iguais ou os três estão na mesma reta +@msg give `at` only with `toward` informe `at` somente com `toward` @msg no app to open files here nenhum aplicativo para abrir arquivos aqui @msg no artboard nenhuma prancheta @msg no artboard {i} (0-based; the document has {_1}) nenhuma prancheta {i} (base 0; o documento tem {_1}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..d1007f216f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -229,6 +229,10 @@ font-technology Variable Вариативные Arc Дуга Arc Lower… Дуга снизу… Arc Tool Инструмент «Дуга» + Three-Point Arc Tool Инструмент «Дуга по трём точкам» + Three-Point Arc Дуга по трём точкам + Arc too large Дуга слишком велика + Third Point Sets Direction Третья точка задаёт направление Arc Upper… Дуга сверху… Arch… Арка… Arc… Дуга… @@ -5046,6 +5050,10 @@ liquify-list-end {0}, {1} {0} и {1} @msg `points` must be three [x, y] pairs of numbers `points` должен содержать три пары чисел [x, y] @msg direct-select three anchor points, or give `points` выделите прямым выделением три опорные точки или задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой +@msg `at` must be "start" or "end" `at` должно быть "start" или "end" +@msg give exactly one of `through` and `toward` укажите ровно один из параметров `through` и `toward` +@msg no arc fits these points: two are the same or all three lie on one line ни одна дуга не подходит к этим точкам: две точки совпадают или все три лежат на одной прямой +@msg give `at` only with `toward` указывайте `at` только вместе с `toward` @msg no app to open files here здесь нет приложения для открытия файлов @msg no artboard нет монтажной области @msg no artboard {i} (0-based; the document has {_1}) нет монтажной области {i} (счёт с 0; в документе {_1}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..a0bd35fb66 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -219,6 +219,10 @@ font-technology Variable Variabla Arc Båge Arc Lower… Nedre båge… Arc Tool Bågverktyg + Three-Point Arc Tool Verktyg för trepunktsbåge + Three-Point Arc Trepunktsbåge + Arc too large Bågen är för stor + Third Point Sets Direction Tredje punkten anger riktningen Arc Upper… Övre båge… Arch… Valv… Arc… Båge… @@ -4919,6 +4923,10 @@ liquify-list-end {0}, {1} {0} och {1} @msg `points` must be three [x, y] pairs of numbers `points` måste vara tre talpar [x, y] @msg direct-select three anchor points, or give `points` direktmarkera tre ankarpunkter eller ange `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje +@msg `at` must be "start" or "end" `at` måste vara "start" eller "end" +@msg give exactly one of `through` and `toward` ange exakt en av `through` och `toward` +@msg no arc fits these points: two are the same or all three lie on one line ingen båge passar de här punkterna: två är samma punkt eller så ligger alla tre på en linje +@msg give `at` only with `toward` ange `at` endast tillsammans med `toward` @msg no app to open files here det finns ingen app för att öppna filer här @msg no artboard ingen rityta @msg no artboard {i} (0-based; the document has {_1}) ingen rityta {i} (räknat från 0; dokumentet har {_1}) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..935008b5e3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -216,6 +216,10 @@ font-technology Variable Değişken Arc Yay Arc Lower… Ark Alt… Arc Tool Yay Aracı + Three-Point Arc Tool Üç Noktalı Yay Aracı + Three-Point Arc Üç Noktalı Yay + Arc too large Yay çok büyük + Third Point Sets Direction Üçüncü Nokta Yönü Belirler Arc Upper… Ark Üst… Arch… Kemer… Arc… Yay… @@ -4739,6 +4743,10 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `points` must be three [x, y] pairs of numbers `points` üç [x, y] sayı çifti olmalıdır @msg direct-select three anchor points, or give `points` üç bağlantı noktasını doğrudan seçin veya `points` verin @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde +@msg `at` must be "start" or "end" `at` "start" veya "end" olmalıdır +@msg give exactly one of `through` and `toward` `through` ve `toward` değerlerinden tam olarak birini verin +@msg no arc fits these points: two are the same or all three lie on one line bu noktalara uyan bir yay yok: ikisi aynı ya da üçü de aynı doğru üzerinde +@msg give `at` only with `toward` `at` değerini yalnızca `toward` ile birlikte verin @msg no app to open files here burada dosyaları açacak uygulama yok @msg no artboard çalışma yüzeyi yok @msg no artboard {i} (0-based; the document has {_1}) çalışma yüzeyi yok {i} (0 tabanlı; belgede {_1} var) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..5edad94723 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -227,6 +227,10 @@ font-technology Variable Варіативні Arc Дуга Arc Lower… Дуга знизу… Arc Tool Інструмент «Дуга» + Three-Point Arc Tool Інструмент «Дуга за трьома точками» + Three-Point Arc Дуга за трьома точками + Arc too large Дуга завелика + Third Point Sets Direction Третя точка задає напрямок Arc Upper… Дуга зверху… Arch… Арка… Arc… Дуга… @@ -5036,6 +5040,10 @@ liquify-list-end {0}, {1} {0} і {1} @msg `points` must be three [x, y] pairs of numbers `points` має містити три пари чисел [x, y] @msg direct-select three anchor points, or give `points` виділіть три опорні точки прямим виділенням або задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій +@msg `at` must be "start" or "end" `at` має бути "start" або "end" +@msg give exactly one of `through` and `toward` вкажіть рівно один із параметрів `through` і `toward` +@msg no arc fits these points: two are the same or all three lie on one line жодна дуга не підходить до цих точок: дві точки збігаються або всі три лежать на одній прямій +@msg give `at` only with `toward` вказуйте `at` лише разом із `toward` @msg no app to open files here тут немає програми для відкриття файлів @msg no artboard немає монтажної області @msg no artboard {i} (0-based; the document has {_1}) немає монтажної області {i} (рахунок з 0; у документі {_1}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..21d3a9cc9b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -252,6 +252,10 @@ font-technology Variable Biến thiên Arc Cung Arc Lower… Cung dưới… Arc Tool Công cụ Cung + Three-Point Arc Tool Công cụ Cung ba điểm + Three-Point Arc Cung ba điểm + Arc too large Cung quá lớn + Third Point Sets Direction Điểm thứ ba chỉ hướng Arc Upper… Cung trên… Arch… Vòm… Arc… Cung… @@ -5368,6 +5372,10 @@ liquify-list-end {0}, {1} {0} và {1} @msg `points` must be three [x, y] pairs of numbers `points` phải là ba cặp số [x, y] @msg direct-select three anchor points, or give `points` hãy chọn trực tiếp ba điểm neo hoặc cung cấp `points` @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng +@msg `at` must be "start" or "end" `at` phải là "start" hoặc "end" +@msg give exactly one of `through` and `toward` hãy cho đúng một trong hai `through` và `toward` +@msg no arc fits these points: two are the same or all three lie on one line không có cung nào khớp với các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng +@msg give `at` only with `toward` chỉ cho `at` cùng với `toward` @msg no app to open files here không có ứng dụng để mở tệp ở đây @msg no artboard không có bảng vẽ @msg no artboard {i} (0-based; the document has {_1}) không có bảng vẽ {i} (bắt đầu từ 0; tài liệu có {_1}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..4f9eac1140 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -177,6 +177,10 @@ antiAlias Sharp 锐利 Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 + Three-Point Arc Tool 三点弧形工具 + Three-Point Arc 三点弧形 + Arc too large 弧形过大 + Third Point Sets Direction 第三点指示方向 Arc Upper… 上弧形… Arch… 拱形… Arc… 弧形… @@ -4544,6 +4548,10 @@ imageTrace Outline 轮廓 @msg `points` must be three [x, y] pairs of numbers `points` 必须是三对数字 [x, y] @msg direct-select three anchor points, or give `points` 请直接选择三个锚点,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线 +@msg `at` must be "start" or "end" `at` 必须是 "start" 或 "end" +@msg give exactly one of `through` and `toward` `through` 和 `toward` 必须且只能指定一个 +@msg no arc fits these points: two are the same or all three lie on one line 没有弧形符合这些点:有两点相同,或三点共线 +@msg give `at` only with `toward` `at` 只能与 `toward` 一起指定 @msg select at least two objects 请至少选择两个对象 @msg exit isolation mode first 请先退出隔离模式 @msg no saved presets 没有已保存的预设 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..8b9dc7f67f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -191,6 +191,10 @@ font-technology Variable 可變 Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 + Three-Point Arc Tool 三點弧形工具 + Three-Point Arc 三點弧形 + Arc too large 弧形過大 + Third Point Sets Direction 第三點指示方向 Arc Upper… 上弧形… Arch… 拱形… Arc… 弧形… @@ -2077,6 +2081,10 @@ file-filter Templates 範本 @msg `points` must be three [x, y] pairs of numbers `points` 必須是三組數字 [x, y] @msg direct-select three anchor points, or give `points` 請以直接選取方式選取三個錨點,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線 +@msg `at` must be "start" or "end" `at` 必須是 "start" 或 "end" +@msg give exactly one of `through` and `toward` `through` 與 `toward` 必須且只能指定一個 +@msg no arc fits these points: two are the same or all three lie on one line 沒有弧形符合這些點:有兩點相同,或三點共線 +@msg give `at` only with `toward` `at` 只能與 `toward` 一起指定 @msg select at least two objects 請選取至少兩個物件 @msg exit isolation mode first 請先結束隔離模式 @msg no saved presets 沒有已儲存的預設集 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index f521e45c22..03786cd0ce 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -45,6 +45,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-anchor-smooth", include_bytes!("../../../assets/icons/dc-anchor-smooth.svg")), ("dc-appearance", include_bytes!("../../../assets/icons/dc-appearance.svg")), ("dc-arc", include_bytes!("../../../assets/icons/dc-arc.svg")), + ("dc-arc-three-point", include_bytes!("../../../assets/icons/dc-arc-three-point.svg")), ("dc-arrow-down", include_bytes!("../../../assets/icons/dc-arrow-down.svg")), ("dc-arrow-extend", include_bytes!("../../../assets/icons/dc-arrow-extend.svg")), ("dc-arrow-tip", include_bytes!("../../../assets/icons/dc-arrow-tip.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e352653279..7a9d64b15a 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -38,6 +38,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-touch-type" => "dc-touch-type", "tool-line" => "dc-line", "tool-arc" => "dc-arc", + "tool-three-point-arc" => "dc-arc-three-point", "tool-spiral" => "tornado", "tool-rect-grid" => "dc-rect-grid", "tool-polar-grid" => "dc-polar-grid", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 56de30acff..709780df21 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -37,7 +37,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ ( "Shapes", &[ - &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid", "flare"], + &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "threePointArc", "spiral", "rectangularGrid", "polarGrid", "flare"], &["ellipse"], &["polygon"], &["shaper"], @@ -460,6 +460,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::shapes::open_options(app, tool), + // The Three-Point Arc tool: whether the third point gives a direction. + vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none). "flare" => Ok(crate::dialogs::flare_options::open(app, None)), // A double click on the Print Tiling tool puts the pages back where the placement puts them. diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..2662b3fc37 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -788,6 +788,35 @@ from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 `` `baseAlong` must be one of x, y ``), as is a `slope` outside its range; the arc is not drawn and no undo step is added. +`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end"}` draws an +open circular arc from `start` to `end` and selects it. With `through`, the arc passes through that point. With +`toward`, the arc leaves `start` heading toward that point, so the line from `start` to the point is the arc's tangent +there. With `at: "end"`, the line from `end` to the point is the tangent at `end` instead. `at` is `"start"` when left +out, and `at` with `through` is an error. The arc has no fill and the current stroke (black when the stroke is none), +its ends are exactly the two points (it is not pixel-aligned), and it has a smooth anchor at the `through` point and +further smooth anchors so that no curve of the path turns more than a quarter turn. The result is +`{id, cx, cy, radius, sweep}`: the circle's center and radius, and the arc's turn in degrees, positive clockwise on the +page. One undo removes the arc. The command returns an error and draws nothing when two of the points are the same, +when the third point lies on the line through the ends, when the arc would reach past the canvas, when a point is not +`[x, y]`, when both or neither of `through` and `toward` are given, when `at` is anything but `"start"` or `"end"`, and +when `at` is given with `through`. + +The Three-Point Arc tool, in the Line Segment tool's group after the Arc tool, runs this command. A drag from one end to +the other, or a click on each, places the ends; Shift keeps the second end at 45° steps from the first (from General › +Constrain Angle). A click on a third point, or a press dragged to it, then draws the arc through it. With the tool's +`direction` option on, the third point gives the direction the arc leaves the first end in; with `mods.alt`, the +direction is at the second end, and Shift keeps the direction at 45° steps. Three-Point Arc Tool Options (`tool.options`, +or a double-click on the tool) sets `direction` with its Third Point Sets Direction box, and +`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. Until the +third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in +direction mode and, with Measurement Labels on, the radius. Where no arc fits, the tool shows "Arc too large" by the +pointer (nothing while the pointer is on an end), and a click there draws nothing and keeps the ends. Escape, and an +edit, Undo or Redo made outside the tool, remove the ends. + +```json +{"name":"run_command","arguments":{"command":"shape.threePointArc","params":{"start":[0,0],"end":[80,0],"through":[40,-40]}}} +``` + While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows the pointer. With `mods.alt` alone, dragging outward adds whole winds of four segments and dragging inward removes @@ -7119,7 +7148,7 @@ snap the pointer as drawing tools do, so dragging a corner onto another object's Every point a drawing tool places snaps the same way, through one snapper (#506): the Pen's and Curvature tool's anchors, the shape tools' start and dragged corner or radius (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, `arc`, `spiral`, `rectangularGrid`, `polarGrid`), the -Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and +Three-Point Arc tool's ends and third point, the Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides: its strokes and straight lines follow the hand (Snap to Grid and Snap to Pixel still move their ends). The point lands on another object's anchor, centre or path ("anchor", "center", "path"), else lines up with the anchors, edges and centres of the art and the artboards (a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..a8c443bd1a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -687,6 +687,7 @@ since 2026-10-01. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. +- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc, its center and its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4182189c4a..d587d64527 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -320,6 +320,7 @@ tools, never checked side by side) isn't captured row by row. | Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 | | Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | | Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | +| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | ## Modifier keys and temporary tools From aa2983906938031625eaec83a855b6a826b30a50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:31:13 -0800 Subject: [PATCH 07/51] Tools: the Three-Point Arc tool places a point with the keys held at release A release at the position of the last pointer event kept the point that the earlier keys had constrained. Pressing the third point with Shift and letting go with Shift and Alt drew the direction from the second end but kept the 45-degree step taken from the first. The release now places the point again when Shift or Alt changed, for both ends and the third point. A change of keys alone does not make the first press a drag, so a click that snaps to an anchor and is let go with Shift changed places only the first end. --- crates/tools/src/three_point_arc.rs | 20 ++++++----- crates/tools/src/three_point_arc/tests.rs | 41 +++++++++++++++++++++++ 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 67ce63e03f..c25a3dca05 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -58,8 +58,8 @@ pub struct ThreePointArcTool { pointer: Option, /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. at_end: bool, - /// Where the pressed pointer was at its last event, before snapping. - raw: Option, + /// Where the pressed pointer was at its last event, before snapping, and the keys held then. + raw: Option<(Point, Mods)>, } /// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through @@ -106,12 +106,14 @@ impl ThreePointArcTool { } } - /// The pressed pointer moved to `ev`: the point being placed follows it. + /// The pressed pointer moved to `ev`, or Shift or Alt changed: the point being placed follows + /// it. A change of keys alone does not make the press a drag. fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) { - self.raw = Some(ev.pos); + let moved = self.raw.is_none_or(|(p, _)| p != ev.pos); + self.raw = Some((ev.pos, ev.mods)); match &mut self.press { Some(Press::Start { at, dragged }) => { - *dragged |= ev.pos.distance(*at) >= cx.tol(DRAG_PX); + *dragged |= moved && ev.pos.distance(*at) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); } @@ -149,7 +151,7 @@ impl Tool for ThreePointArcTool { vec![] } PointerKind::Down => { - self.raw = Some(ev.pos); + self.raw = Some((ev.pos, ev.mods)); let leave = self.leave(cx, ev.mods); match (self.start, self.end) { (None, _) => { @@ -180,8 +182,10 @@ impl Tool for ThreePointArcTool { vec![] } PointerKind::Up => { - // A release away from the last drag event places the point where it is let go. - if self.press.is_some() && self.raw != Some(ev.pos) { + // A release away from the last drag event places the point where it is let go, and + // a release with Shift or Alt changed places it as those keys keep it. + let same = self.raw.is_some_and(|(p, m)| p == ev.pos && (m.shift, m.alt) == (ev.mods.shift, ev.mods.alt)); + if self.press.is_some() && !same { self.follow(cx, ev); } match (self.press.take(), self.start, self.pointer) { diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index 88e63dc1b4..d7c35ddc8b 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -209,6 +209,47 @@ fn a_point_is_placed_where_the_press_is_let_go() { assert_eq!(t.end, Some(Point::new(380.0, 300.0))); } +/// A release with Shift or Alt changed since the press places the point as the keys at the +/// release keep it, even where the pointer did not move. +#[test] +fn a_release_places_the_point_with_the_keys_held_then() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let (none, shift) = (Mods::default(), Mods { shift: true, ..Mods::default() }); + // The second end: pressed without Shift, let go with it. + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 306.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 306.0), shift)); + assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end); + // The third point in direction mode: pressed with Shift, let go with Shift and Alt, so the + // direction line keeps to 45° steps from the second end. + t.set_option("direction", &json!(true)); + let both = Mods { alt: true, ..shift }; + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), both)); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + let at = |key: &str, i: usize| params[key][i].as_f64().unwrap_or(f64::NAN); + let (dx, dy) = (at("toward", 0) - at("end", 0), at("toward", 1) - at("end", 1)); + assert!(params["at"] == "end" && (dx.abs() - dy.abs()).abs() < 1e-9, "{params}"); +} + +/// A first click that snaps to the rectangle's corner, 3 pt from the pointer, and is let go with +/// Shift changed places only the first end: a change of keys alone is not a drag. +#[test] +fn a_click_let_go_with_shift_changed_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let g = Point::new(200.0, 200.0); + let off = (203.0, 201.0); + let mut t = ThreePointArcTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, off, Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, off, Mods { shift: true, ..Mods::default() })); + assert_eq!((t.start, t.end), (Some(g), None)); +} + /// Shift keeps the second end at 45° steps from the first. #[test] fn shift_keeps_the_second_end_at_45_degree_steps() { From 07f852fb5940641f41bc9802494f1b493121b1cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 14:52:57 -0800 Subject: [PATCH 08/51] Brushes: Add original Artistic brush library --- crates/engine/src/cmd/brushlib.rs | 37 +++++++++++++++++++ crates/engine/src/tests/brushlib.rs | 29 ++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 4 ++ crates/ui-egui/src/i18n/bs.tsv | 4 ++ crates/ui-egui/src/i18n/ca.tsv | 4 ++ crates/ui-egui/src/i18n/cs.tsv | 4 ++ crates/ui-egui/src/i18n/da.tsv | 4 ++ crates/ui-egui/src/i18n/de.tsv | 4 ++ crates/ui-egui/src/i18n/el.tsv | 4 ++ crates/ui-egui/src/i18n/es.tsv | 4 ++ crates/ui-egui/src/i18n/fi.tsv | 4 ++ crates/ui-egui/src/i18n/fr.tsv | 4 ++ crates/ui-egui/src/i18n/gu.tsv | 4 ++ crates/ui-egui/src/i18n/hi.tsv | 4 ++ crates/ui-egui/src/i18n/hu.tsv | 4 ++ crates/ui-egui/src/i18n/id.tsv | 4 ++ crates/ui-egui/src/i18n/it.tsv | 4 ++ crates/ui-egui/src/i18n/ja.tsv | 4 ++ crates/ui-egui/src/i18n/ka.tsv | 4 ++ crates/ui-egui/src/i18n/ko.tsv | 4 ++ crates/ui-egui/src/i18n/nl.tsv | 4 ++ crates/ui-egui/src/i18n/pl.tsv | 4 ++ crates/ui-egui/src/i18n/pt-br.tsv | 4 ++ crates/ui-egui/src/i18n/ru.tsv | 4 ++ crates/ui-egui/src/i18n/sv.tsv | 4 ++ crates/ui-egui/src/i18n/tests.rs | 3 +- crates/ui-egui/src/i18n/tr.tsv | 4 ++ crates/ui-egui/src/i18n/uk.tsv | 4 ++ crates/ui-egui/src/i18n/vi.tsv | 4 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 4 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 4 ++ .../src/panels/tests_brush_libraries.rs | 9 ++++- docs/mcp.md | 4 +- docs/target-app-parity.md | 3 +- 34 files changed, 191 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 34becd7c02..629701fa11 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -179,6 +179,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit }, + BuiltinBrushLibrary { id: "artistic", name: "Artistic", make: artistic }, ]; /// Built-in library `id`, made once. @@ -232,6 +233,42 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush { Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) } } +/// Artistic: four original vector compositions that stretch along a path and take its color. +fn artistic() -> BrushLibrary { + let orbit = group(vec![ + black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())), + black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())), + ]); + let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))]; + for i in 0..6 { + let x = 9.0 + 16.0 * i as f64; + let side = if i % 2 == 0 { 1.0 } else { -1.0 }; + petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)]))); + } + let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))]; + for i in 0..5 { + let x = 20.0 * i as f64; + lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)]))); + lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)]))); + } + let mut facets = Vec::new(); + for i in 0..8 { + let x = 12.5 * i as f64; + let high = if i % 2 == 0 { 6.0 } else { 3.5 }; + facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)]))); + } + built( + "Artistic", + Document::new(100.0, 100.0), + vec![ + art("Orbit Lines", orbit, Colorization::Tints), + art("Petal Garland", group(petals), Colorization::Tints), + art("Lattice Braid", group(lattice), Colorization::Tints), + art("Facet Sweep", group(facets), Colorization::Tints), + ], + ) +} + /// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's /// own pattern, Pinstripes. fn art_ribbons() -> BrushLibrary { diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 4f0b739951..19ca14a3f0 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -116,7 +116,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "game-trails", "energy-beams", "dry-media", - "tech-circuit" + "tech-circuit", + "artistic" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); @@ -160,6 +161,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("game-trails", "art"), ("energy-beams", "art"), ("dry-media", "art"), + ("artistic", "art"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); @@ -190,6 +192,31 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap(); + let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + for b in &lib.brushes { + let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) }; + assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name); + for path in [line_to(180.0), line_to(1.0)] { + assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([line])); + assert_eq!(undo_len(&s), before + 1); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + /// Every path of brush art `n`: (anchors, opacity). fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> { let mut out = vec![]; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..3cbbddaa1d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7237,3 +7237,7 @@ breakText Glyphs Глифи @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Orbit Lines Орбитални линии + Petal Garland Гирлянд от венчелистчета + Lattice Braid Решетъчна плетка + Facet Sweep Фасетен щрих diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..ce8d8a4ab1 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7291,3 +7291,7 @@ shape Open Otvoren @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Orbit Lines Orbitalne linije + Petal Garland Vijenac od latica + Lattice Braid Rešetkasti preplet + Facet Sweep Fasetni potez diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..f1cffbafe9 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8126,3 +8126,7 @@ breakText Glyphs Glifs @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Orbit Lines Línies orbitals + Petal Garland Garlanda de pètals + Lattice Braid Trena reticular + Facet Sweep Traç facetat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..4c7f75f26e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9917,3 +9917,7 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Orbit Lines Orbitální čáry + Petal Garland Okvětní girlanda + Lattice Braid Mřížkový cop + Facet Sweep Fazetový tah diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..525afef49c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10025,3 +10025,7 @@ breakText Glyphs Glyffer @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Orbit Lines Banekurver + Petal Garland Kronbladsguirlande + Lattice Braid Gitterfletning + Facet Sweep Facetteret strøg diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..6697f76f1d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9516,3 +9516,7 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Orbit Lines Orbitlinien + Petal Garland Blütengirlande + Lattice Braid Gittergeflecht + Facet Sweep Facettenstrich diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..63445bf761 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8100,3 +8100,7 @@ breakText Glyphs Γλύφοι @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Orbit Lines Τροχιακές γραμμές + Petal Garland Γιρλάντα πετάλων + Lattice Braid Πλεξούδα πλέγματος + Facet Sweep Πολυεδρική πινελιά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..9ebf373510 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8087,3 +8087,7 @@ breakText Glyphs Glifos @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Orbit Lines Líneas orbitales + Petal Garland Guirnalda de pétalos + Lattice Braid Trenza reticular + Facet Sweep Trazo facetado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..728e5fd50f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8183,3 +8183,7 @@ breakText Glyphs Merkit @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Orbit Lines Kiertoradan viivat + Petal Garland Terälehtiköynnös + Lattice Braid Ristikkopunos + Facet Sweep Särmikäs veto diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..3501d9d831 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9902,3 +9902,7 @@ breakText Glyphs Glyphes @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Orbit Lines Lignes orbitales + Petal Garland Guirlande de pétales + Lattice Braid Tresse en treillis + Facet Sweep Trait à facettes diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..c220068e1d 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4987,3 +4987,7 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Orbit Lines ભ્રમણકક્ષાની રેખાઓ + Petal Garland પાંખડીઓની માળા + Lattice Braid જાળી વેણી + Facet Sweep પાસાદાર રેખા diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..853faccbf8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9524,3 +9524,7 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Orbit Lines कक्षीय रेखाएँ + Petal Garland पंखुड़ी माला + Lattice Braid जाली चोटी + Facet Sweep पहलूदार स्ट्रोक diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..2ebba74ca4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9905,3 +9905,7 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Orbit Lines Pályavonalak + Petal Garland Sziromfüzér + Lattice Braid Rácsfonat + Facet Sweep Fazettás vonás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..a26e217a71 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7252,3 +7252,7 @@ breakText Glyphs Glif @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Orbit Lines Garis Orbit + Petal Garland Rangkaian Kelopak + Lattice Braid Anyaman Kisi + Facet Sweep Sapuan Berfaset diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..048b51cdfb 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9550,3 +9550,7 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Orbit Lines Linee orbitali + Petal Garland Ghirlanda di petali + Lattice Braid Intreccio a reticolo + Facet Sweep Tratto sfaccettato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..a942a98e0e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9617,3 +9617,7 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Orbit Lines 軌道線 + Petal Garland 花びらのガーランド + Lattice Braid 格子編み + Facet Sweep 多面体のストローク diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..20f8c08415 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10285,3 +10285,7 @@ font-script Japanese იაპონური @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არაბეჭდვად შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Orbit Lines ორბიტული ხაზები + Petal Garland ფურცლების გირლანდა + Lattice Braid ბადის ნაწნავი + Facet Sweep წახნაგოვანი მონასმი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..7376c3321a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9514,3 +9514,7 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Orbit Lines 궤도 선 + Petal Garland 꽃잎 화환 + Lattice Braid 격자 땋기 + Facet Sweep 면 분할 붓질 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..b1f9cf82cd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9953,3 +9953,7 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Orbit Lines Baanlijnen + Petal Garland Bloemblaadjesslinger + Lattice Braid Rastervlecht + Facet Sweep Gefacetteerde streek diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..0a7463b817 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9770,3 +9770,7 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Orbit Lines Linie orbitalne + Petal Garland Girlanda płatków + Lattice Braid Plecionka kratowa + Facet Sweep Fasetowane pociągnięcie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..5278240f2c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9988,3 +9988,7 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Orbit Lines Linhas orbitais + Petal Garland Guirlanda de pétalas + Lattice Braid Trança em grade + Facet Sweep Traço facetado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..e27905223e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10011,3 +10011,7 @@ shape Open Открытый @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Orbit Lines Орбитальные линии + Petal Garland Гирлянда лепестков + Lattice Braid Решётчатое плетение + Facet Sweep Гранёный мазок diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..9ac219ec4d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9601,3 +9601,7 @@ digits Hindi Hindi @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Orbit Lines Banlinjer + Petal Garland Kronbladsgirlang + Lattice Braid Gallerfläta + Facet Sweep Fasetterat drag diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 97fccd9167..bf6fa61a89 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -501,8 +501,9 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { .flat_map(|(_, lib)| lib.brushes.iter().map(|b| b.name.clone()).collect::>()) .collect(); names.sort(); + let duplicates: Vec<&str> = names.windows(2).filter(|pair| pair[0] == pair[1]).map(|pair| pair[0].as_str()).collect(); + assert_eq!(duplicates, ["Zigzag"], "only the established Pattern Borders / Game Trails name is shared"); names.dedup(); - assert_eq!(names.len(), 46, "{names:?}"); let mut bad = vec![]; for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { let missing: Vec<&String> = names.iter().filter(|n| lang.catalog().plain(n).is_none()).collect(); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..1ec43640be 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9875,3 +9875,7 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Orbit Lines Yörünge Çizgileri + Petal Garland Taç Yaprağı Çelengi + Lattice Braid Kafes Örgü + Facet Sweep Fasetli Darbe diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..51c66702ad 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9526,3 +9526,7 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Orbit Lines Орбітальні лінії + Petal Garland Гірлянда пелюсток + Lattice Braid Ґратчасте плетіння + Facet Sweep Гранований мазок diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..935710a096 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7759,3 +7759,7 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Orbit Lines Đường quỹ đạo + Petal Garland Vòng hoa cánh + Lattice Braid Bện lưới + Facet Sweep Nét đa diện diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..411d5357f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9758,3 +9758,7 @@ breakText Glyphs 字形 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Orbit Lines 轨道线 + Petal Garland 花瓣花环 + Lattice Braid 格纹编织 + Facet Sweep 切面笔触 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..8c2fd76802 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9568,3 +9568,7 @@ breakText Glyphs 字符 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Orbit Lines 軌道線 + Petal Garland 花瓣花環 + Lattice Braid 格紋編織 + Facet Sweep 切面筆觸 diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 87fe34953f..7343068348 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -201,7 +201,8 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("game-trails"), json!("energy-beams"), json!("dry-media"), - json!("tech-circuit") + json!("tech-circuit"), + json!("artistic") ] ); let dry = entries.iter().find(|e| under(e) && e.params["library"] == "dry-media").map(|e| e.label.as_str()); @@ -232,6 +233,12 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Artistic"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("artistic"), Some(4))); + let undo = undo_len(&app); + click(&mut app, &ctx, "Orbit Lines", Modifiers::NONE, 3.0); + assert!(has(&app, "Orbit Lines") && !has(&app, "Facet Sweep")); + assert_eq!(undo_len(&app), undo + 1); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..425badc8e5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5051,9 +5051,9 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: ten generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle +Brush libraries are read-only sets of brushes: eleven generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and -Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`), the `.vectorcraft` files in the user library folder of the desktop app (User +Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, and Artistic with four original vector art brushes, id `artistic`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and `brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..d61eac876d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1104,9 +1104,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Artistic) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. + - **Artistic brush library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Artistic offers Orbit Lines, Petal Garland, Lattice Braid and Facet Sweep. Each is original, editable vector artwork stretched along a path by an art brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `artistic_library_strokes_are_editable_and_reopen_from_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers drawing on short and long paths, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. From 177236f4016a2806c94b879c78cb45839c0b8889 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:32:07 -0800 Subject: [PATCH 09/51] Brushes: Localize Artistic library name distinctly --- crates/engine/src/cmd/brushlib.rs | 8 ++++---- crates/engine/src/tests/brushlib.rs | 3 +++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/tests_brush_libraries.rs | 6 +++++- docs/mcp.md | 5 +++-- docs/target-app-parity.md | 4 ++-- 33 files changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 629701fa11..3c4767cfa5 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -179,7 +179,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit }, - BuiltinBrushLibrary { id: "artistic", name: "Artistic", make: artistic }, + BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic }, ]; /// Built-in library `id`, made once. @@ -258,7 +258,7 @@ fn artistic() -> BrushLibrary { facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)]))); } built( - "Artistic", + "Artistic Brushes", Document::new(100.0, 100.0), vec![ art("Orbit Lines", orbit, Colorization::Tints), @@ -822,8 +822,8 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc if let Some(found) = concealed_library_id(s, key).and_then(|id| s.brush_libraries.get(&id)) { return Some(found); } - if let Some(b) = BUILTIN.iter().find(|b| b.id == key) { - return Some((builtin_info(b), builtin_library(key)?)); + if let Some(b) = BUILTIN.iter().find(|b| b.id == key || (b.id == "artistic" && key.eq_ignore_ascii_case("Artistic"))) { + return Some((builtin_info(b), builtin_library(b.id)?)); } let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id; library(s, &id) diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 19ca14a3f0..f38204b85d 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -196,6 +196,9 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() { let mut s = session(); let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap(); + let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap(); + assert_eq!(alias.brushes, lib.brushes); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic"); let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"]; assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3cbbddaa1d..5595539b1b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7241,3 +7241,4 @@ breakText Glyphs Глифи Petal Garland Гирлянд от венчелистчета Lattice Braid Решетъчна плетка Facet Sweep Фасетен щрих + Artistic Brushes Художествени четки diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index ce8d8a4ab1..280b7393a3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7295,3 +7295,4 @@ shape Open Otvoren Petal Garland Vijenac od latica Lattice Braid Rešetkasti preplet Facet Sweep Fasetni potez + Artistic Brushes Umjetničke četke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f1cffbafe9..918743dc97 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8130,3 +8130,4 @@ breakText Glyphs Glifs Petal Garland Garlanda de pètals Lattice Braid Trena reticular Facet Sweep Traç facetat + Artistic Brushes Pinzells artístics diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4c7f75f26e..97d0b54527 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9921,3 +9921,4 @@ breakText Glyphs Glyfy Petal Garland Okvětní girlanda Lattice Braid Mřížkový cop Facet Sweep Fazetový tah + Artistic Brushes Umělecké štětce diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 525afef49c..04731cb1a6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10029,3 +10029,4 @@ breakText Glyphs Glyffer Petal Garland Kronbladsguirlande Lattice Braid Gitterfletning Facet Sweep Facetteret strøg + Artistic Brushes Kunstneriske pensler diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6697f76f1d..afd1a4b1d8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9520,3 +9520,4 @@ breakText Glyphs Glyphen Petal Garland Blütengirlande Lattice Braid Gittergeflecht Facet Sweep Facettenstrich + Artistic Brushes Künstlerische Pinsel diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 63445bf761..f6f33cd590 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8104,3 +8104,4 @@ breakText Glyphs Γλύφοι Petal Garland Γιρλάντα πετάλων Lattice Braid Πλεξούδα πλέγματος Facet Sweep Πολυεδρική πινελιά + Artistic Brushes Καλλιτεχνικά πινέλα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9ebf373510..ddcceaf867 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8091,3 +8091,4 @@ breakText Glyphs Glifos Petal Garland Guirnalda de pétalos Lattice Braid Trenza reticular Facet Sweep Trazo facetado + Artistic Brushes Pinceles artísticos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 728e5fd50f..ace4e320fc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8187,3 +8187,4 @@ breakText Glyphs Merkit Petal Garland Terälehtiköynnös Lattice Braid Ristikkopunos Facet Sweep Särmikäs veto + Artistic Brushes Taidesiveltimet diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3501d9d831..75acf0d7c8 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9906,3 +9906,4 @@ breakText Glyphs Glyphes Petal Garland Guirlande de pétales Lattice Braid Tresse en treillis Facet Sweep Trait à facettes + Artistic Brushes Pinceaux artistiques diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c220068e1d..538e29b870 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4991,3 +4991,4 @@ swatch [Registration] [રજિસ્ટ્રેશન] Petal Garland પાંખડીઓની માળા Lattice Braid જાળી વેણી Facet Sweep પાસાદાર રેખા + Artistic Brushes કલાત્મક બ્રશ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 853faccbf8..e2eb49c8dc 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9528,3 +9528,4 @@ theme Appearance अपीयरेंस Petal Garland पंखुड़ी माला Lattice Braid जाली चोटी Facet Sweep पहलूदार स्ट्रोक + Artistic Brushes कलात्मक ब्रश diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 2ebba74ca4..0f54351dcf 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9909,3 +9909,4 @@ breakText Glyphs Glifák Petal Garland Sziromfüzér Lattice Braid Rácsfonat Facet Sweep Fazettás vonás + Artistic Brushes Művészi ecsetek diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index a26e217a71..df78a33a13 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7256,3 +7256,4 @@ breakText Glyphs Glif Petal Garland Rangkaian Kelopak Lattice Braid Anyaman Kisi Facet Sweep Sapuan Berfaset + Artistic Brushes Kuas Artistik diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 048b51cdfb..885f4af387 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9554,3 +9554,4 @@ breakText Glyphs Glifi Petal Garland Ghirlanda di petali Lattice Braid Intreccio a reticolo Facet Sweep Tratto sfaccettato + Artistic Brushes Pennelli artistici diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a942a98e0e..3dbce04560 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9621,3 +9621,4 @@ breakText Glyphs 字形 Petal Garland 花びらのガーランド Lattice Braid 格子編み Facet Sweep 多面体のストローク + Artistic Brushes アートブラシ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 20f8c08415..42d7034155 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10289,3 +10289,4 @@ font-script Japanese იაპონური Petal Garland ფურცლების გირლანდა Lattice Braid ბადის ნაწნავი Facet Sweep წახნაგოვანი მონასმი + Artistic Brushes მხატვრული ფუნჯები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7376c3321a..d760fbfccd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9518,3 +9518,4 @@ breakText Glyphs 글리프 Petal Garland 꽃잎 화환 Lattice Braid 격자 땋기 Facet Sweep 면 분할 붓질 + Artistic Brushes 예술 브러시 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b1f9cf82cd..6752bfc08e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9957,3 +9957,4 @@ breakText Glyphs Glyphs Petal Garland Bloemblaadjesslinger Lattice Braid Rastervlecht Facet Sweep Gefacetteerde streek + Artistic Brushes Artistieke penselen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0a7463b817..9c4ecb5817 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9774,3 +9774,4 @@ breakText Glyphs Glify Petal Garland Girlanda płatków Lattice Braid Plecionka kratowa Facet Sweep Fasetowane pociągnięcie + Artistic Brushes Pędzle artystyczne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5278240f2c..993e2b42c1 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9992,3 +9992,4 @@ swatch Yellow Green Verde-amarelado Petal Garland Guirlanda de pétalas Lattice Braid Trança em grade Facet Sweep Traço facetado + Artistic Brushes Pincéis artísticos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e27905223e..e5c295c660 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10015,3 +10015,4 @@ shape Open Открытый Petal Garland Гирлянда лепестков Lattice Braid Решётчатое плетение Facet Sweep Гранёный мазок + Artistic Brushes Художественные кисти diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9ac219ec4d..4dabbb457d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9605,3 +9605,4 @@ digits Hindi Hindi Petal Garland Kronbladsgirlang Lattice Braid Gallerfläta Facet Sweep Fasetterat drag + Artistic Brushes Konstnärliga penslar diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 1ec43640be..4fc7996c39 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9879,3 +9879,4 @@ breakText Glyphs Glifler Petal Garland Taç Yaprağı Çelengi Lattice Braid Kafes Örgü Facet Sweep Fasetli Darbe + Artistic Brushes Sanatsal Fırçalar diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 51c66702ad..70b1ef5749 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9530,3 +9530,4 @@ breakText Glyphs Гліфи Petal Garland Гірлянда пелюсток Lattice Braid Ґратчасте плетіння Facet Sweep Гранований мазок + Artistic Brushes Художні пензлі diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 935710a096..1584130345 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7763,3 +7763,4 @@ breakText Glyphs Glyph Petal Garland Vòng hoa cánh Lattice Braid Bện lưới Facet Sweep Nét đa diện + Artistic Brushes Cọ nghệ thuật diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 411d5357f1..78d1fc3508 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9762,3 +9762,4 @@ breakText Glyphs 字形 Petal Garland 花瓣花环 Lattice Braid 格纹编织 Facet Sweep 切面笔触 + Artistic Brushes 艺术画笔 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8c2fd76802..e338396ee4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9572,3 +9572,4 @@ breakText Glyphs 字符 Petal Garland 花瓣花環 Lattice Braid 格紋編織 Facet Sweep 切面筆觸 + Artistic Brushes 藝術筆刷 diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 7343068348..88cf2f8be8 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -233,8 +233,12 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); - let r = app.run("window.brushLibrary", json!({"library": "Artistic"})).unwrap(); + let r = app.run("window.brushLibrary", json!({"library": "Artistic Brushes"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("artistic"), Some(4))); + let previous = crate::i18n::current(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + assert_eq!(crate::menus::display_label(&app, "window.brushLibrary", "Artistic Brushes"), "Künstlerische Pinsel"); + crate::i18n::set_current(previous); let undo = undo_len(&app); click(&mut app, &ctx, "Orbit Lines", Modifiers::NONE, 3.0); assert!(has(&app, "Orbit Lines") && !has(&app, "Facet Sweep")); diff --git a/docs/mcp.md b/docs/mcp.md index 425badc8e5..6ad039ff2f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5053,10 +5053,11 @@ error. Brush libraries are read-only sets of brushes: eleven generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and -Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, and Artistic with four original vector art brushes, id `artistic`), the `.vectorcraft` files in the user library folder of the desktop app (User +Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, and Artistic Brushes with four original vector art brushes, id `artistic`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and -`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). +`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). The +built-in Artistic Brushes library also accepts `Artistic` as a lookup name. `brush.addFromLibrary {library, name? | names?}` copies brushes into the document's Brushes as one undo step (no names: the whole library), with the resources their art uses: patterns, symbols, swatches (`swatchConflict` as for `edit.paste`), graphic styles and images. Brushes the document already has (same name and definition) are reported diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d61eac876d..d65b7cc148 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1104,10 +1104,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Artistic) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Artistic Brushes) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - - **Artistic brush library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Artistic offers Orbit Lines, Petal Garland, Lattice Braid and Facet Sweep. Each is original, editable vector artwork stretched along a path by an art brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `artistic_library_strokes_are_editable_and_reopen_from_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers drawing on short and long paths, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. + - **Artistic Brushes library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Artistic Brushes offers Orbit Lines, Petal Garland, Lattice Braid and Facet Sweep; commands also accept Artistic as a lookup name. Each is original, editable vector artwork stretched along a path by an art brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `artistic_library_strokes_are_editable_and_reopen_from_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers drawing on short and long paths, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. From e4edb7a3f371b58f9dc99712c45612988a294311 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:23:27 -0800 Subject: [PATCH 10/51] Rerun CI From ad00ab8c8fb817e8c1bceb294cfb6a07e0b38e7b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:51:15 -0800 Subject: [PATCH 11/51] Preserve loaded Artistic library name before built-in alias --- crates/engine/src/cmd/brushlib.rs | 10 +++++++--- crates/engine/src/tests/brushlib.rs | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 3c4767cfa5..524443a48c 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -822,11 +822,15 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc if let Some(found) = concealed_library_id(s, key).and_then(|id| s.brush_libraries.get(&id)) { return Some(found); } - if let Some(b) = BUILTIN.iter().find(|b| b.id == key || (b.id == "artistic" && key.eq_ignore_ascii_case("Artistic"))) { + if let Some(b) = BUILTIN.iter().find(|b| b.id == key) { return Some((builtin_info(b), builtin_library(b.id)?)); } - let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id; - library(s, &id) + if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) { + return library(s, &id); + } + // Keep the short built-in alias, but let a user or loaded library own its display name. + let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?; + Some((builtin_info(b), builtin_library(b.id)?)) } fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc)> { diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index f38204b85d..d23d2905af 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -220,6 +220,20 @@ fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() { + let mut file = vectorcraft_doc::Document::new(100.0, 100.0); + vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]); + let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file)); + let mut s = session(); + let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"})); + assert_eq!(loaded["name"], "Artistic"); + let id = loaded["library"].as_str().unwrap(); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id); + assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id); + assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works"); +} + /// Every path of brush art `n`: (anchors, opacity). fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> { let mut out = vec![]; From 51cf404cee3b2dafe1e35dc44b05b9247ddb8714 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 20:23:57 -0800 Subject: [PATCH 12/51] Docs: count Paint among the built-in brush libraries The area rows, the bundled-content row, the G5 entry and the UI row now name Paint and count eleven built-in brush libraries, and the ROADMAP progress log has a line for it. --- ROADMAP.md | 1 + docs/gaps.md | 6 +++--- docs/target-app-parity.md | 6 +++--- docs/ui-parity.md | 2 +- 4 files changed, 8 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b2ebdb0545..84f26b75f7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -126,6 +126,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. - 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. +- 2026-11-18: Built-in Paint brush library: Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep, original art brushes generated in code that take the stroke color as tints. Eleven built-in brush libraries; headline numbers unchanged. - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. - 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged. diff --git a/docs/gaps.md b/docs/gaps.md index 96a94b325c..ddc43e0131 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -671,8 +671,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (ten original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes (one - bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes) and Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (eleven original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes (one + bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes) and Paint (Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and @@ -694,7 +694,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Fine Grain, Canvas Weave, Burlap Sack, Cracked Glaze, Mosaic Floor, Quilted Squares, Leaded Glass and Damp Paper, painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the ten shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 3–13 h (estimated). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fcb92c0d5c..2e89aae85a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -255,7 +255,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (eleven generated libraries including Paint, Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -524,7 +524,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (ten generated in code including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (eleven generated in code including Paint, Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -576,7 +576,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries ten (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries eleven (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Paint, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8ddaf7c662..cbef0749e2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -451,7 +451,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves or the Gradient tool draws a vector; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Paint, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; eleven built-in libraries (original, generated in code) | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | From a5de88558f0a8a1b0829c07c63176976d1217e89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 02:09:37 -0800 Subject: [PATCH 13/51] Symbols: New Symbol and Delete Symbol read Shift and Alt from their own click MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The New Symbol and Delete Symbol buttons, the art drop on the panel and the menu's New Symbol… and Redefine Symbol read Shift and Alt from the release of the primary button over the control, instead of from the modifiers left at the end of the frame. Letting Shift or Alt go, or clicking elsewhere, later in the same frame no longer changes what the click does. --- crates/ui-egui/src/panels/symbols.rs | 119 +++++++++++++++++++++++---- 1 file changed, 101 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index c6cf27acf9..6e99df63ae 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -404,7 +404,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) { // Shift held at the release keeps the dropped art as ordinary art. let mut p = json!({ "ids": ids, "type": "dynamic" }); - if modifiers_at_release(ui).shift { + if modifiers_released_in(ui, zone.rect).shift { p["keepArt"] = json!(true); } if let Err(e) = app.run("symbol.new", p) { @@ -452,7 +452,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } else if new.clicked() { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. - let m = ui.input(|i| i.modifiers); + // Both are read as the button went up on it. + let m = modifiers_released_in(ui, new.rect); let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; if m.shift { p["keepArt"] = json!(true); @@ -465,9 +466,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // it: the dragged symbol, or every symbol Select All Unused picked when it is one of them. if let Some(name) = symbol_dropped(ui, &trash, &names, uid) { let picked = if marked.contains(&name) { &marked[..] } else { &[] }; - delete(app, picked, Some(&name), super::alt_held(ui)); + delete(app, picked, Some(&name), modifiers_released_in(ui, trash.rect).alt); } else if trash.clicked() { - delete(app, &marked, sel.as_deref(), super::alt_held(ui)); + delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.rect).alt); } }); } @@ -480,17 +481,20 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); - // Shift keeps the selected art as ordinary art instead of making it an instance. - let shift = ui.input(|i| i.modifiers.shift); - let redefine = if shift { json!({"name": sel, "keepArt": true}) } else { name.clone() }; - let new = if shift { json!({"keepArt": true}) } else { json!({}) }; - let items: [(&str, bool, &str, Value); 3] = [ - (tl!("New Symbol…"), has_sel, "ui.symbolOptions", new), - (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", redefine), - (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), + // Shift, held as the button went up on New Symbol… or Redefine Symbol, keeps the selected art + // as ordinary art instead of making it an instance. + let items: [(&str, bool, &str, Value, bool); 3] = [ + (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({}), true), + (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", name.clone(), true), + (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone(), false), ]; - for (label, enabled, cmd, params) in items { + for (label, enabled, cmd, mut params, keeps_art) in items { + let top = ui.cursor().min.y; if menu_item(ui, label, enabled, false) { + let row = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.cursor().min.y); + if keeps_art && modifiers_released_in(ui, row).shift { + params["keepArt"] = json!(true); + } app.run(cmd, params).ok(); } } @@ -589,18 +593,33 @@ fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option item.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) } -/// Whether Alt (Option) is held for a drop: when the primary button went up in this frame, as it -/// went up, else now. +/// Whether Alt (Option) is held for a click or a drop: when the primary button went up in this +/// frame, as it went up, else now. fn alt_at_release(ui: &Ui) -> bool { modifiers_at_release(ui).alt } -/// The modifiers held for a drop: when the primary button went up in this frame, as it went up, -/// else now. +/// The modifiers held for a click or a drop on `rect`: when the primary button last went up over +/// `rect` in this frame, as it went up, else as [`modifiers_at_release`] gives them. +fn modifiers_released_in(ui: &Ui, rect: egui::Rect) -> egui::Modifiers { + ui.input(|i| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } if rect.contains(*pos) => { + Some(*modifiers) + } + _ => None, + }) + }) + .unwrap_or_else(|| modifiers_at_release(ui)) +} + +/// The modifiers held for a click or a drop: when the primary button went up in this frame, as it +/// last went up (egui reports the click of the last release in the frame), else now. fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { ui.input(|i| { i.events .iter() + .rev() .find_map(|e| match e { egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), _ => None, @@ -1045,6 +1064,69 @@ mod tests { assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); } + /// A click of the primary button off the panel with no modifiers held, the pointer then back + /// at `at`. + fn stray_click(at: Pos2) -> [egui::Event; 4] { + let off = pos2(-10.0, -10.0); + let button = + |pressed| egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + [egui::Event::PointerMoved(off), button(true), button(false), egui::Event::PointerMoved(at)] + } + + /// Clicks the panel button labeled `label` with `modifiers` held as the primary button goes up, + /// between two clicks off the panel without them, and lets them go later in the same frame. + fn click_button_let_go(app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, app, vec![], modifiers); + let at = clickable(&out).into_iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + let let_go = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + let mut events = stray_click(at).to_vec(); + events.extend([press(true), press(false), let_go]); + events.extend(stray_click(at)); + frame_held(&ctx, app, events, modifiers); + } + + /// Clicks the menu item labeled `label` with `modifiers` held as the primary button goes up, + /// between two clicks off the menu without them, and lets them go later in the same frame. + fn click_menu_let_go(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) { + let held = egui::Event::ModifiersChanged(modifiers); + let labels = menu_frame(ctx, app, vec![held.clone()]); + let item = labels.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} in the menu")); + let press = |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers }; + let mut events = vec![held]; + events.extend(stray_click(item)); + events.extend([press(true), press(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + events.extend(stray_click(item)); + menu_frame(ctx, app, events); + } + + /// The New Symbol and Delete Symbol buttons and the menu's New Symbol… and Redefine Symbol read + /// Shift and Alt as the primary button goes up on them, though clicks elsewhere without them + /// come before and after and they are let go later in the same frame. + #[test] + fn symbol_clicks_read_the_modifiers_as_the_button_goes_up() { + let (mut app, rect) = leaf_dot_and_rect(); + click_button_let_go(&mut app, "New Symbol", egui::Modifiers::SHIFT | egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu_let_go(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol 2"), (0, 1), "the menu's Shift keeps the rectangle as ordinary art"); + app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap(); + click_menu_let_go(&ctx, &mut app, "Redefine Symbol", egui::Modifiers::SHIFT); + assert_eq!(art(&app, "Dot"), (0, 1), "Redefine Symbol with Shift keeps the rectangle as ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + // Dot holds the rectangle now and nothing places it, so Alt deletes it without asking. + click_button_let_go(&mut app, "Delete Symbol", egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt deletes an unused symbol without asking"); + assert_eq!(symbols(&mut app), ["Leaf", "New Symbol", "New Symbol 2"]); + } + /// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol. #[test] fn symbol_options_checks_keep_art() { @@ -2425,7 +2507,8 @@ mod tests { frame(ctx, app, vec![egui::Event::PointerMoved(from + vec2(40.0, 40.0))]); frame(ctx, app, vec![egui::Event::PointerMoved(from + vec2(80.0, 80.0))]); let held = frame_held(ctx, app, vec![egui::Event::PointerMoved(to)], egui::Modifiers::NONE); - frame_held(ctx, app, vec![button(to, false)], modifiers); + let release = egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }; + frame_held(ctx, app, vec![release], modifiers); held } From 863994ac633ac96f0dcd6008c9dd749cf83f0076 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 06:31:05 -0800 Subject: [PATCH 14/51] M1: mirror Direct Selection handles during dragging (#7842) --- crates/doc/src/text/object.rs | 10 + crates/engine/src/cmd/live/blend.rs | 5 + crates/engine/src/cmd/live/commands.rs | 2 +- crates/engine/src/cmd/path.rs | 8 +- crates/engine/src/cmd/typecmd.rs | 5 +- crates/engine/tests/direct_handle_mirror.rs | 437 ++++++++++++++++++++ crates/tools/src/direct.rs | 29 +- docs/gaps.md | 2 + docs/ui-parity.md | 2 +- 9 files changed, 487 insertions(+), 13 deletions(-) create mode 100644 crates/engine/tests/direct_handle_mirror.rs diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 746c0b69d5..1671bb591e 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -451,12 +451,22 @@ impl TextObject { /// fractions of the path. False, changing nothing, for other type, when the anchor doesn't /// exist, a degenerate `xf` or a path that would not be finite. pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool { + self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false) + } + /// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor + /// in document space, preserving the anchor kind. `independent` takes precedence. Both handles + /// are edited in one reshape, using the same validated document-to-text map. + pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool { let xf = self.xf; matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| { let Some(a) = path.anchor_mut(si, ai) else { return false }; let mut drawn = a.transform(xf); drawn.set_handle(out, pos, independent); + if symmetric && !independent { + let opposite = drawn.p - (pos - drawn.p); + if out { drawn.h_in = opposite } else { drawn.h_out = opposite } + } *a = drawn.transform(to_text); true }) diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index a2cb0e3f91..dcbb2c7188 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -225,6 +225,7 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(C, "handle must be in or out")), }; let independent = switch_or(p, "independent", false, C)?; + let symmetric = switch_or(p, "symmetric", false, C)? && !independent; let with = spine_points_param(p, C)?; // Any `with`, even an empty list, asks to move points, which a handle drag doesn't. if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) { @@ -234,6 +235,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?; if let Some(out) = handle { a.set_handle(out, q, independent); + if symmetric { + let opposite = a.p - (q - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } return Ok(()); } let delta = q - a.p; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 79b2915aa0..76d1fee968 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Move Spine Point", [], None, - "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", + "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, ignored with `independent`; both default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", has_doc, spine_move_anchor ), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 0960e5ca28..5038c1efa8 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool}", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (independent takes precedence); both default false", has_doc, set_handle ), @@ -458,12 +458,14 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { let out = str_param(p, "which") != Some("in"); let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?); let independent = switch_or(p, "independent", false, "path.setHandle")?; + let symmetric = switch_or(p, "symmetric", false, "path.setHandle")? && !independent; // A handle already there, on an anchor already of the kind it would get, changes nothing and // records no undo step. The handle is compared directly: `set_handle` would recompute the // other handle of a smooth anchor, which need not give back the same value. if let Some(a) = anchor_of(s, id, si, ai)? && (if out { a.h_out } else { a.h_in }) == pos && !(independent && a.kind != AnchorKind::Corner) + && (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p)) { return ok(); } @@ -471,6 +473,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { let path = path_mut(d, id)?; let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; a.set_handle(out, pos, independent); + if symmetric { + let opposite = a.p - (pos - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index f50a2c7364..436433f7fd 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Move Type Path Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, independent takes precedence; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", has_doc, set_path_handle ), @@ -1449,6 +1449,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in"); let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let independent = switch_or(p, "independent", false, C)?; + let symmetric = switch_or(p, "symmetric", false, C)?; let node = s.doc()?.doc.node(id); let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })); if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { @@ -1461,7 +1462,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { let within = |t: &TextObject| { t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)) }; - if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) { + if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) { t.kind = before; return Err(bad(C, "no such path anchor, or the path would reach past the canvas")); } diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/direct_handle_mirror.rs new file mode 100644 index 0000000000..9fa6f26927 --- /dev/null +++ b/crates/engine/tests/direct_handle_mirror.rs @@ -0,0 +1,437 @@ +//! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Anchor, AnchorKind, Point}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn view() -> ViewInfo { + ViewInfo { + smart_guides: false, + guides: false, + snap_to_point: false, + snap_to_grid: false, + snap_to_pixel: false, + snap_to_glyph: false, + corner_widgets: false, + show_bbox: false, + ..ViewInfo::default() + } +} + +fn session() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 900, "height": 700})); + for (key, value) in [("constrainAngle", json!(0)), ("showHandlesMultipleAnchors", json!(true)), ("realTimeDrawing", json!(true))] { + run(&mut s, "prefs.set", json!({"key": key, "value": value})); + } + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn curve(s: &mut Session, incoming: Point) -> NodeId { + let id = run( + s, + "path.create", + json!({"anchors": [ + {"x": 20, "y": 220}, + {"x": 100, "y": 100, "in": [incoming.x, incoming.y], "out": [180, 100]}, + {"x": 320, "y": 220} + ]}), + ); + let id = NodeId(id["id"].as_u64().unwrap()); + s.select_tool("directSelection", view()).unwrap(); + id +} + +fn anchor(s: &Session, id: NodeId) -> Anchor { + node(s, id).path_data().unwrap().subpaths[0].anchors[1] +} + +fn pointer(s: &mut Session, kind: PointerKind, at: Point, mods: Mods) { + s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(mods), view()).unwrap(); +} + +fn press_handle(s: &mut Session, at: Point) { + pointer(s, PointerKind::Down, at, Mods::default()); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.in_interaction(), "the visible handle press begins Reshape"); +} + +fn near(actual: Point, expected: Point) { + assert!(actual.distance(expected) < 1e-6, "point {actual:?}, expected {expected:?}"); +} + +fn handles(a: Anchor, incoming: Point, outgoing: Point, kind: AnchorKind) { + near(a.h_in, incoming); + near(a.h_out, outgoing); + assert_eq!(a.kind, kind); +} + +fn assert_other_geometry(s: &Session, id: NodeId, before: &Node) { + let after = node(s, id); + let (old, new) = (before.path_data().unwrap(), after.path_data().unwrap()); + assert_eq!(new.subpaths.len(), old.subpaths.len()); + assert_eq!(new.subpaths[0].closed, old.subpaths[0].closed); + assert_eq!(new.subpaths[0].anchors.len(), 3); + assert_eq!(new.subpaths[0].anchors[0], old.subpaths[0].anchors[0]); + assert_eq!(new.subpaths[0].anchors[2], old.subpaths[0].anchors[2]); + assert_eq!(new.subpaths[0].anchors[1].p, old.subpaths[0].anchors[1].p); + assert_eq!(after.appearance, before.appearance); +} + +#[test] +fn direct_handle_baseline_ordinary_smooth_keeps_the_opposite_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + assert_eq!(anchor(&s, id).kind, AnchorKind::Smooth); + let selection = json!(s.doc().unwrap().selection); + let undo = s.doc().unwrap().history.undo.len(); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, Mods::default()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(json!(s.doc().unwrap().selection), selection); +} + +#[test] +fn direct_handle_baseline_cmd_added_mid_drag_mirrors_the_opposite() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, Mods { cmd: true, ..Mods::default() }); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, Mods { cmd: true, ..Mods::default() }); +} + +#[derive(Debug, PartialEq)] +struct Snapshot { + document: Value, + selection: Value, + undo: usize, + redo: usize, +} + +fn snapshot(s: &Session) -> Snapshot { + let st = s.doc().unwrap(); + Snapshot { document: json!(st.doc), selection: json!(st.selection), undo: st.history.undo.len(), redo: st.history.redo.len() } +} + +fn assert_content(s: &Session, expected: &Snapshot) { + let got = snapshot(s); + assert_eq!(got.document, expected.document); + assert_eq!(got.selection, expected.selection); +} + +fn cmd() -> Mods { + Mods { cmd: true, ..Mods::default() } +} + +fn reflected(a: Point, q: Point) -> Point { + a - (q - a) +} + +fn constrained(a: Point, q: Point) -> Point { + a + vectorcraft_geom::constrain_angle_from(q - a, 45.0, 0.0) +} + +fn assert_mirrored(a: Anchor, q: Point, kind: AnchorKind) { + handles(a, reflected(a.p, q), q, kind); +} + +#[test] +fn direct_handle_stationary_cmd_release_repress_commit_and_next_gesture() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + for (mods, opposite) in [(cmd(), Point::new(20.0, 40.0)), (Mods::default(), Point::new(60.0, 70.0)), (cmd(), Point::new(20.0, 40.0))] { + pointer(&mut s, PointerKind::Drag, q, mods); + handles(anchor(&s, id), opposite, q, AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo, "previews are not separate edits"); + } + pointer(&mut s, PointerKind::Up, q, cmd()); + let committed = snapshot(&s); + assert_eq!(committed.undo, before.undo + 1); + assert_eq!(committed.selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &committed); + // Cmd did not install a persistent coupling mode: a later ordinary Smooth drag keeps + // the opposite handle's committed length, rather than matching the newly dragged length. + press_handle(&mut s, q); + let next = Point::new(180.0, 200.0); + pointer(&mut s, PointerKind::Drag, next, Mods::default()); + let a = anchor(&s, id); + near(a.h_out, next); + assert_eq!(a.kind, AnchorKind::Smooth); + assert!((a.h_in.distance(a.p) - 100.0).abs() < 1e-6); + assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 20.0); + assert!(((a.h_in - a.p).cross(a.h_out - a.p)).abs() < 1e-6); + pointer(&mut s, PointerKind::Up, next, Mods::default()); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 2); +} + +#[test] +fn direct_handle_shift_constrains_before_mirroring_and_alt_takes_priority() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let p = anchor(&s, id).p; + press_handle(&mut s, Point::new(180.0, 100.0)); + let raw = Point::new(180.0, 150.0); + let q = constrained(p, raw); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..shifted }); + handles(anchor(&s, id), Point::new(50.0, 100.0), q, AnchorKind::Corner); + // Removing Alt rebuilds from the original Smooth anchor, not the Corner preview. + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..cmd() }); + handles(anchor(&s, id), Point::new(50.0, 100.0), raw, AnchorKind::Corner); + pointer(&mut s, PointerKind::Up, raw, Mods { alt: true, ..cmd() }); +} + +#[test] +fn direct_handle_corner_with_collapsed_partner_is_reversible_without_changing_kind() { + let mut s = session(); + let id = curve(&mut s, Point::new(100.0, 100.0)); + let before = snapshot(&s); + assert_eq!(anchor(&s, id).kind, AnchorKind::Corner); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Corner); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(100.0, 100.0), q, AnchorKind::Corner); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Corner); + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap(); + assert_eq!(snapshot(&s), before); +} + +#[test] +fn direct_handle_stationary_drag_still_mirrors_unequal_partner_but_equal_is_noop() { + for (incoming, changes) in [(Point::new(50.0, 100.0), true), (Point::new(20.0, 100.0), false)] { + let mut s = session(); + let id = curve(&mut s, incoming); + let before = snapshot(&s); + let q = Point::new(180.0, 100.0); + press_handle(&mut s, q); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, q, cmd()); + if changes { + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + } else { + assert_eq!(snapshot(&s), before, "an already reflected pair records no edit"); + } + } +} + +#[test] +fn direct_handle_escape_restores_document_selection_and_existing_redo() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + run(&mut s, "shape.rectangle", json!({"x": 500, "y": 400, "width": 25, "height": 30})); + let redo_document = snapshot(&s).document; + run(&mut s, "edit.undo", json!({})); + run(&mut s, "select.set", json!({"ids": [id.0]})); + let before = snapshot(&s); + assert_eq!(before.redo, 1, "a real existing Redo is the cancellation control"); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap(); + assert!(!s.in_interaction()); + assert_eq!(snapshot(&s), before); + pointer(&mut s, PointerKind::Up, q, Mods::default()); + assert_eq!(snapshot(&s), before, "a later release does not commit the canceled preview"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(snapshot(&s).document, redo_document, "the prior Redo still restores its actual content"); +} + +#[test] +fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + let a = anchor(&s, id); + pointer(&mut s, PointerKind::Down, a.p, cmd()); + assert_eq!(s.tool_id(), "selection", "Cmd before Down keeps the existing Selection loan"); + pointer(&mut s, PointerKind::Up, a.p, cmd()); + assert_eq!(s.tool_id(), "directSelection"); + assert_eq!(anchor(&s, id), a); + assert_eq!(snapshot(&s).document, before.document); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo); +} + +fn text_anchor(s: &Session, id: NodeId) -> Anchor { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") }; + t.type_path().unwrap().subpaths[0].anchors[1] +} + +fn text_properties(s: &Session, id: NodeId) -> Value { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") }; + let vectorcraft_doc::TextKind::OnPath { start, end, .. } = &t.kind else { panic!("path text") }; + json!({"runs": t.runs, "para": t.para, "paras": t.paras, "xf": t.xf, "start": start, "end": end, + "effect": t.path_effect, "align": t.path_align, "spacing": t.path_spacing, "appearance": n.appearance}) +} + +fn path_text(s: &mut Session) -> NodeId { + let path = curve(s, Point::new(50.0, 100.0)); + let made = run( + s, + "text.createInPath", + json!({"path": path.0, "mode": "onPath", "text": "Along the original curve", "font": "Source Sans 3", "size": 12}), + ); + let id = NodeId(made["id"].as_u64().unwrap()); + run(s, "type.pathOptions", json!({"id": id.0, "start": 0.15, "end": 0.85})); + run(s, "object.transform", json!({"ids": [id.0], "matrix": [1.5, 0.4, 0.25, 0.9, 250, 80]})); + s.select_tool("directSelection", view()).unwrap(); + id +} + +#[test] +fn direct_handle_affine_path_text_mirrors_in_drawn_space_and_keeps_brackets() { + let mut s = session(); + let id = path_text(&mut s); + let before = snapshot(&s); + let properties = text_properties(&s, id); + assert_eq!(properties["start"], json!(0.15)); + assert_eq!(properties["end"], json!(0.85)); + let a = text_anchor(&s, id); + assert_eq!(a.kind, AnchorKind::Smooth); + near(a.p, Point::new(425.0, 210.0)); + near(a.h_out, Point::new(545.0, 242.0)); + assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 40.0); + press_handle(&mut s, a.h_out); + let raw = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0); + pointer(&mut s, PointerKind::Drag, raw, cmd()); + assert_mirrored(text_anchor(&s, id), raw, AnchorKind::Smooth); + assert_eq!(text_properties(&s, id), properties); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(text_anchor(&s, id), constrained(a.p, raw), AnchorKind::Smooth); + assert_eq!(text_properties(&s, id), properties); + pointer(&mut s, PointerKind::Up, raw, shifted); + let after = snapshot(&s); + assert_eq!(after.undo, before.undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &after); +} + +fn blend_state(s: &Session, id: NodeId) -> (Anchor, Value, Vec) { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") }; + assert!(spec.spine.is_some(), "the fixture uses an already pinned spine"); + let path = vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0; + (path.subpaths[0].anchors[1], json!(children), spec.key_anchors.clone()) +} + +fn blend(s: &mut Session) -> NodeId { + let a = run(s, "shape.rectangle", json!({"x": 15, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap(); + let b = run(s, "shape.rectangle", json!({"x": 295, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap(); + let made = run(s, "object.blend.make", json!({"ids": [a, b], "steps": 2})); + let id = NodeId(made["id"].as_u64().unwrap()); + let added = run(s, "object.blend.spine.addAnchor", json!({"id": id.0, "x": 100, "y": 100})); + assert_eq!(added["anchor"], json!(1)); + run(s, "object.blend.spine.convertAnchor", json!({"id": id.0, "anchor": 1, "to": "smooth", "x": 180, "y": 100})); + run(s, "object.blend.spine.moveAnchor", json!({"id": id.0, "anchor": 1, "handle": "in", "x": 50, "y": 100})); + run(s, "select.set", json!({"ids": [id.0]})); + s.select_tool("directSelection", view()).unwrap(); + let (middle, _, keys) = blend_state(s, id); + near(middle.p, Point::new(100.0, 100.0)); + handles(middle, Point::new(50.0, 100.0), Point::new(180.0, 100.0), AnchorKind::Smooth); + assert_eq!(keys, [0, 2]); + // An actual spine-point click makes its handles visible to Direct Selection. + pointer(s, PointerKind::Down, middle.p, Mods::default()); + pointer(s, PointerKind::Up, middle.p, Mods::default()); + assert!(!s.in_interaction()); + id +} + +#[test] +fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() { + let mut s = session(); + let id = blend(&mut s); + let before = snapshot(&s); + let (a, keys, mapping) = blend_state(&s, id); + press_handle(&mut s, a.h_out); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(blend_state(&s, id).0, q, AnchorKind::Smooth); + let raw = Point::new(180.0, 150.0); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(blend_state(&s, id).0, constrained(a.p, raw), AnchorKind::Smooth); + // The existing spine Shift-only path is deliberately unconstrained; Cmd's new rule + // must not leak into that old branch after the modifier is released. + pointer(&mut s, PointerKind::Drag, raw, Mods { shift: true, ..Mods::default() }); + near(blend_state(&s, id).0.h_out, raw); + pointer(&mut s, PointerKind::Drag, raw, shifted); + let (after_anchor, after_keys, after_mapping) = blend_state(&s, id); + assert_mirrored(after_anchor, constrained(a.p, raw), AnchorKind::Smooth); + assert_eq!(after_keys, keys, "handle edits leave the actual key art unchanged"); + assert_eq!(after_mapping, mapping); + pointer(&mut s, PointerKind::Up, raw, shifted); + let after = snapshot(&s); + assert_eq!(after.undo, before.undo + 1); + assert_eq!(after.selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &after); +} + +#[test] +fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + let original = node(&s, id); + press_handle(&mut s, Point::new(50.0, 100.0)); + let q = Point::new(40.0, 20.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_other_geometry(&s, id, &original); + pointer(&mut s, PointerKind::Up, q, cmd()); + handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1); + assert_eq!(snapshot(&s).selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); +} diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 9323bfb20f..6458b2a227 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -428,6 +428,21 @@ fn spine_anchor(cx: &ToolContext, (id, ai): (NodeId, usize)) -> Option Vec { + let symmetric = ev.mods.cmd && !ev.mods.alt; + let q = if symmetric && ev.mods.shift { + spine_anchor(cx, (id, anchor)).map_or(p, |a| a.p + vectorcraft_geom::constrain_angle_from(p - a.p, 45.0, cx.constrain_angle)) + } else { + p + }; + let mut params = json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}); + if symmetric { + params["symmetric"] = json!(true); + } + vec![Action::Preview("object.blend.spine.moveAnchor".into(), params)] +} + /// Blend `id`'s spine, built once for callers that look up several of its points. fn spine_path(cx: &ToolContext, id: NodeId) -> Option { match &cx.doc.node(id)?.kind { @@ -983,10 +998,11 @@ impl Tool for DirectSelectionTool { self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides); self.guides = guides; let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" }; - vec![Action::Preview( - cmd.into(), - json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}), - )] + let mut params = json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}); + if ev.mods.cmd && !ev.mods.alt { + params["symmetric"] = json!(true); + } + vec![Action::Preview(cmd.into(), params)] } (PointerKind::Drag, State::SpinePoint { id, anchor, from, start, began }) => { let mut out = vec![]; @@ -1024,10 +1040,7 @@ impl Tool for DirectSelectionTool { )); out } - (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => vec![Action::Preview( - "object.blend.spine.moveAnchor".into(), - json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": p.x, "y": p.y, "independent": ev.mods.alt}), - )], + (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => drag_spine_handle(cx, ev, (id, anchor, out), p), (PointerKind::Drag, State::Mesh) => self.mesh.drag_to(p).unwrap_or_default(), (PointerKind::Up, State::Mesh) => { self.state = State::Idle; diff --git a/docs/gaps.md b/docs/gaps.md index ea34b655ca..d363f1f1dd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -125,6 +125,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G1 Interaction fidelity +- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. + macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. - **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index db8acdeedb..db7b28fe5a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -238,7 +238,7 @@ tools, never checked side by side) isn't captured row by row. | Drag a curved segment to bend it, a straight one to move its anchors | done | | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834) | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), or Control/Command added mid-drag (mirror the opposite handle) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; `crates/engine/tests/direct_handle_mirror.rs` | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | From b76c83eaf34383a9b2924b0e6208559723f8650e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 07:47:13 -0800 Subject: [PATCH 15/51] Direct Selection: the Cmd that lends it from the Pen does not mirror handles With the Pen chosen, Cmd/Ctrl lends Direct Selection for one gesture (the Pen's default loan, or the last selection tool chosen). The session takes Cmd off the press only, so the drags after it still carried Cmd and mirrored the opposite handle of every lent handle drag. The session now marks the lent tool, and that press does not mirror while it is held. Letting Cmd go and pressing it again during the drag mirrors, as in Direct Selection itself. path.setHandle, text.setPathHandle and object.blend.spine.moveAnchor refuse `symmetric` together with `independent`, and spine moves refuse `symmetric` without `handle`. At an open end, where no segment leaves the anchor on the other side, `symmetric` does not mirror. docs/mcp.md describes `symmetric` on the three commands. --- crates/doc/src/text/object.rs | 9 +- crates/engine/src/cmd/live/blend.rs | 10 +- crates/engine/src/cmd/live/commands.rs | 2 +- crates/engine/src/cmd/path.rs | 20 ++- crates/engine/src/cmd/typecmd.rs | 5 +- crates/engine/src/tooling.rs | 4 + crates/engine/tests/direct_handle_mirror.rs | 150 ++++++++++++++++++++ crates/geom/src/path.rs | 5 + crates/tools/src/direct.rs | 33 ++++- docs/gaps.md | 4 +- docs/mcp.md | 24 +++- docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 13 files changed, 247 insertions(+), 22 deletions(-) diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 1671bb591e..c0e305aeeb 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -454,16 +454,19 @@ impl TextObject { self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false) } /// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor - /// in document space, preserving the anchor kind. `independent` takes precedence. Both handles - /// are edited in one reshape, using the same validated document-to-text map. + /// in document space, preserving the anchor kind. `independent` takes precedence, and at an + /// open end of the path, where no segment leaves the anchor on that side, the handle moves as + /// it would without `symmetric`. Both handles are edited in one reshape, using the same validated + /// document-to-text map. pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool { let xf = self.xf; matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| { + let mirror = symmetric && !independent && path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, !out)); let Some(a) = path.anchor_mut(si, ai) else { return false }; let mut drawn = a.transform(xf); drawn.set_handle(out, pos, independent); - if symmetric && !independent { + if mirror { let opposite = drawn.p - (pos - drawn.p); if out { drawn.h_in = opposite } else { drawn.h_out = opposite } } diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index dcbb2c7188..04ffbe2b9f 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -225,13 +225,21 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(C, "handle must be in or out")), }; let independent = switch_or(p, "independent", false, C)?; - let symmetric = switch_or(p, "symmetric", false, C)? && !independent; + let symmetric = switch_or(p, "symmetric", false, C)?; let with = spine_points_param(p, C)?; // Any `with`, even an empty list, asks to move points, which a handle drag doesn't. if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) { return Err(bad(C, "`with` moves points, not a handle")); } + if symmetric && independent { + return Err(bad(C, "`independent` and `symmetric` cannot both be true")); + } + if symmetric && handle.is_none() { + return Err(bad(C, "`symmetric` places a handle: give `handle`")); + } edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| { + // At an open end of the spine the handle moves as it would without `symmetric`. + let symmetric = symmetric && handle.is_some_and(|out| sp.has_segment(index, !out)); let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?; if let Some(out) = handle { a.set_handle(out, q, independent); diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 76d1fee968..72fe483b11 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Move Spine Point", [], None, - "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, ignored with `independent`; both default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", + "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `symmetric` needs `handle` and cannot go with `independent`; both default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", has_doc, spine_move_anchor ), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 5038c1efa8..744b3648ea 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (independent takes precedence); both default false", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); independent and symmetric cannot both be true; both default false", has_doc, set_handle ), @@ -458,7 +458,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { let out = str_param(p, "which") != Some("in"); let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?); let independent = switch_or(p, "independent", false, "path.setHandle")?; - let symmetric = switch_or(p, "symmetric", false, "path.setHandle")? && !independent; + let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?; + if symmetric && independent { + return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true")); + } + // The other handle is mirrored only where a segment leaves the anchor on its side: at an open + // end the handle moves as it would without `symmetric`. + let symmetric = symmetric && has_segment(s, id, si, ai, !out)?; // A handle already there, on an anchor already of the kind it would get, changes nothing and // records no undo step. The handle is compared directly: `set_handle` would recompute the // other handle of a smooth anchor, which need not give back the same value. @@ -520,6 +526,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result Result { + if s.script_running() { + return Err(EngineError::Busy); + } + let d = &s.doc()?.doc; + Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out))) +} + fn set_anchors(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?; let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 436433f7fd..185baf734f 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Move Type Path Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, independent takes precedence; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", has_doc, set_path_handle ), @@ -1450,6 +1450,9 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let independent = switch_or(p, "independent", false, C)?; let symmetric = switch_or(p, "symmetric", false, C)?; + if symmetric && independent { + return Err(bad(C, "`independent` and `symmetric` cannot both be true")); + } let node = s.doc()?.doc.node(id); let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })); if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 794cc7a2a3..46158609a6 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -283,6 +283,10 @@ impl Session { let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); lent.set_option("meshPoints", &points); } + // The Cmd/Ctrl held for the loan is not the Cmd/Ctrl that mirrors a dragged handle (#7842). + if id == "directSelection" { + lent.set_option("lentByCmd", &Value::Bool(true)); + } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/direct_handle_mirror.rs index 9fa6f26927..d7fdfab36f 100644 --- a/crates/engine/tests/direct_handle_mirror.rs +++ b/crates/engine/tests/direct_handle_mirror.rs @@ -290,6 +290,42 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() { assert_eq!(s.doc().unwrap().history.undo.len(), before.undo); } +#[test] +fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + s.select_tool("pen", view()).unwrap(); + let before = node(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd()); + assert_eq!(s.tool_id(), "directSelection", "Cmd lends the Pen the last selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + // Cmd let go and pressed again during the drag mirrors, as it does in Direct Selection itself. + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); +} + +#[test] +fn direct_handle_cmd_held_through_a_pen_lent_drag_leaves_the_opposite_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + s.select_tool("pen", view()).unwrap(); + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd()); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); +} + fn text_anchor(s: &Session, id: NodeId) -> Anchor { let n = node(s, id); let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") }; @@ -435,3 +471,117 @@ fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_le run(&mut s, "edit.undo", json!({})); assert_content(&s, &before); } + +/// `command` with `params` is refused with an error containing `message`, and the document, +/// selection and undo history stay as they were. +fn refused(s: &mut Session, command: &str, params: Value, message: &str) { + let before = snapshot(s); + let err = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(err.contains(message), "{command} {params}: {err}"); + assert_eq!(snapshot(s), before); +} + +#[test] +fn path_set_handle_symmetric_mirrors_refuses_bad_values_and_records_no_step_when_in_place() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let at = |x: f64, y: f64| json!({"id": id.0, "anchor": 1, "which": "out", "x": x, "y": y}); + for bad in [json!("yes"), json!(1)] { + let mut p = at(180.0, 160.0); + p["symmetric"] = bad; + refused(&mut s, "path.setHandle", p, "`symmetric` must be true or false"); + } + let mut both = at(180.0, 160.0); + both["symmetric"] = json!(true); + both["independent"] = json!(true); + refused(&mut s, "path.setHandle", both, "`independent` and `symmetric` cannot both be true"); + + let undo = s.doc().unwrap().history.undo.len(); + let mut mirror = at(180.0, 160.0); + mirror["symmetric"] = json!(true); + run(&mut s, "path.setHandle", mirror.clone()); + handles(anchor(&s, id), Point::new(20.0, 40.0), Point::new(180.0, 160.0), AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let placed = snapshot(&s); + run(&mut s, "path.setHandle", mirror); + assert_eq!(snapshot(&s), placed, "both handles already in place record no undo step"); +} + +#[test] +fn symmetric_leaves_the_other_handle_retracted_at_an_open_end() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let first = |s: &Session| node(s, id).path_data().unwrap().subpaths[0].anchors[0]; + let p = first(&s).p; + run(&mut s, "path.setHandle", json!({"id": id.0, "anchor": 0, "which": "out", "x": 60, "y": 180, "symmetric": true})); + handles(first(&s), p, Point::new(60.0, 180.0), AnchorKind::Corner); + + let mut s = session(); + let blend_id = blend(&mut s); + let end = |s: &Session| { + let n = node(s, blend_id); + let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") }; + vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0.subpaths[0].anchors[0] + }; + let start = end(&s); + run(&mut s, "object.blend.spine.moveAnchor", json!({"id": blend_id.0, "anchor": 0, "handle": "out", "x": 60, "y": 60, "symmetric": true})); + near(end(&s).h_out, Point::new(60.0, 60.0)); + near(end(&s).h_in, start.h_in); + near(end(&s).h_in, start.p); +} + +#[test] +fn spine_and_type_path_handles_refuse_bad_symmetric_values() { + let mut s = session(); + let id = blend(&mut s); + let spine = |extra: Value| { + let mut p = json!({"id": id.0, "anchor": 1, "handle": "out", "x": 180, "y": 160}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + refused(&mut s, "object.blend.spine.moveAnchor", spine(json!({"symmetric": "yes"})), "`symmetric` must be true or false"); + refused( + &mut s, + "object.blend.spine.moveAnchor", + spine(json!({"symmetric": true, "independent": true})), + "`independent` and `symmetric` cannot both be true", + ); + refused( + &mut s, + "object.blend.spine.moveAnchor", + json!({"id": id.0, "anchor": 1, "x": 180, "y": 160, "symmetric": true}), + "`symmetric` places a handle", + ); + + let text = path_text(&mut s); + let a = text_anchor(&s, text); + let at = json!({"id": text.0, "anchor": 1, "which": "out", "x": a.h_out.x, "y": a.h_out.y + 20.0}); + let mut bad = at.clone(); + bad["symmetric"] = json!(0); + refused(&mut s, "text.setPathHandle", bad, "`symmetric` must be true or false"); + let mut both = at; + both["symmetric"] = json!(true); + both["independent"] = json!(true); + refused(&mut s, "text.setPathHandle", both, "`independent` and `symmetric` cannot both be true"); +} + +#[test] +fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror_type_on_a_path() { + let mut s = session(); + let id = path_text(&mut s); + let a = text_anchor(&s, id); + let length = a.h_in.distance(a.p); + s.select_tool("pen", view()).unwrap(); + pointer(&mut s, PointerKind::Down, a.h_out, cmd()); + assert_eq!(s.tool_id(), "directSelection"); + let q = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + let held = text_anchor(&s, id); + near(held.h_out, q); + assert!((held.h_in.distance(held.p) - length).abs() < 1e-6, "the other handle keeps its length"); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(text_anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); +} diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index c5343171ef..c3d9083ab3 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -280,6 +280,11 @@ impl SubPath { pub fn polyline(points: &[Point], closed: bool) -> Self { Self { anchors: points.iter().map(|&p| Anchor::corner(p)).collect(), closed } } + /// Whether anchor `ai` has a segment on its outgoing (`out`) or incoming side. + pub fn has_segment(&self, ai: usize, out: bool) -> bool { + let n = self.anchors.len(); + ai < n && n > 1 && (self.closed || if out { ai + 1 < n } else { ai > 0 }) + } /// Number of segments (a closed path has one more, back to the start). pub fn segment_count(&self) -> usize { let n = self.anchors.len(); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 6458b2a227..91797def71 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -248,9 +248,27 @@ pub struct DirectSelectionTool { frame_click: Option<(NodeId, AnchorRef)>, /// Where the pointer last hovered: the type on a path bracket under it draws thicker. bracket_hover: Option, + /// The Cmd/Ctrl press that lent this tool for one gesture (`lentByCmd`) is still + /// held: it does not mirror a dragged handle. Once Cmd/Ctrl is let go, pressing it again does. + lent_cmd: bool, } impl DirectSelectionTool { + /// Whether a handle drag with `ev`'s modifiers mirrors the opposite handle: Cmd/Ctrl held + /// without Alt, unless it is still the press that lent this tool for one gesture while another + /// tool, such as the Pen, is chosen. + fn mirrors(&self, ev: &PointerEvent) -> bool { + ev.mods.cmd && !ev.mods.alt && !self.lent_cmd + } + + /// Forget the lending Cmd/Ctrl once an event comes without it. The session takes Cmd/Ctrl off + /// the press it lends the tool for, while the drags after it still carry it. + fn track_lent_cmd(&mut self, ev: &PointerEvent) { + if ev.kind != PointerKind::Down { + self.lent_cmd &= ev.mods.cmd; + } + } + pub fn new(group: bool) -> Self { Self { group, @@ -278,6 +296,7 @@ impl DirectSelectionTool { frame_revision: (0, 0), frame_click: None, bracket_hover: None, + lent_cmd: false, } } @@ -429,8 +448,8 @@ fn spine_anchor(cx: &ToolContext, (id, ai): (NodeId, usize)) -> Option Vec { - let symmetric = ev.mods.cmd && !ev.mods.alt; +/// `symmetric`: the opposite handle mirrors the dragged one ([`DirectSelectionTool::mirrors`]). +fn drag_spine_handle(cx: &ToolContext, ev: &PointerEvent, (id, anchor, out): (NodeId, usize, bool), p: Point, symmetric: bool) -> Vec { let q = if symmetric && ev.mods.shift { spine_anchor(cx, (id, anchor)).map_or(p, |a| a.p + vectorcraft_geom::constrain_angle_from(p - a.p, 45.0, cx.constrain_angle)) } else { @@ -791,10 +810,15 @@ impl Tool for DirectSelectionTool { } /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group /// Selection, which selects whole objects, does not. + /// The session sets `lentByCmd` on the tool Cmd/Ctrl lends for one gesture + /// ([`DirectSelectionTool::mirrors`]). fn set_option(&mut self, key: &str, value: &Value) { if key == "meshPoints" && !self.group { self.mesh.set_options(value); } + if key == "lentByCmd" { + self.lent_cmd = value.as_bool().unwrap_or(false); + } } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved @@ -853,6 +877,7 @@ impl Tool for DirectSelectionTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.bracket_hover = (ev.kind == PointerKind::Move).then_some(ev.pos); + self.track_lent_cmd(ev); if let Some(out) = self.guide.pointer(cx, ev) { return out; } @@ -999,7 +1024,7 @@ impl Tool for DirectSelectionTool { self.guides = guides; let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" }; let mut params = json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}); - if ev.mods.cmd && !ev.mods.alt { + if self.mirrors(ev) { params["symmetric"] = json!(true); } vec![Action::Preview(cmd.into(), params)] @@ -1040,7 +1065,7 @@ impl Tool for DirectSelectionTool { )); out } - (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => drag_spine_handle(cx, ev, (id, anchor, out), p), + (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => drag_spine_handle(cx, ev, (id, anchor, out), p, self.mirrors(ev)), (PointerKind::Drag, State::Mesh) => self.mesh.drag_to(p).unwrap_or_default(), (PointerKind::Up, State::Mesh) => { self.state = State::Idle; diff --git a/docs/gaps.md b/docs/gaps.md index d363f1f1dd..6b48c3bec6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -125,10 +125,10 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G1 Interaction fidelity -- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. - macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. +- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. + - **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. diff --git a/docs/mcp.md b/docs/mcp.md index 8fbc770ca7..b7de8791f7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2198,7 +2198,7 @@ naming the key, and leave the document and its undo history as they were: `opaci The blend and envelope commands refuse a string, a number or another value that is not true or false with `` `smooth` must be true or false ``, naming the key, and leave the document, its undo history and the options new blends and envelopes start with as they were: `smooth` in `object.blend.make` and `object.blend.options`; -`independent` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal` +`independent` and `symmetric` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal` in `object.envelope.makeWithWarp`, `resetWithWarp` and `options`, also when an `orientation` is given; `maintainShape` in `object.envelope.resetWithMesh`; `antiAlias`, `distortAppearance`, `distortLinearGradients` and `distortPatternFills` in `object.envelope.options`; and `editing` in `object.envelope.editContents`. A null is read as @@ -6350,6 +6350,13 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. `path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that keeps its kind, leave the document as it is and record no undo step. +`path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same +length, and the anchor keeps its kind. At an open end, where no segment leaves the anchor on the other side, +`symmetric` has no effect and the handle moves as it would without it. Both `symmetric` and `independent` default to false, and a call with both true is +refused with `` `independent` and `symmetric` cannot both be true ``; the document does not change and no undo step +is recorded. Direct Selection sends `symmetric` while Cmd/Ctrl is held during a handle drag, unless that Cmd/Ctrl +press lent Direct Selection for the gesture while another tool, such as the Pen, was chosen and has not been let go +since (#7842). A call that puts both handles where they already are records no undo step. `path.insertAnchor` keeps the direct-selected anchors and selected segments of the path on the same points: those after the new anchor on its subpath are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves, with the new anchor as an end of both that moves with them. Undo restores the path and @@ -6467,7 +6474,7 @@ Left out or null, `width` is 8 pt. The range is VectorCraft's own value. These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: -`independent` in `path.close` and `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and +`independent` in `path.close` and `path.setHandle`; `symmetric` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and `fill` in `path.freehand` (and in `brush.freehand`); `closed` and the `corner` of a point in `path.curvature`; `corner` in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSelected`, `mergeOnlySelection` and `merge` in `path.blob`. A null is read as a key left out. @@ -10198,10 +10205,12 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane `text.reshapePath {id, anchors: [[subpath, anchor]…], dx, dy}` does the same for the path of type on a path (Direct Selection dragging one of its anchors): the start and end brackets keep their fractions of the path and the text reflows along it. -`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?}` moves a direction handle of one -of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in one -undo step. A call of `text.reshapeArea`, `text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and -`dy` both 0, or a handle moved to where it already is) adds no undo step and keeps redo. +`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?, symmetric?}` moves a direction handle +of one of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in +one undo step. With `symmetric: true` the other handle goes opposite the moved one at the same length, measured on +the page, as in `path.setHandle`; `symmetric` and `independent` cannot both be true. A call of `text.reshapeArea`, +`text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and `dy` both 0, or handles left where they +already are) adds no undo step and keeps redo. ```json {"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}} @@ -12683,7 +12692,8 @@ the compound path selected), and the next click starts a new path. Choosing any A blend's spine is the straight lines between its key centres until it is edited. `object.blend.info` lists it (`spine.anchors`, `keyAnchors`: the point each key sits on). `object.blend.spine.addAnchor {x, y}` adds a point where the spine passes nearest, `object.blend.spine.moveAnchor {anchor, x, y}` moves a point (a key on it moves along; with -`handle: "in" | "out"` it places that handle), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment +`handle: "in" | "out"` it places that handle, and with `symmetric: true` also the other handle opposite it at the +same length, as `path.setHandle` does; `symmetric` needs `handle` and cannot go with `independent`), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment so its point at `t` moves by (dx, dy), turning a straight spine into a curve (`perpendicular` works as in `path.reshapeSegment`), and `object.blend.spine.removeAnchor {anchor}` deletes a point no key sits on; the first edit turns the spine into a path. Moving a key moves its end of the spine. Release (`object.blend.release`) leaves the spine of a blend that has one as a path that paints nothing (`spines` in the result): diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d6072fd54f..bc8f9b5dd3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -713,6 +713,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. +- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index db7b28fe5a..deed54234b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -238,7 +238,7 @@ tools, never checked side by side) isn't captured row by row. | Drag a curved segment to bend it, a straight one to move its anchors | done | | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), or Control/Command added mid-drag (mirror the opposite handle) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; `crates/engine/tests/direct_handle_mirror.rs` | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), or Control/Command added mid-drag (mirror the opposite handle) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs` | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | From 236bafbf7af7f409204fde21e4a36dbf6ea811ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 13:43:15 -0800 Subject: [PATCH 16/51] Brushes: keep the library test's frame times increasing The Artistic Brushes click runs frames at 3.0 to 3.5, so the Pressure Sensitive click now starts at 4.0 instead of 3.0. egui panics when a frame's time is earlier than the last one. --- crates/ui-egui/src/panels/tests_brush_libraries.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index cdcb726874..4947e33444 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -248,7 +248,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), Some(4))); let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); let undo = undo_len(&app); - click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 3.0); + click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 4.0); assert!(has(&app, "Flex Ribbon") && !has(&app, "Pulse Stroke")); assert_eq!(undo_len(&app), undo + 1); assert_eq!( From 021587a1135f0fdc2b3e6c597bfe57bb6204d78d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:22:44 -0800 Subject: [PATCH 17/51] Brushes: keep the Pattern Borders doc comment on its own function --- crates/engine/src/cmd/brushlib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 5300cc084a..258fe76d2f 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -549,7 +549,6 @@ fn spacer(r: Rect) -> Node { Node::path(NodeId(0), shapes::rectangle(r), Appearance::default()) } -/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles. /// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one /// stroke stretched along the path, with an intentionally different edge and paint distribution. fn paint() -> BrushLibrary { @@ -589,6 +588,7 @@ fn paint() -> BrushLibrary { ) } +/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles. fn pattern_borders() -> BrushLibrary { let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)])); let beads = group(vec![black(shapes::rectangle(Rect::new(0.0, -0.3, 8.0, 0.3))), black(shapes::ellipse(Rect::new(1.5, -2.5, 6.5, 2.5)))]); From 6c2e9c5b1a70c0c4cf3e3f1e4d02945904f4c9c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:25:30 -0800 Subject: [PATCH 18/51] Symbols: drops read the release that ends the drag; other clicks use held keys A drop of art on the panel, art on a symbol and a symbol on Delete Symbol read Shift or Alt from the first primary release in the frame, which is the one that ends the drag. A later click in the same frame no longer turns a Shift drop into an instance, a plain drop into Redefine Symbol, or a plain drop on Delete Symbol into a delete without asking. New Symbol, Delete Symbol and the menu items still read the release over them. A click with no such release, from the keyboard or a screen reader, uses the keys held now instead of an unrelated release. --- crates/ui-egui/src/panels/symbols.rs | 130 ++++++++++++++++++++++----- 1 file changed, 109 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index a28aa8769c..a94ce33be1 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -403,9 +403,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover()); if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) { - // Shift held at the release keeps the dropped art as ordinary art. + // Shift held at the release that ends the drag keeps the dropped art as ordinary art. let mut p = json!({ "ids": ids, "type": "dynamic" }); - if modifiers_released_in(ui, zone.rect).shift { + if modifiers_at_release(ui).shift { p["keepArt"] = json!(true); } if let Err(e) = app.run("symbol.new", p) { @@ -472,7 +472,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // it: the dragged symbol, or every symbol Select All Unused picked when it is one of them. if let Some(name) = symbol_dropped(ui, &trash, &names, uid) { let picked = if marked.contains(&name) { &marked[..] } else { &[] }; - delete(app, picked, Some(&name), modifiers_released_in(ui, trash.rect).alt); + delete(app, picked, Some(&name), alt_at_release(ui)); } else if trash.clicked() { delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.rect).alt); } @@ -599,33 +599,35 @@ fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option item.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) } -/// Whether Alt (Option) is held for a click or a drop: when the primary button went up in this -/// frame, as it went up, else now. +/// Whether Alt (Option) is held for a drop: as [`modifiers_at_release`] gives it. fn alt_at_release(ui: &Ui) -> bool { modifiers_at_release(ui).alt } -/// The modifiers held for a click or a drop on `rect`: when the primary button last went up over -/// `rect` in this frame, as it went up, else as [`modifiers_at_release`] gives them. +/// The modifiers held for a click on `rect`: when the primary button last went up over `rect` in +/// this frame, as it went up (egui reports the click of the last release in the frame), else now, +/// as for a click from the keyboard or a screen reader. fn modifiers_released_in(ui: &Ui, rect: egui::Rect) -> egui::Modifiers { - ui.input(|i| { - i.events.iter().rev().find_map(|e| match e { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } if rect.contains(*pos) => { - Some(*modifiers) - } - _ => None, - }) - }) - .unwrap_or_else(|| modifiers_at_release(ui)) -} - -/// The modifiers held for a click or a drop: when the primary button went up in this frame, as it -/// last went up (egui reports the click of the last release in the frame), else now. -fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { ui.input(|i| { i.events .iter() .rev() + .find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } if rect.contains(*pos) => { + Some(*modifiers) + } + _ => None, + }) + .unwrap_or(i.modifiers) + }) +} + +/// The modifiers held for a drop: when the primary button went up in this frame, as it first went +/// up, which is the release that ends a drag under way when the frame starts; else now. +fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { + ui.input(|i| { + i.events + .iter() .find_map(|e| match e { egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), _ => None, @@ -1177,6 +1179,30 @@ mod tests { assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); } + /// A drop on the panel reads Shift from the release that ends the drag: a click on the list + /// without Shift later in the same frame keeps a Shift drop's art as ordinary art, and a click + /// with Shift does not keep a plain drop's art. + #[test] + fn a_drop_on_the_panel_reads_shift_from_the_release_that_ends_the_drag() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + let at = pos2(180.0, 60.0); + let release = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + let press = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers }; + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::SHIFT); + let plain = egui::Modifiers::NONE; + let events = vec![release(egui::Modifiers::SHIFT), egui::Event::ModifiersChanged(plain), press(plain), release(plain)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::SHIFT); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the Shift drop keeps the rectangle as ordinary art"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], plain); + let shift = egui::Modifiers::SHIFT; + let events = vec![release(plain), egui::Event::ModifiersChanged(shift), press(shift), release(shift)]; + frame_held(&ctx, &mut app, events, plain); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "the plain drop makes the rectangle an instance"); + } + /// A click of the primary button off the panel with no modifiers held, the pointer then back /// at `at`. fn stray_click(at: Pos2) -> [egui::Event; 4] { @@ -2935,6 +2961,68 @@ mod tests { assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged"); } + /// A plain art drop on a symbol followed in the same frame by an Alt-click on that symbol makes + /// a new symbol and leaves the symbol as it was: the release that ends the drag decides. + #[test] + fn an_alt_click_after_a_plain_art_drop_in_the_same_frame_does_not_redefine() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + let alt_press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT }; + let events = vec![button(at, false), egui::Event::ModifiersChanged(egui::Modifiers::ALT), alt_press, alt_release(at)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::NONE); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged"); + } + + /// A plain drop of an unused symbol on Delete Symbol followed in the same frame by an Alt-click + /// on the button still asks first: the release that ends the drag decides. + #[test] + fn an_alt_click_after_a_plain_drop_on_delete_in_the_same_frame_still_asks() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let trash = button_rect(&ctx, &mut app, "Delete Symbol").center(); + let dot = item_at(&ctx, &mut app, "Dot"); + frame(&ctx, &mut app, vec![]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot), button(dot, true)]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot + vec2(40.0, 40.0))]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot + vec2(80.0, 80.0))]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash)], egui::Modifiers::NONE); + let alt_press = + egui::Event::PointerButton { pos: trash, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT }; + let events = vec![button(trash, false), egui::Event::ModifiersChanged(egui::Modifiers::ALT), alt_press, alt_release(trash)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the plain drop asks first"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + } + + /// A screen reader's Click on Delete Symbol asks first for an unused symbol, though an Alt-click + /// elsewhere comes before it in the same frame and Alt is let go after. + #[test] + fn a_screen_reader_click_on_delete_does_not_take_alt_from_another_click() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = + nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")).map(|(id, _)| *id).expect("a Delete Symbol node"); + let off = pos2(-10.0, -10.0); + let alt = |pressed| egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + let click = + egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: node, target_tree: TreeId::ROOT, data: None }); + let events = vec![egui::Event::PointerMoved(off), alt(true), alt(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE), click]; + frame_held(&ctx, &mut app, events, egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the screen reader's Click asks first"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + } + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new /// symbol and adds no undo step: art of another document, objects the document no longer has, /// no objects, and a release away from the panel are not outlined, and art holding an instance From 1d7f3f6f22f9f484ae6342fb4dac5f84d68c81eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 14:56:28 -0800 Subject: [PATCH 19/51] Color Wheel: fix OKLCH and HSL slider review findings - The largest chroma at a hue near a primary color finds the stretch past the first gamut edge, so pure blue at chroma 0.4 stays blue. The C track dims the gap between the two stretches. - Oklab conversions use the signed sRGB transfer curve for channels below 0. - HSL hues wrap before the channel offsets; Color::to_hsl and from_hsl are removed, so callers pass the color settings themselves. - color.convert {to: "oklch"} clips RGB numbers past 0 to 1, as hex does. - A hue on a gray, or a saturation on black or white, leaves a Gray paint unchanged and records no undo step. - Remembered row and wheel components are dropped once the panel shows another color or target. - Hiding or switching the rows during a row drag keeps the preview as one undo step and ends the interaction. - The L and H tracks keep their colors until the other two components change, so a frame does not search the gamut for every track color. - Docs name the document's assigned profile as the RGB space OKLCH Sliders need, and give color.convert's example its color. --- crates/color/src/lib.rs | 24 ++- crates/color/src/libraries.rs | 12 +- crates/color/src/oklab.rs | 102 ++++++++++++- crates/engine/src/cmd/colormgmt.rs | 3 +- crates/engine/src/tests/colormgmt.rs | 15 +- crates/ui-egui/src/panels/color_wheel.rs | 138 ++++++++++++++---- .../ui-egui/src/panels/tests_color_wheel.rs | 73 ++++++++- docs/control-protocol.md | 4 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 10 files changed, 319 insertions(+), 62 deletions(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 8180f1c459..c3d74615ae 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -151,15 +151,6 @@ impl Color { let [r, g, b] = hsb_to_rgb([h, s, v]); Color::Rgb { r, g, b } } - /// HSL with hue in degrees 0..360, saturation and lightness 0..1 ([`rgb_to_hsl`] of the - /// display color). - pub fn to_hsl(&self) -> [f32; 3] { - rgb_to_hsl(self.to_rgb()) - } - pub fn from_hsl(h: f32, s: f32, l: f32) -> Self { - let [r, g, b] = hsl_to_rgb([h, s, l]); - Color::Rgb { r, g, b } - } /// `#rrggbb` (display RGB). pub fn to_hex(&self) -> String { let [r, g, b, _] = self.to_rgba8(1.0); @@ -380,10 +371,11 @@ pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] { /// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS /// Color 4 converts HSL to sRGB (): the inverse of -/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range, so -120° gives the color of 240°. -/// The specification's sample code uses JavaScript's remainder operator and gives a different -/// color for a negative hue. +/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120° +/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's +/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue. pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] { + let h = h.rem_euclid(360.0); let a = s * l.min(1.0 - l); let f = |n: f32| { let k = (n + h / 30.0).rem_euclid(12.0); @@ -565,11 +557,12 @@ mod tests { ([360.0, 1.0, 0.5], "#ff0000"), ([-120.0, 1.0, 0.5], "#0000ff"), ] { - assert_eq!(Color::from_hsl(hsl[0], hsl[1], hsl[2]).to_hex(), hex, "{hsl:?}"); + let [r, g, b] = hsl_to_rgb(hsl); + assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}"); } let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]); assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}"); - let [h, s, l] = Color::rgb8(255, 128, 0).to_hsl(); + let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated()); assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}"); // A gray has no hue: the hue is 0 and the saturation 0, at any lightness. for v in [0.0, 0.25, 0.5, 1.0] { @@ -581,6 +574,9 @@ mod tests { // A color past the gamut that gives a negative saturation turns its hue by 180°. let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]); assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}"); + // A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°. + let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5])); + assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}"); } /// The 216 web colors go to HSL and back to the same 8-bit color. diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index 5fc952a061..9c756256a3 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -99,7 +99,9 @@ pub fn builtin_library(id: &str) -> Option> { // ---------- colour construction ---------- -/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. +/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below +/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does +/// (). pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b; let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b; @@ -110,7 +112,7 @@ pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3, -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3, ]; - lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) + lin.map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) }) } /// OKLab `[l, a, b]` of a colour's display RGB. @@ -118,11 +120,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] { srgb_to_oklab(c.to_rgb_uncalibrated()) } -/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). +/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded +/// with the curve's sign turned, as CSS Color 4's extended sRGB does +/// (). pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] { let [r, g, b] = rgb.map(|v| { let v = f64::from(v); - if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) } }); let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt(); let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt(); diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 90467fc6c3..018df4526d 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -38,27 +38,78 @@ pub fn in_srgb(rgb: [f64; 3]) -> bool { /// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white. pub fn max_chroma(l: f64, h: f64) -> f64 { + largest_fitting_chroma(l, h, f64::INFINITY) +} + +/// The primary and secondary colors of sRGB: the corners of its cube next to black. +const PRIMARIES: [[f32; 3]; 6] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0]]; + +/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or +/// outside black and white. +fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 { if !(l > 0.0 && l < 1.0) || !h.is_finite() { return 0.0; } - // sRGB holds every chroma from 0 up to its edge along a hue at a given lightness. + let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h)); + // The edge of the chromas from 0 that sRGB holds without a break. let (mut lo, mut hi) = (0.0, 0.5); for _ in 0..40 { let mid = (lo + hi) / 2.0; - if in_srgb(oklch_to_srgb(l, mid, h)) { lo = mid } else { hi = mid } + if fits(mid) { lo = mid } else { hi = mid } } - lo + // Past that edge the ray can come back into sRGB near a line from black to a primary or + // secondary color. Such a line is straight in Oklab, so it keeps that color's hue and its + // chroma grows with its lightness. At the lightness and hue of blue, for example, the ray leaves + // sRGB at a chroma of about 0.266 and meets blue itself at about 0.313; at L 0.44 and a hue + // 0.01° past blue's, a second stretch runs from about 0.3042 to 0.3048. Each such stretch ends + // at or just below the line's chroma, so the search walks down from there in small steps to the + // first chroma that fits and then finds the stretch's end between it and the step above. + let past = PRIMARIES.iter().filter_map(|rgb| { + let [pl, a, b] = srgb_to_oklab(*rgb); + let edge = l / pl * a.hypot(b); + let off = (h - b.atan2(a).to_degrees()).rem_euclid(360.0); + if l > pl || edge <= lo || off.min(360.0 - off) > NEAR_PRIMARY_HUE { + return None; + } + let start = edge.min(limit); + let mut c = start; + while c > lo && start - c <= PAST_WALK { + if fits(c) { + let (mut inside, mut outside) = (c, (c + PAST_STEP).min(start)); + if outside > inside && !fits(outside) { + for _ in 0..20 { + let mid = (inside + outside) / 2.0; + if fits(mid) { inside = mid } else { outside = mid } + } + } else { + inside = outside; + } + return Some(inside); + } + c -= PAST_STEP; + } + None + }); + past.fold(lo.min(limit), f64::max) } +/// How near a primary or secondary color's hue, in degrees, the ray must pass for +/// [`largest_fitting_chroma`] to look past the first edge. +const NEAR_PRIMARY_HUE: f64 = 2.0; +/// The step of that walk. +const PAST_STEP: f64 = 2e-4; +/// How far below the line's chroma that walk goes. +const PAST_WALK: f64 = 0.06; + /// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: -/// a color outside sRGB keeps its lightness and hue and takes the largest chroma that fits. -/// Lightness is clamped to 0..=1 and chroma to 0 or more. +/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that +/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; let h = if h.is_finite() { h } else { 0.0 }; let exact = oklch_to_srgb(l, c, h); - let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, max_chroma(l, h).min(c), h), true) }; + let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) }; (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) } @@ -126,6 +177,45 @@ mod tests { assert!(!from_oklch(l, max * 0.5, h).1); } + /// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the + /// largest chroma is blue's, and a chroma past it gives blue. + #[test] + fn the_largest_chroma_at_blues_hue_is_blues() { + let [l, c, h] = to_oklch([0.0, 0.0, 1.0]); + let max = max_chroma(l, h); + assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}"); + let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h); + assert_eq!((eight(rgb), lowered), ([0, 0, 255], true)); + // A chroma between the two stretches takes the end of the first one, inside sRGB. + let (rgb, lowered) = from_oklch(l, 0.29, h); + let [_, gc, _] = to_oklch(rgb); + assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}"); + // A hue just past blue's: a narrow second stretch ends just below the line from black to blue. + let (l, h) = (0.44, 264.06); + let max = max_chroma(l, h); + assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}"); + let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0); + assert!(got > 0.303, "{got}"); + // A darker blue on the line from black to blue. + let [l, c, h] = to_oklch([0.0, 0.0, 0.25]); + assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h)); + } + + /// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's + /// extended sRGB does, in both directions. + #[test] + fn negative_channels_use_the_signed_transfer_curve() { + let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4); + let [l, c, _] = to_oklch([-0.5; 3]); + assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}"); + for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) { + assert!((v + 0.5).abs() < 1e-4, "{v}"); + } + // Small values near 0 keep the straight part of the curve. + let [l, _, _] = to_oklch([-0.01; 3]); + assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}"); + } + #[test] fn black_white_and_bad_numbers_hold_no_chroma() { assert_eq!(max_chroma(0.0, 30.0), 0.0); diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 7e27e9a12d..fafff19dfd 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -891,7 +891,8 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { "gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))), "lab" => ("lab", json!([lab.l, lab.a, lab.b])), "oklch" => { - let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col)); + // RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them. + let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0))); ("oklch", json!([l * 100.0, ch, h])) } other => return Err(bad(C, format!("unknown model `{other}`"))), diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 33bb47103e..8e043cdc84 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -338,14 +338,23 @@ fn convert_to_oklch_answers_lightness_chroma_and_hue() { let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap(); let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0))); let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); - let l = cyan["values"][0].as_f64().unwrap() / 100.0; - assert!((l - shown[0]).abs() < 1e-9 && (l - naive[0]).abs() > 0.02, "{cyan} {shown:?} {naive:?}"); + let c: Vec = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let got = [c[0] / 100.0, c[1], c[2]]; + assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}"); + assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}"); // A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB. let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap(); let w: Vec = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); - let clipped = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0))); + let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0)); + let clipped = vectorcraft_color::oklab::to_oklch(shown); assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}"); + assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}"); assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}"); + // RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white. + let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap(); + assert_eq!(past["hex"], "#ffffff"); + let l = past["values"][0].as_f64().unwrap(); + assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}"); } #[test] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 0b3549311f..d12e66c668 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -14,8 +14,9 @@ //! //! Panel menu › OKLCH Sliders shows L, C and H rows under the wheel or the box that edit the color //! by OKLCH lightness, chroma and hue (CSS Color 4: -//! ), while the working RGB space is -//! sRGB. Panel menu › HSL Sliders shows H, S and L rows in their place that edit the color by the +//! ), while the active document's RGB +//! space ([`cms::active`]: the profile assigned to the document, else the working RGB space of the +//! color settings) is sRGB. Panel menu › HSL Sliders shows H, S and L rows in their place that edit the color by the //! hue, saturation and lightness of CSS Color 4's HSL //! (). The choice is kept with the //! preferences too. @@ -139,7 +140,8 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { set(&mut app.ui.color_wheel, p, &cms::active())?; Ok(json!(app.ui.color_wheel)) @@ -292,7 +294,9 @@ const MEMORY: &str = "color-wheel-hsb"; /// Panel state: the OKLCH the slider rows asked for last, the [`Owner`] of the color they stored /// and its display sRGB. const OKLCH_MEMORY: &str = "color-wheel-oklch"; -/// The message for OKLCH Sliders while the working RGB space is not sRGB. +/// Panel state: the slider rows whose drag previews on an open interaction, until it is released. +const ROWS_LIVE: &str = "color-wheel-rows-live"; +/// The message for OKLCH Sliders while the active document's RGB space is not sRGB. const OKLCH_NEEDS_SRGB: &str = "OKLCH needs sRGB as the working RGB space"; /// Panel state: the HSL the slider rows asked for last, the [`Owner`] of the color they stored and /// its display sRGB. @@ -338,6 +342,28 @@ impl Owner { } } +/// The components remembered under `key` for the target's `color`: the display sRGB the color had +/// when they were stored, and the components. A record whose owner or display color differs from +/// what the panel shows now is dropped, so that it does not come back when the same color returns +/// later. +fn recall( + app: &VectorcraftApp, + ui: &Ui, + key: &str, + tgt: &Target, + color: Option, + cms: &Cms, +) -> Option<([f32; 3], T)> { + let (owner, shown, v) = pstate::>(ui.ctx(), key)?; + match color { + Some(c) if owner == Owner::of(app, tgt, c) && cms.display_rgb(&c) == shown => Some((shown, v)), + _ => { + set_pstate(ui.ctx(), key, None::<(Owner, [f32; 3], T)>); + None + } + } +} + /// The HSB a color shows on the wheel: that of its display sRGB through `cms`. pub(crate) fn display_hsb(cms: &Cms, c: &Color) -> [f32; 3] { rgb_to_hsb(cms.display_rgb(c)) @@ -403,13 +429,15 @@ pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; /// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed. /// A color outside sRGB shows at the largest chroma that fits at its L and H, the color a pick -/// there stores. With `max_chroma` (the C track, whose L and H stay fixed) that chroma is given; -/// without it, it is found for each color. +/// there stores. With `max_chroma` (the C track, whose L and H stay fixed) that chroma is given +/// for the colors past it; without it, or in a gap below it where the ray leaves sRGB and comes +/// back, it is found for each color. pub(crate) fn oklch_track(lch: [f64; 3], max_chroma: Option) -> Color32 { + let exact = oklab::oklch_to_srgb(lch[0], lch[1], lch[2]); let (rgb, outside) = match max_chroma { Some(m) if lch[1] > m => (oklab::oklch_to_srgb(lch[0], m, lch[2]), true), - Some(_) => (oklab::oklch_to_srgb(lch[0], lch[1], lch[2]), false), - None => { + Some(_) if oklab::in_srgb(exact) => (exact, false), + _ => { let (rgb, lowered) = oklab::from_oklch(lch[0], lch[1], lch[2]); (rgb.map(f64::from), lowered) } @@ -434,8 +462,8 @@ pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], Live)> { let t = Tokens::get(ui.ctx()); let enabled = color.is_some() && cms.rgb_is_srgb(); - let lch = match (color, pstate::>(ui.ctx(), OKLCH_MEMORY)) { - (Some(c), Some((owner, shown, lch))) if owner == Owner::of(app, tgt, c) => remembered_oklch(cms, &c, shown, lch), + let lch = match (color, recall::<[f64; 3]>(app, ui, OKLCH_MEMORY, tgt, color, cms)) { + (Some(c), Some((shown, lch))) => remembered_oklch(cms, &c, shown, lch), (Some(c), _) => oklab::to_oklch(cms.display_rgb(&c)), (None, _) => [0.0; 3], }; @@ -453,6 +481,9 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: out }; let mut out = None; + // The L and H tracks search the gamut for each color outside sRGB, so their colors are kept + // until the other two components change. + let mut tracks = pstate::<[Option<([u64; 3], Vec)>; 3]>(ui.ctx(), OKLCH_TRACKS); ui.add_enabled_ui(enabled, |ui| { let field_w = 48.0; let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); @@ -463,7 +494,23 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text))); let v = shown[i].clamp(0.0, max); let at = |x: f32| with(i, f64::from(x) * max); - let track = |x: f32| if enabled { oklch_track(at(x), (i == 1).then_some(max_c)) } else { t.input }; + let mut key = lch.map(f64::to_bits); + key[i] = 0; + let colors = match &tracks[i] { + Some((k, colors)) if i != 1 && enabled && *k == key => colors.clone(), + _ if i != 1 && enabled => { + let last = (TRACK_SAMPLES - 1) as f32; + let colors: Vec = (0..TRACK_SAMPLES).map(|s| oklch_track(at(s as f32 / last), None)).collect(); + tracks[i] = Some((key, colors.clone())); + colors + } + _ => Vec::new(), + }; + let track = |x: f32| match colors.get((x.clamp(0.0, 1.0) * (TRACK_SAMPLES - 1) as f32).round() as usize) { + Some(c) => *c, + None if enabled => oklch_track(at(x), (i == 1).then_some(max_c)), + None => t.input, + }; let value = SliderValue::field(v, 0.0..=max, suffix, 0); let (dragged, phase, keyed) = widgets::color_slider_stepped(ui, ("color-wheel-oklch", i), name, Some(value), (v / max) as f32, slider_w, &track); @@ -489,9 +536,16 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: }); } }); + set_pstate(ui.ctx(), OKLCH_TRACKS, tracks); out.filter(|_| enabled) } +/// Panel state: the colors of the L and H tracks of OKLCH Sliders, each with the OKLCH (its own +/// component left out) they were drawn for. +const OKLCH_TRACKS: &str = "color-wheel-oklch-tracks"; +/// How many colors along a cached track. +const TRACK_SAMPLES: usize = 128; + /// The HSL `[h°, s, l]` the rows show for `c` through `cms` when `hsl` was asked for last and `c` /// then displayed as the sRGB `shown`: `hsl` while `c` still displays as `shown` (the hue of a gray /// and the saturation of black and white stay), else `c`'s own. @@ -512,8 +566,8 @@ fn hsl32(hsl: [f32; 3]) -> Color32 { pub(crate) fn hsl_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f32; 3], Live)> { let t = Tokens::get(ui.ctx()); let enabled = color.is_some(); - let hsl = match (color, pstate::>(ui.ctx(), HSL_MEMORY)) { - (Some(c), Some((owner, shown, hsl))) if owner == Owner::of(app, tgt, c) => remembered_hsl(cms, &c, shown, hsl), + let hsl = match (color, recall::<[f32; 3]>(app, ui, HSL_MEMORY, tgt, color, cms)) { + (Some(c), Some((shown, hsl))) => remembered_hsl(cms, &c, shown, hsl), (Some(c), _) => rgb_to_hsl(cms.display_rgb(&c)), (None, _) => [0.0; 3], }; @@ -567,8 +621,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let cms = cms::active(); // With None, a pattern or a "?" proxy the wheel shows the last solid color without markers, // and a click, an arrow key or a screen reader's action applies the picked color. - let hsb = match (color, pstate::>(ui.ctx(), MEMORY)) { - (Some(c), Some((owner, shown, hsb))) if owner == Owner::of(app, &tgt, c) => remembered_hsb(&cms, &c, shown, hsb), + let hsb = match (color, recall::<[f32; 3]>(app, ui, MEMORY, &tgt, color, &cms)) { + (Some(c), Some((shown, hsb))) => remembered_hsb(&cms, &c, shown, hsb), (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); @@ -618,22 +672,41 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { picked_hsl = hsl_rows(app, ui, &tgt, color, &cms); } } + // A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`) reports no release: + // its preview is kept as one undo step and the interaction ends. + let live = pstate::>(ui.ctx(), ROWS_LIVE); + if live.is_some_and(|rows| rows != app.ui.color_wheel.sliders) { + if app.session.in_interaction() + && let Err(e) = app.session.commit_interaction() + { + app.status(e.to_string()); + } + app.sync_views(); + set_pstate(ui.ctx(), ROWS_LIVE, None::); + } let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); - if let Some((hsl, phase)) = picked_hsl { - let c = stored_srgb(&cms, hsl_to_rgb(hsl), replaced(app, &tgt, behind).as_ref(), cmyk_doc); - apply(app, &tgt, c, phase, behind); - if !behind { - set_pstate(ui.ctx(), HSL_MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), hsl))); + let rows = match (picked_hsl, picked_lch) { + (Some((hsl, phase)), _) => Some((hsl_to_rgb(hsl), phase, HSL_MEMORY, Remembered::Hsl(hsl))), + (_, Some((lch, phase))) => Some((oklab::from_oklch(lch[0], lch[1], lch[2]).0, phase, OKLCH_MEMORY, Remembered::Oklch(lch))), + _ => None, + }; + if let Some((srgb, phase, key, asked)) = rows { + // A hue on a gray, or a saturation on black or white, leaves the displayed color as it is: + // the rows keep what they were given, and the paint (a Gray color too) stays unchanged. + let current = color.filter(|c| { + let d = cms.display_rgb(c); + !behind && live.is_none() && (0..3).all(|i| (d[i] - srgb[i]).abs() <= 1e-5) + }); + if let Some(c) = current { + asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c)); + return; } - return; - } - if let Some((lch, phase)) = picked_lch { - let (srgb, _) = oklab::from_oklch(lch[0], lch[1], lch[2]); let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); + set_pstate(ui.ctx(), ROWS_LIVE, (phase == Live::Dragging).then_some(app.ui.color_wheel.sliders)); if !behind { - set_pstate(ui.ctx(), OKLCH_MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), lch))); + asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c)); } return; } @@ -644,3 +717,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), hsb))); } } + +/// What a slider row asked for, kept under its memory key. +enum Remembered { + Hsl([f32; 3]), + Oklch([f64; 3]), +} + +impl Remembered { + fn remember(self, ui: &Ui, key: &str, owner: Owner, shown: [f32; 3]) { + match self { + Remembered::Hsl(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))), + Remembered::Oklch(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))), + } + } +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 7cba14af3a..f13f78e8e2 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -691,6 +691,15 @@ fn the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_c let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); assert!(lowered); assert_eq!(oklch_track([0.98, 0.2, h], None), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); + // At blue's L and H the ray leaves sRGB below the largest chroma and comes back at blue: the C + // track dims that gap and shows the color a pick there stores. + let [bl, _, bh] = vectorcraft_color::oklab::to_oklch([0.0, 0.0, 1.0]); + let blue_max = vectorcraft_color::oklab::max_chroma(bl, bh); + let (stored, lowered) = vectorcraft_color::oklab::from_oklch(bl, 0.29, bh); + let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(lowered && blue_max > 0.3); + assert_eq!(oklch_track([bl, 0.29, bh], Some(blue_max)), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); + assert_eq!(oklch_track([bl, blue_max, bh], Some(blue_max)).a(), 255, "blue itself is inside sRGB"); assert!((chroma_tick(max) - (max / 0.4) as f32).abs() < 1e-6 && chroma_tick(max) > 0.1 && chroma_tick(max) < 1.0); assert_eq!((chroma_tick(0.0), chroma_tick(0.5)), (0.0, 1.0)); } @@ -792,16 +801,17 @@ fn oklch_sliders_need_srgb_as_the_working_space() { move |ui, app: &mut VectorcraftApp| { let tgt = super::color::wheel_target(app, ui); let color = tgt.color(); - let _ = oklch_rows(app, ui, &tgt, color, &p3); + let picked = oklch_rows(app, ui, &tgt, color, &p3); + assert!(picked.is_none(), "a gray row picks nothing: {picked:?}"); }, app(json!("#ff0000")), ); h.run_steps(2); assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); - let undo = undo_len(h.state()); let rail = oklch_slider(&h, "Lightness").rect(); click(&mut h, on_rail(rail, 0.2), Modifiers::NONE); - assert_eq!(undo_len(h.state()), undo, "a gray row picks nothing"); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + set_slider_value(&mut h, "Lightness", 20.0); } /// The rows show what they asked for while the color displays as it did, and the color's own @@ -1024,3 +1034,60 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(e, "`sliders` must be none, oklch or hsl"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); } + +/// A hue given to a Gray color does not change how it displays, so its paint stays a Gray color +/// and no undo step is recorded; the hue row keeps the hue. +#[test] +fn a_hue_on_a_gray_color_leaves_its_paint_gray() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut app = app(json!({"gray": 0.5})); + app.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut h = oklch_harness_shown(app); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + assert!(matches!(gray, Color::Gray { .. }), "{gray:?}"); + set_slider_value(&mut h, hue, 200.0); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(200.0), "{rows}"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "{rows}: the Gray fill stays as it was"); + } +} + +/// The hue given to a gray is dropped once the panel shows another color, so the same gray applied +/// again later shows its own hue, 0°. +#[test] +fn a_remembered_hue_is_dropped_after_the_paint_changes() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut app = app(json!("#808080")); + app.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut h = oklch_harness_shown(app); + set_slider_value(&mut h, hue, 240.0); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(240.0), "{rows}"); + h.state_mut().run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + h.run_steps(2); + h.state_mut().run("paint.setFill", json!({"color": "#808080"})).unwrap(); + h.run_steps(2); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(0.0), "{rows}: the gray's own hue"); + } +} + +/// Hiding the rows, or showing the other rows, during a drag on a row keeps the color the drag +/// previewed as one undo step and leaves no interaction open. +#[test] +fn hiding_the_rows_during_a_drag_keeps_its_color_as_one_undo_step() { + for rows in ["none", "oklch"] { + let mut h = hsl_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "HSL Lightness").rect(); + let undo = undo_len(h.state()); + press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE); + for _ in 0..2 { + h.event(Event::PointerMoved(on_rail(rail, 0.25))); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "{rows}: the drag previews"); + let previewed = fill(h.state()); + h.state_mut().run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + h.run_steps(2); + press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE); + assert!(!h.state().session.in_interaction(), "{rows}: the interaction ended"); + assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1), "{rows}"); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index deefa7751f..8b29059609 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -270,8 +270,8 @@ pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint. `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, sliders?}` shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, and shows OKLCH Sliders, HSL -Sliders or neither (`sliders: "oklch"`, `"hsl"` or `"none"`; `"oklch"` is an error while the working RGB space is not -sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. +Sliders or neither (`sliders: "oklch"`, `"hsl"` or `"none"`; `"oklch"` is an error while the active document's RGB +space, its assigned profile or else the working RGB space, is not sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, diff --git a/docs/mcp.md b/docs/mcp.md index 0d68533e69..36c37613b7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -677,11 +677,13 @@ the list return an error and change nothing. The command returns `{view, channel kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or -the box), and `"none"` hides them; `"oklch"` is an error while the working RGB space is not sRGB. +the box), and `"none"` hides them in any RGB space. `"oklch"` is an error while the active document's RGB space is +not sRGB: the profile assigned to the document when it has one, else the working RGB space of Edit › Color Settings. `ui.colorWheel {"sliders": "hsl"}` shows HSL Sliders in their place: H, S and L rows with the hue (0 to 360°), saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color 4's `hsl()` defines them. -`color.convert {"to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. A color outside sRGB -(a Lab or CMYK color, or an RGB color in a wider working RGB space) is clipped to sRGB first. +`color.convert {"color": "#ff0000", "to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. +A color outside sRGB (a Lab or CMYK color, an RGB color in a wider RGB space, or RGB numbers past 0 to 1) is clipped +to sRGB first. 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e0401e8fe9..43ee1da4de 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1819,7 +1819,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. - - **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. + - **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. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, 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. - **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. - **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 1ea9a2775adbed14b8e58a7d4d6167d78dcca533 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:01:23 -0800 Subject: [PATCH 20/51] Three-Point Arc: save the direction option, fix two placement cases - `tool.setOption` (and the Tool Options dialog) now accepts `direction` as true or false and refuses other values or unknown options. - The first press counts as a drag when the pointer moves 2 pt from where it was pressed, not from the point it snapped to. - `]` pressed while the third point is held down places that point as the new mode keeps it. --- crates/engine/src/tests/three_point_arc.rs | 20 ++++++++++++ crates/tools/src/three_point_arc.rs | 31 +++++++++++++----- crates/tools/src/three_point_arc/tests.rs | 38 ++++++++++++++++++++++ 3 files changed, 81 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs index 8a7a349220..ebd755dda7 100644 --- a/crates/engine/src/tests/three_point_arc.rs +++ b/crates/engine/src/tests/three_point_arc.rs @@ -198,3 +198,23 @@ fn three_clicks_with_the_tool_draw_the_arc() { let id = *s.doc().unwrap().selection.objects.first().unwrap(); assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9); } + +/// `tool.setOption` (the Tool Options dialog's Save) sets the tool's `direction` option, and +/// refuses a value that is not true or false, or an option the tool doesn't have. +#[test] +fn set_option_sets_the_direction_and_refuses_bad_values() { + let mut s = session(); + for on in [true, false] { + let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"direction": on}})).unwrap(); + assert_eq!(set["direction"], json!(on)); + assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(on)); + } + let cases = [ + (json!({"tool": "threePointArc", "key": "direction", "value": "yes"}), "tool `threePointArc`: `direction` must be true or false"), + (json!({"tool": "threePointArc", "key": "bogus", "value": true}), "tool `threePointArc`: unknown option `bogus`"), + ]; + for (p, want) in cases { + assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); + } + assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false)); +} diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index c25a3dca05..2732836dc1 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -38,8 +38,9 @@ pub const TOO_LARGE: &str = "Arc too large"; /// The press in progress. #[derive(Clone, Copy, Debug, PartialEq)] enum Press { - /// The first end, pressed at `at`: a release after a drag places the second end there. - Start { at: Point, dragged: bool }, + /// The first end, placed at `at` by a press at `from` (before snapping): a release after a + /// drag places the second end there. The drag is measured from `from`. + Start { at: Point, from: Point, dragged: bool }, /// The second end, pressed after a click placed the first: the release places it. End, /// The third point, pressed once both ends are placed: the release draws the arc. @@ -112,8 +113,8 @@ impl ThreePointArcTool { let moved = self.raw.is_none_or(|(p, _)| p != ev.pos); self.raw = Some((ev.pos, ev.mods)); match &mut self.press { - Some(Press::Start { at, dragged }) => { - *dragged |= moved && ev.pos.distance(*at) >= cx.tol(DRAG_PX); + Some(Press::Start { at, from, dragged }) => { + *dragged |= moved && ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); } @@ -157,7 +158,7 @@ impl Tool for ThreePointArcTool { (None, _) => { let at = self.snap.press(cx, ev.pos, &[], None); self.start = Some(at); - self.press = Some(Press::Start { at, dragged: false }); + self.press = Some(Press::Start { at, from: ev.pos, dragged: false }); self.pointer = Some(at); } (Some(a), None) => { @@ -189,7 +190,7 @@ impl Tool for ThreePointArcTool { self.follow(cx, ev); } match (self.press.take(), self.start, self.pointer) { - (Some(Press::Start { at, dragged: true }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), + (Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), (Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b), (Some(Press::Third), Some(a), Some(c)) => { let Some(b) = self.end else { return vec![] }; @@ -212,10 +213,16 @@ impl Tool for ThreePointArcTool { } } - fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { ToolKey::Escape => self.clear(), - ToolKey::BracketRight if self.start.is_some() => self.direction = !self.direction, + ToolKey::BracketRight if self.start.is_some() => { + self.direction = !self.direction; + // A press in progress: the point being placed keeps to the new mode. + if let (Some(_), Some((p, mods))) = (self.press, self.raw) { + self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)); + } + } _ => {} } vec![] @@ -305,6 +312,14 @@ impl Tool for ThreePointArcTool { self.direction = on; } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "direction" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index d7c35ddc8b..2481de1bff 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -188,6 +188,44 @@ fn the_direction_option_takes_a_bool() { assert_eq!(t.options(), json!({ "direction": false })); } +/// `]` pressed while the third point is held down places the point as the new mode keeps it: the +/// point Shift kept on the direction line goes back to where the pointer is, and the other way. +#[test] +fn bracket_during_a_press_places_the_third_point_in_the_new_mode() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift)), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0))); + // Through mode first, switched to direction mode during the press: Shift keeps the line upright. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift)); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9) && params["at"] == "start", "{params}"); +} + +/// With Snap to Point, a first press that snaps to the rectangle's corner, 1.5 pt from the +/// pointer, and moves 1.9 pt before it is let go is a click: the drag is measured from the press, +/// not from the corner, so only the first end is placed. +#[test] +fn a_short_move_from_a_snapped_press_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snap_to_point: true, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, (201.5, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (203.4, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, (203.4, 200.0), Mods::default())); + assert_eq!((t.start, t.end), (Some(Point::new(200.0, 200.0)), None)); +} + /// A release away from the last drag event places the point where the pointer is let go, for /// the second end and for the third point. #[test] From db71faca9a51bb917e60ffe363a0a9d990cf716b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:03:40 -0800 Subject: [PATCH 21/51] Brushes: test Artistic tints and list the library in the progress docs The Artistic test now draws each brush with a red stroke and checks that every path takes the stroke color. A second check covers a loaded library named Artistic Brushes: the name selects the built-in library, as for every built-in name, and the loaded library's id still selects it. docs/mcp.md now describes that rule, says that the exact id `artistic` selects the built-in library and that `Artistic` selects it only when no library has that name, and counts thirteen built-in libraries. The G5 entry, the UI brush-library row, the M10 row and the area rows list Artistic Brushes with thirteen libraries. --- crates/engine/src/tests/brushlib.rs | 18 ++++++++++++++++++ docs/gaps.md | 6 +++--- docs/mcp.md | 8 +++++--- docs/roadmap.md | 2 +- docs/target-app-parity.md | 8 ++++---- docs/ui-parity.md | 2 +- 6 files changed, 32 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index c741b1824f..39c48c9b88 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -212,12 +212,24 @@ fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() { let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"]; assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0); for b in &lib.brushes { let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) }; assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name); for path in [line_to(180.0), line_to(1.0)] { assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name); } + // The art is black, so with Tints every path takes the stroke color itself. + let mut fills = vec![]; + for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) { + piece.walk(&mut |n| { + if n.path_data().is_some() { + fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb())); + } + }); + } + let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5); + assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name); let before = undo_len(&s); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]})); assert_eq!(strs(&added["added"]), [b.name.as_str()]); @@ -242,6 +254,12 @@ fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() { assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id); assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id); assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works"); + // A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id. + let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"})); + assert_eq!(full["name"], "Artistic Brushes"); + let full_id = full["library"].as_str().unwrap(); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic"); + assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id); } /// Every path of brush art `n`: (anchors, opacity). diff --git a/docs/gaps.md b/docs/gaps.md index a8ba004253..4b94f27013 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -691,8 +691,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (twelve original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one - bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (thirteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one + bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes), Arrows (Solid, Open, Double, Chevron and Dashed Arrow) and Artistic Brushes (Orbit Lines, Petal Garland, Lattice Braid and Facet Sweep); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and @@ -714,7 +714,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Fine Grain, Canvas Weave, Burlap Sack, Cracked Glaze, Mosaic Floor, Quilted Squares, Leaded Glass and Damp Paper, painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the thirteen shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 3–13 h (estimated). diff --git a/docs/mcp.md b/docs/mcp.md index 7e2008a1cb..34eb007dbc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5478,13 +5478,15 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: twelve generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle +Brush libraries are read-only sets of brushes: thirteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`, and Artistic Brushes with four original vector art brushes, id `artistic`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and -`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). The -built-in Artistic Brushes library also accepts `Artistic` as a lookup name. +`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). A name +that a built-in library and a User Defined or loaded library share selects the built-in one; select the other by its +`user/…` or `loaded/…` id. The exact id `artistic` selects the built-in Artistic Brushes library, and `Artistic` +selects it too when no library is named `Artistic`. `brush.addFromLibrary {library, name? | names?}` copies brushes into the document's Brushes as one undo step (no names: the whole library), with the resources their art uses: patterns, symbols, swatches (`swatchConflict` as for `edit.paste`), graphic styles and images. Brushes the document already has (same name and definition) are reported diff --git a/docs/roadmap.md b/docs/roadmap.md index 4e23db3070..55b10d7565 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -176,7 +176,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, twelve generated libraries including Tech Circuit, Arrows, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, thirteen generated libraries including Tech Circuit, Arrows, Artistic Brushes, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1d8737d55f..b6a216b636 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -267,7 +267,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (twelve generated libraries including Tech Circuit, Arrows, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (thirteen generated libraries including Tech Circuit, Arrows, Artistic Brushes, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -539,7 +539,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (twelve generated in code including Tech Circuit, Arrows, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (thirteen generated in code including Tech Circuit, Arrows, Artistic Brushes, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -591,7 +591,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries twelve (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries thirteen (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows, Artistic Brushes) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -1186,7 +1186,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - - **Artistic Brushes library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Artistic Brushes offers Orbit Lines, Petal Garland, Lattice Braid and Facet Sweep; commands also accept Artistic as a lookup name. Each is original, editable vector artwork stretched along a path by an art brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `artistic_library_strokes_are_editable_and_reopen_from_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers drawing on short and long paths, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. + - **Artistic Brushes library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Artistic Brushes offers Orbit Lines, Petal Garland, Lattice Braid and Facet Sweep; the exact id `artistic` selects it, and commands accept Artistic as a lookup name for it when no library is named Artistic. Each is original, editable vector artwork stretched along a path by an art brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `artistic_library_strokes_are_editable_and_reopen_from_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers drawing on short and long paths, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. - **Pressure Sensitive library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Pressure Sensitive offers Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow. The first two are art brushes whose width follows recorded pen pressure; the other two are calligraphic nibs whose size follows it. They use the engine's existing pressure input where the device and platform deliver it, and a neutral width for a mouse path. These presets and names are VectorCraft's own. Evidence: `pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` checks light and heavy pressure, short and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Arrows library:** Window › Brush Libraries › Arrows holds five art brushes, each 100 pt long: Solid Arrow, Open Arrow (an outlined head), Double Arrow (a head at each end), Chevron Arrow (a second chevron on the shaft) and Dashed Arrow (five separate dashes and a head). Each brush stretches only the part between its guides, so the shaft follows the path's length and the heads keep their proportions, with Tints colorization. The brushes, their names and their art are VectorCraft's own, generated in code (`brush.libraries`, `brush.addFromLibrary`; `arrows_library_lists_renders_and_applies_original_brushes`, `dashed_arrow_keeps_separate_dashes_and_survives_library_save`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 64e6be0b94..960540bfb2 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -472,7 +472,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; twelve built-in libraries (original, generated in code) | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows, Artistic Brushes, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; thirteen built-in libraries (original, generated in code) | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | From 5fe226850d121d75067d466fd2e4284ca4ba6e27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:21:28 -0800 Subject: [PATCH 22/51] Color Wheel: keep the OKLCH chroma search below the asked chroma The first chroma search in largest_fitting_chroma ran from 0 to 0.5 and could land on the line from black to blue above the chroma asked for. The result then fell back to the asked chroma, which lies outside sRGB, and from_oklch clipped it, changing the lightness and hue. The search now stops at the asked chroma, so the chroma it finds always fits. The parity doc now says color.convert's OKLCH matches the rows only for a color inside sRGB, since it clips the display RGB first. --- crates/color/src/oklab.rs | 17 +++++++++++++++-- docs/target-app-parity.md | 2 +- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 018df4526d..1df3c4b1df 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -51,8 +51,8 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 { return 0.0; } let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h)); - // The edge of the chromas from 0 that sRGB holds without a break. - let (mut lo, mut hi) = (0.0, 0.5); + // An edge of the chromas sRGB holds, searched no higher than `limit`, so `lo` always fits. + let (mut lo, mut hi) = (0.0, limit.min(0.5)); for _ in 0..40 { let mid = (lo + hi) / 2.0; if fits(mid) { lo = mid } else { hi = mid } @@ -201,6 +201,19 @@ mod tests { assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h)); } + /// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a + /// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color + /// inside sRGB with the lightness and hue asked for. + #[test] + fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() { + let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]); + let l = bl * 0.3125 / bc; + let (rgb, lowered) = from_oklch(l, 0.29, h); + let [gl, gc, gh] = to_oklch(rgb); + assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}"); + assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}"); + } + /// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's /// extended sRGB does, in both directions. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ec41d91518..4a69666192 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1879,7 +1879,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. - - **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. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, 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. + - **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. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. 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. - **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. - **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 197f3ed64540f865d62209e5e4394a28780f76a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:36:41 -0800 Subject: [PATCH 23/51] Symbols: a click just outside New Symbol or Delete Symbol reads its own modifiers egui counts a release within its interact radius of a button as a click on it. The panel's buttons now read Shift and Alt from such a release too, and skip a release that ends a drag, which egui does not count as a click. --- crates/ui-egui/src/panels/symbols.rs | 107 +++++++++++++++++++++++---- 1 file changed, 93 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index a94ce33be1..204b0742c2 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -459,7 +459,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. // Both are read as the button went up on it. - let m = modifiers_released_in(ui, new.rect); + let m = modifiers_released_in(ui, new.interact_rect); let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; if m.shift { p["keepArt"] = json!(true); @@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let picked = if marked.contains(&name) { &marked[..] } else { &[] }; delete(app, picked, Some(&name), alt_at_release(ui)); } else if trash.clicked() { - delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.rect).alt); + delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.interact_rect).alt); } }); } @@ -604,21 +604,42 @@ fn alt_at_release(ui: &Ui) -> bool { modifiers_at_release(ui).alt } -/// The modifiers held for a click on `rect`: when the primary button last went up over `rect` in -/// this frame, as it went up (egui reports the click of the last release in the frame), else now, -/// as for a click from the keyboard or a screen reader. +/// The modifiers held for a click on the widget whose interact rectangle is `rect`: when the +/// primary button last went up in this frame as a click (the pointer stayed within egui's click +/// distance of where the button went down) over `rect` or within egui's interact radius of it +/// (egui counts a release that close as a click on the widget), as it went up (egui reports the +/// click of the last such release in the frame), else now, as for a click from the keyboard or a +/// screen reader. A release that ends a drag is not a click and is skipped. fn modifiers_released_in(ui: &Ui, rect: egui::Rect) -> egui::Modifiers { + let radius = ui.ctx().global_style().interaction.interact_radius; + let max_click_dist = ui.ctx().options(|o| o.input_options.max_click_dist); ui.input(|i| { - i.events - .iter() - .rev() - .find_map(|e| match e { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } if rect.contains(*pos) => { - Some(*modifiers) + // Where the button went down in this frame, and whether the pointer has since moved too far + // for a click; a press in an earlier frame is taken as the start of a click. + let mut origin: Option = None; + let mut moved = false; + let mut found = None; + for e in &i.events { + match e { + egui::Event::PointerMoved(pos) => { + moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist); } - _ => None, - }) - .unwrap_or(i.modifiers) + egui::Event::PointerButton { pos, pressed: true, .. } => { + origin = Some(*pos); + moved = false; + } + egui::Event::PointerButton { pos, button, pressed: false, modifiers } => { + moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist); + if *button == egui::PointerButton::Primary && !moved && rect.distance_sq_to_pos(*pos) <= radius * radius { + found = Some(*modifiers); + } + origin = None; + moved = false; + } + _ => {} + } + } + found.unwrap_or(i.modifiers) }) } @@ -1266,6 +1287,64 @@ mod tests { assert_eq!(symbols(&mut app), ["Leaf", "New Symbol", "New Symbol 2"]); } + /// A click just outside New Symbol, which egui still counts as a click on it, reads Shift and + /// Alt as the primary button goes up there, though they are let go later in the same frame. + #[test] + fn a_click_just_outside_new_symbol_reads_the_modifiers_as_the_button_goes_up() { + let (mut app, _) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let modifiers = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + let out = frame_held(&ctx, &mut app, vec![], modifiers); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let b = nodes + .iter() + .find(|(_, n)| n.label().is_some_and(|l| l.trim() == "New Symbol")) + .and_then(|(_, n)| n.bounds()) + .expect("a New Symbol button"); + let at = pos2(b.x0 as f32 - 2.0, ((b.y0 + b.y1) / 2.0) as f32); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + let events = vec![egui::Event::PointerMoved(at), press(true), press(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; + frame_held(&ctx, &mut app, events, modifiers); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + } + + /// An Alt-click on Delete Symbol followed in the same frame by a drag that ends just outside + /// it without Alt reads Alt from the click: the release that ends the drag is not a click. + #[test] + fn a_drag_ending_near_delete_symbol_after_an_alt_click_keeps_the_click_modifiers() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let b = nodes + .iter() + .find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")) + .and_then(|(_, n)| n.bounds()) + .expect("a Delete Symbol button"); + let center = pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let near = pos2(b.x0 as f32 - 1.0, center.y); + let from = pos2(near.x, near.y - 12.0); + let button = |pos, pressed, modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + let (alt, none) = (egui::Modifiers::ALT, egui::Modifiers::NONE); + let events = vec![ + egui::Event::PointerMoved(center), + button(center, true, alt), + button(center, false, alt), + egui::Event::ModifiersChanged(none), + egui::Event::PointerMoved(from), + button(from, true, none), + egui::Event::PointerMoved(near), + button(near, false, none), + ]; + frame_held(&ctx, &mut app, events, alt); + assert_eq!(dialog_kind(&app), None, "Alt deletes the unused symbol without asking"); + assert_eq!(symbols(&mut app), ["Leaf"]); + } + /// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol. #[test] fn symbol_options_checks_keep_art() { From bd54c2a63bcafd15c03fa4c0d4dbb13d5250fe64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:37:07 -0800 Subject: [PATCH 24/51] Three-Point Arc: measure the arc's curve, not its handles, against the canvas An arc near the canvas edge whose handles reach past it while the curve stays inside showed "Arc too large", though shape.threePointArc draws it. The tool now measures the curve's bounds, as the document's range check does for such a path. --- crates/tools/src/three_point_arc.rs | 5 ++++- crates/tools/src/three_point_arc/tests.rs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 2732836dc1..4145c549e7 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -73,7 +73,10 @@ pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: b (true, false) => CircularArc::leaving(start, third - start, end).map(|arc| (arc, arc.to_path())), (true, true) => CircularArc::arriving(start, end, end - third).map(|arc| (arc, arc.to_path())), }?; - let on_canvas = path.anchors().all(|(_, _, a)| [a.p, a.h_in, a.h_out].iter().all(|q| q.x.abs() <= MAX_COORD && q.y.abs() <= MAX_COORD)); + // The curve is measured, not its handles, which can reach past the canvas while the curve stays + // inside, as the document's own range check measures a path. + let inside = |x: f64, y: f64| x.abs() <= MAX_COORD && y.abs() <= MAX_COORD; + let on_canvas = path.bounds().is_some_and(|r| inside(r.x0, r.y0) && inside(r.x1, r.y1)); on_canvas.then_some((arc, path)) } diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index 2481de1bff..70f1f51e69 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -115,6 +115,25 @@ fn a_third_point_in_line_with_the_ends_draws_nothing() { assert_eq!(click(&mut t, &cx, (340.0, 340.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 340.0))); } +/// An arc near the canvas edge fits while its curve stays inside, even where a handle reaches past +/// the edge, and gives no arc once the curve reaches past it. +#[test] +fn an_arc_near_the_canvas_edge_is_measured_by_its_curve() { + // A 60° arc of radius 1000 whose rightmost point is `edge`: the handles at its ends reach about + // 45 pt further right. + let arc = |edge: f64| { + let (r, c) = (1000.0, edge - 1000.0); + let (dx, dy) = (r * 30f64.to_radians().cos(), r * 30f64.to_radians().sin()); + let start = Point::new(c + dx, -dy); + let end = Point::new(c + dx, dy); + arc_of(start, end, start + Vec2::new(0.5, 3f64.sqrt() / 2.0) * 100.0, true, false) + }; + let Some((_, path)) = arc(MAX_COORD - 1.0) else { panic!("an arc inside the canvas fits") }; + assert!(path.control_bounds().is_some_and(|r| r.x1 > MAX_COORD), "a handle reaches past the edge"); + assert!(path.bounds().is_some_and(|r| r.x1 <= MAX_COORD && (r.x1 - (MAX_COORD - 1.0)).abs() < 1e-6)); + assert!(arc(MAX_COORD + 1.0).is_none(), "an arc reaching past the canvas does not fit"); +} + /// In direction mode, Shift keeps the direction line at 45° steps from the end it starts at. #[test] fn shift_keeps_the_direction_at_45_degree_steps() { From 3d5a6c3c01f46e3f4dd2f2a27a056e5432206932 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:47:52 -0800 Subject: [PATCH 25/51] Three-Point Arc: `]` while hovering moves the shown third point to the new mode With both ends placed and Shift held, switching modes with `]` left the point the tool showed where the old mode put it until the pointer moved, while a click there drew the arc of the new mode. --- crates/tools/src/three_point_arc.rs | 14 +++++++--- crates/tools/src/three_point_arc/tests.rs | 31 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs index 4145c549e7..60314cbe1f 100644 --- a/crates/tools/src/three_point_arc.rs +++ b/crates/tools/src/three_point_arc.rs @@ -59,7 +59,8 @@ pub struct ThreePointArcTool { pointer: Option, /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. at_end: bool, - /// Where the pressed pointer was at its last event, before snapping, and the keys held then. + /// Where the pointer was at its last event, pressed or hovering, before snapping, and the keys + /// held then. raw: Option<(Point, Mods)>, } @@ -150,6 +151,7 @@ impl Tool for ThreePointArcTool { } match ev.kind { PointerKind::Move => { + self.raw = Some((ev.pos, ev.mods)); let leave = self.leave(cx, ev.mods); self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref())); vec![] @@ -222,8 +224,14 @@ impl Tool for ThreePointArcTool { ToolKey::BracketRight if self.start.is_some() => { self.direction = !self.direction; // A press in progress: the point being placed keeps to the new mode. - if let (Some(_), Some((p, mods))) = (self.press, self.raw) { - self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)); + // A hovering pointer: the third point it shows keeps to the new mode too. + match (self.press, self.raw) { + (Some(_), Some((p, mods))) => self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)), + (None, Some((p, mods))) if self.end.is_some() && self.pointer.is_some() => { + let leave = self.leave(cx, mods); + self.pointer = Some(self.snap.hover(cx, p, &[], leave.as_ref())); + } + _ => {} } } _ => {} diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs index 70f1f51e69..eaf269e974 100644 --- a/crates/tools/src/three_point_arc/tests.rs +++ b/crates/tools/src/three_point_arc/tests.rs @@ -230,6 +230,37 @@ fn bracket_during_a_press_places_the_third_point_in_the_new_mode() { assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9) && params["at"] == "start", "{params}"); } +/// `]` pressed while the pointer hovers moves the third point the tool shows to where the new mode +/// keeps it, so the arc shown is the arc a click there draws. +#[test] +fn bracket_while_hovering_shows_the_third_point_in_the_new_mode() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + hover(&mut t, &cx, (303.0, 250.0), shift); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + // The direction line from the first end: Shift keeps it upright. + let start = Point::new(300.0, 300.0); + let line = t.overlays(&cx).into_iter().find_map(|o| match o { + Overlay::Line { a, b, dashed: false, .. } if a == start => Some(b), + _ => None, + }); + assert!(line.is_some_and(|b| (b.x - 300.0).abs() < 1e-9), "{line:?}"); + let acts = click_with(&mut t, &cx, (303.0, 250.0), shift); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}"); + // Back to through mode while hovering: the point goes back to the pointer. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + hover(&mut t, &cx, (303.0, 250.0), shift); + assert!(t.pointer.is_some_and(|q| (q.x - 300.0).abs() < 1e-9), "{:?}", t.pointer); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.pointer, Some(Point::new(303.0, 250.0))); + assert_eq!(click_with(&mut t, &cx, (303.0, 250.0), shift), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0))); +} + /// With Snap to Point, a first press that snaps to the rectangle's corner, 1.5 pt from the /// pointer, and moves 1.9 pt before it is let go is a click: the drag is measured from the press, /// not from the corner, so only the first end is placed. From c5863cd11ab20f48f012d92c0d4b67afd46aa73a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:25:09 -0800 Subject: [PATCH 26/51] Docs: radius preview of the Three-Point Arc tool needs Measurement Labels The tool shows the radius by the pointer only with Measurement Labels on. The progress lines in docs/target-app-parity.md, docs/ui-parity.md and ROADMAP.md now say so. --- ROADMAP.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ecc21a96fe..fed8d57326 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -156,7 +156,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. -- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b411cc405e..52e802d906 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -716,7 +716,7 @@ since 2026-10-01. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. -- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc, its center and its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. +- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc and its center, and with Measurement Labels on its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index cddc571578..d74a5f8edb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -337,7 +337,7 @@ tools, never checked side by side) isn't captured row by row. | Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 | | Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | | Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | -| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | +| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | ## Modifier keys and temporary tools From 9ff55c19c63b4125655840b9081e6e56c3d19821 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 22:52:01 -0800 Subject: [PATCH 27/51] Part of #5941: drop-down lists show every option when the window has room A drop-down list stopped at the room on one side of its field, so a window with room for the whole list still cut it short: the Export As Format list showed 18 of its 20 formats at 1280x900 and 17 at 1000x856. The list now opens in a popup of its own. It opens below its field when it fits there, above it when it fits there instead, and otherwise moves up from below into the window, over its field. A list taller than the window scrolls, and the current option still opens in view. The field is drawn in the same look, with the same tooltip for a value cut short and the same role for screen readers. --- crates/ui-egui/src/dialogs/tests_export.rs | 113 ++++++++++++++-- crates/ui-egui/src/widgets.rs | 2 + crates/ui-egui/src/widgets/dropdowns.rs | 150 ++++++++++++++++++--- crates/ui-egui/src/widgets/look_tests.rs | 87 +++++++++++- 4 files changed, 316 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index c0eccbc56d..51258fbfa9 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -259,11 +259,12 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format _ => {} } } - let labels: Vec<&str> = export_as::formats().iter().map(|f| f.label).collect(); // A built-in format six from the end of the built-in ones: out of view when the list opens at // its top, and far enough from the end that a plug-in format another test adds after the - // built-in ones does not move the rows shown around it. + // built-in ones does not move the rows shown around it. The window is short enough that the + // list centered on it stops short of its end. let built_in: Vec<_> = fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect(); + let labels: Vec<&str> = built_in.iter().map(|f| f.label).collect(); let chosen = built_in.len().checked_sub(6).and_then(|i| built_in.get(i)).copied().expect("Export As lists formats"); let (mut app, _) = app(1); app.run("file.exportAs", json!({"format": chosen.id})).unwrap(); @@ -272,31 +273,38 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format theme::apply(&ctx, Default::default()); // Every scroll area takes the bar at rest from the theme, whatever style the list sets itself. assert_eq!(ctx.global_style().spacing.scroll, crate::widgets::list_scroll_style()); - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 480.0))); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 280.0))); let mut time = 0.0; + let popup = std::cell::RefCell::new(vec![]); + // The texts and bars painted on the open list (without the dialog under it), and every text. let mut run = |app: &mut VectorcraftApp, events: Vec| { time += 0.25; - let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| show(app, ui.ctx())); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| { + show(app, ui.ctx()); + popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); + }); out.textures_delta.clear(); - let (mut texts, mut bars) = (vec![], vec![]); - out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); - (texts, bars) + let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); + popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); + (texts, bars, all) }; let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); run(&mut app, vec![away.clone()]); - let (texts, _) = run(&mut app, vec![]); + let (_, _, texts) = run(&mut app, vec![]); let field = texts.iter().find(|(s, ..)| s == chosen.label).map(|(_, r, _)| r.center()).expect("the Format field shows the chosen format"); let click_at = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; // Opens the list, moves the pointer away and returns the list's rect, the format names drawn in // it with their clip rects, and the bars drawn. - type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec) -> (Vec<(String, egui::Rect, egui::Rect)>, Vec) + 'r; + type Texts = Vec<(String, egui::Rect, egui::Rect)>; + type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec) -> (Texts, Vec, Texts) + 'r; let open = |run: &mut Run<'_>, app: &mut VectorcraftApp| { run(app, vec![egui::Event::PointerMoved(field), click_at(field, true)]); run(app, vec![click_at(field, false)]); run(app, vec![away.clone()]); let (mut texts, mut bars) = (vec![], vec![]); for _ in 0..4 { - (texts, bars) = run(app, vec![]); + (texts, bars, _) = run(app, vec![]); } let list = ctx .memory(|m| { @@ -334,11 +342,13 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format run(&mut app, vec![wheel]); let mut scrolled = vec![]; for _ in 0..4 { - (scrolled, _) = run(&mut app, vec![]); + (scrolled, ..) = run(&mut app, vec![]); } let scrolled: Vec<_> = scrolled.into_iter().filter(|(s, r, _)| labels.contains(&s.as_str()) && list.contains_rect(*r)).collect(); - run(&mut app, vec![egui::Event::PointerMoved(field), click_at(field, true)]); - run(&mut app, vec![click_at(field, false)]); + // Escape closes it: a list taller than the room beside its field covers the field. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + run(&mut app, vec![escape(true)]); + run(&mut app, vec![escape(false)]); let (_, reopened, _) = open(&mut run, &mut app); if rows.len() < labels.len() { assert_ne!(tops(&scrolled), tops(&rows), "the wheel scrolled the list"); @@ -347,6 +357,83 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format assert!(whole(&reopened, chosen.label), "the chosen format shows whole: {:?}", tops(&reopened)); } +/// #5941: the Format list stopped at the room on one side of its field, so a window with room for +/// every format still cut the list short. In windows of 1280×900 and 1000×856 the list shows every +/// built-in format whole, the greyed-out DWG row after them included, inside the window, without a +/// scroll bar. A plug-in format that another test adds or removes meanwhile is not counted. +#[test] +fn the_format_list_shows_every_format_when_the_window_has_room() { + fn walk(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>, bars: &mut Vec) { + match shape { + egui::Shape::Text(t) => texts.push((t.galley.text().into(), t.visual_bounding_rect(), clip)), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, texts, bars)), + _ => {} + } + } + let labels: Vec<&str> = + fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).map(|f| f.label).chain(["DWG (use DXF)"]).collect(); + for (width, height) in [(1280.0, 900.0), (1000.0, 856.0)] { + let case = format!("{width}×{height}"); + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + let mut time = 0.0; + let popup = std::cell::RefCell::new(vec![]); + // The texts and bars painted on the open list (without the dialog under it), and every text. + let mut run = |app: &mut VectorcraftApp, events: Vec| { + time += 0.25; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }, |ui| { + show(app, ui.ctx()); + popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); + }); + out.textures_delta.clear(); + let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); + popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); + (texts, bars, all) + }; + let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); + run(&mut app, vec![away.clone()]); + let (_, _, all) = run(&mut app, vec![]); + let field = all.iter().find(|(s, ..)| s == "PNG").map(|(_, r, _)| r.center()).expect("the Format field shows PNG"); + let click = |pressed| egui::Event::PointerButton { pos: field, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(field), click(true)]); + run(&mut app, vec![click(false)]); + run(&mut app, vec![away.clone()]); + let list_rect = || { + ctx.memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + }; + // A plug-in format that another test installs or removes changes the list's height, and the + // list is placed for its new height on the pass after. Read it once it keeps its rect. + let (mut texts, mut bars, mut list) = (vec![], vec![], None); + for _ in 0..12 { + (texts, bars, _) = run(&mut app, vec![]); + let now = list_rect(); + if now.is_some() && now == list { + break; + } + list = now; + } + let list = list.expect("the Format list is open"); + assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window"); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every format shows whole in {list:?}"); + assert!(bars.is_empty(), "{case}: a list that shows every format draws no scroll bar: {bars:?}"); + } +} + #[test] fn svg_continues_in_svg_options() { let (mut app, written) = app(2); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d6a0f7c50e..0187050f75 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -49,6 +49,8 @@ pub use drag::{ }; #[cfg(test)] use dropdowns::combo_button_id; +#[cfg(test)] +pub(crate) use dropdowns::top_popup_shapes; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_icon_names, dropdown_icon_names_sized, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 50d99b81f8..2ea0f48276 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -149,9 +149,10 @@ fn option_row<'a>(ui: &mut Ui, enabled: bool, selected: bool, atoms: impl egui:: response } -/// The id [`craft_ui::ComboBox::from_id_salt`] gives its button in this `Ui`: `from_id_salt` -/// stores `IdSalt::new(salt)` and hashes it once more with the scope, so the app must hash `id` -/// the same way to read the button's focus and open state before it is drawn. +/// The id of the button of [`combo_atoms_named`] in this `Ui`, the one +/// [`craft_ui::ComboBox::from_id_salt`] gives its button: `from_id_salt` stores +/// `IdSalt::new(salt)` and hashes it once more with the scope. The app reads the button's focus and +/// open state with it before the button is drawn. pub(super) fn combo_button_id(ui: &Ui, id: &impl std::hash::Hash) -> egui::Id { ui.make_persistent_id(egui::IdSalt::new(HashOnly(id))) } @@ -206,9 +207,8 @@ fn combo_atoms_named<'a, R>( if opening { ui.data_mut(|d| d.insert_temp(opened_key, pass)); } - // The menu measures itself against the whole screen on the pass it opens and takes - // the room beside its field on the next one, so the current option is scrolled into - // view on both. + // The list is laid out unseen to measure it on the pass it opens and placed on the + // next one, so the current option is scrolled into view on both. let settling = ui.data(|d| d.get_temp::(opened_key)).is_some_and(|p| pass <= p + 1); // A list drawn inside this one's rows finds its own record, and this one's comes back after it. let outer = if settling { OPENING.replace(Some(Opening::default())) } else { OPENING.take() }; @@ -238,22 +238,14 @@ fn combo_atoms_named<'a, R>( chosen }; let enter_for_combo = ui.memory(|m| m.has_focus(button_id)) || craft_ui::ComboBox::is_open(ui.ctx(), button_id); - let max_height = (ui.ctx().content_rect().height() - MENU_GAP).max(ui.spacing().combo_height); - let response = craft_ui::ComboBox::from_id_salt(HashOnly(&id)) - .selected_text(current) - .width(width - 4.0) - .height(max_height) - .popup_style(egui::style::StyleModifier::new(|style| { - egui::containers::menu::menu_style(style); - style.spacing.scroll = list_scroll_style(); - })) - .show_ui(ui, list); + let response = combo_button(ui, button_id, current, width - 4.0); + let shown = combo_list(ui, &response, list); // The button or open list handles Enter before the modal can accept it. if enter_for_combo { ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); } - let _ = name_field(label_field(response.response.clone(), label), name); - let chosen = response.inner.flatten(); + let _ = name_field(label_field(response, label), name); + let chosen = shown.flatten(); // egui closes the list on a click of the pointer only: an option picked with Space or // Enter closes it here, and the combo gives the keyboard back, so that Enter reaches the // dialog's OK (#2789). @@ -266,6 +258,128 @@ fn combo_atoms_named<'a, R>( .inner } +/// The button of [`combo_atoms_named`] with the id `button_id`, at least `width` wide, showing +/// `current`: [`craft_ui::ComboBox`]'s button, with its look, its tooltip for a value cut short and +/// its role for screen readers. It is drawn here so that its list opens in [`combo_list`]. +fn combo_button<'a>(ui: &mut Ui, button_id: egui::Id, current: impl egui::IntoAtoms<'a>, width: f32) -> Response { + use egui::class::HasClasses as _; + use egui::{AtomExt as _, NumExt as _}; + let open = egui::Popup::is_id_open(ui.ctx(), button_id.with("popup")); + let mut classes = egui::class::Classes::default(); + classes.add_class(craft_ui::ComboBox::CLASS); + classes.set_class(craft_ui::ComboBox::CLASS_OPEN, open); + let egui::widget_style::ButtonStyle { atom_layout } = ui.widget_style(button_id, &classes); + let visuals = if open { + ui.visuals().widgets.open + } else if let Some(response) = ui.ctx().read_response(button_id) { + *ui.style().interact(&response) + } else { + ui.visuals().widgets.inactive + }; + let min_size = vec2(width, 0.0).at_least(atom_layout.min_size); + let current = current.into_atoms(); + let text = current.text().map(String::from).unwrap_or_default(); + let rtl = ui.style().right_to_left; + // The combo box's arrow: a downward triangle. + let arrow = egui::Atom::paint(Vec2::splat(ui.spacing().icon_width), move |ui, args| { + let rect = args.rect.expand(visuals.expansion); + let rect = Rect::from_center_size(rect.center(), vec2(rect.width() * 0.7, rect.height() * 0.45)); + ui.painter().add(egui::Shape::rotated_triangle(rect, 0.0, visuals.fg_stroke.color)); + }) + .atom_grow(true) + .atom_align(if rtl { egui::Align2::LEFT_CENTER } else { egui::Align2::RIGHT_CENTER }); + let button = atom_layout + .apply( + egui::WidgetAtom::new((current, arrow)) + .id(button_id) + .sense(Sense::click()) + .fallback_font(egui::TextStyle::Button) + .wrap_mode(ui.wrap_mode()) + .direction(if rtl { egui::Direction::RightToLeft } else { egui::Direction::LeftToRight }), + ) + .min_size(min_size) + .measure(ui, ui.available_size()); + let elided = button.container.iter_texts().any(|galley| galley.elided); + let response = button.allocate(ui).paint(ui).response; + // A value cut short shows in full on hover, as a truncated `Label`'s does. + let response = if elided { + response.on_hover_ui(|ui| { + ui.set_max_width(ui.spacing().tooltip_width); + ui.add(egui::Label::new(text.as_str()).wrap()); + }) + } else { + response + }; + response.widget_info(|| egui::WidgetInfo { + enabled: ui.is_enabled(), + current_text_value: Some(text.clone()), + ..egui::WidgetInfo::new(egui::Role::ComboBox) + }); + response +} + +/// The list of [`combo_atoms_named`] while it is open, drawn by `list` in a popup of its own that +/// opens from `button` and takes the whole list whenever the window has room for it (#5941): below +/// the button when it fits there, above it when it fits there instead, and otherwise shifted from +/// below into the window, over the button. A list taller than the window scrolls. Returns what +/// `list` returned, or `None` while the list is closed. +fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> Option { + let ctx = ui.ctx(); + let id = button.id.with("popup"); + let style = egui::style::StyleModifier::new(|style| { + egui::containers::menu::menu_style(style); + style.spacing.scroll = list_scroll_style(); + }); + let popup = + egui::Popup::menu(button).id(id).width(button.rect.width()).style(style.clone()).close_behavior(egui::PopupCloseBehavior::CloseOnClick); + let screen = ctx.content_rect(); + // The room on each side of the rect the popup opens from: the part of the button in view. + let anchor = popup.get_anchor_rect().unwrap_or(button.rect); + let below = screen.bottom() - anchor.bottom(); + let above = anchor.top() - screen.top(); + // The list's size from its last pass: egui lays a popup out unseen on the pass it opens, so the + // list is measured before it is placed. A right-to-left layout lines the list up with the + // button's right edge, as egui's menus do. + let rtl = ctx.global_style().right_to_left; + let align = match popup.get_expected_size() { + Some(size) if size.y > below && size.y <= above => { + if rtl { + egui::RectAlign::TOP_END + } else { + egui::RectAlign::TOP_START + } + } + // egui keeps a popup inside the window, so a list too tall for either side moves up. + _ if rtl => egui::RectAlign::BOTTOM_END, + _ => egui::RectAlign::BOTTOM_START, + }; + let mut popup_style = (*ctx.global_style()).clone(); + style.apply(&mut popup_style); + let frame = egui::Frame::popup(&popup_style).total_margin().sum().y; + let height = (screen.height() - frame).max(ui.spacing().interact_size.y); + let shown = popup.align(align).align_alternatives(&[]).show(|ui| { + ui.set_min_width(ui.available_width()); + // A popup offers its contents the height it had on its last pass; the list is offered the + // window's instead. + ui.set_max_height(height); + // Labels widen a narrow list rather than wrap, as in egui's combo box. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + egui::ScrollArea::vertical().max_height(height).show(ui, list).inner + }); + if shown.is_some() { + ctx.accesskit_node_builder(id, |node| node.set_role(egui::Role::ListBox)); + } + shown.map(|r| r.inner) +} + +/// The shapes painted so far in this pass on the topmost popup that was shown in the last one, such +/// as an open dropdown list, without what lies under it. Read at the end of a test's UI. +#[cfg(test)] +pub(crate) fn top_popup_shapes(ctx: &egui::Context) -> Vec { + let top = ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last()); + top.map_or_else(Vec::new, |layer| ctx.graphics(|g| g.get(layer).map(|p| p.all_entries().cloned().collect()).unwrap_or_default())) +} + /// The recessed combo box of [`dropdown`] showing `current`, whose menu keeps a search field and /// filters in place over a list that scrolls (the font menu and the shortcut import's target /// picker, #555). `menu` shows the menu with one of [`craft_ui::combo::Menu`]'s header forms and diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 47d8e41a91..13ee6ebd58 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -133,10 +133,13 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() { for (height, above, current) in [(260.0, 117.0, 19), (260.0, 117.0, 10), (180.0, 77.0, 10), (180.0, 77.0, 3)] { let ctx = themed(Default::default()); let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); let mut add = |ui: &mut Ui| { ui.add_space(above); field.set(ui.horizontal(|ui| dropdown_names(ui, "short-list", labels[current], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); }; + // The shapes of the open list, without the field under it. let mut run = |time: f64, events: Vec| { let raw = egui::RawInput { time: Some(time), @@ -146,7 +149,7 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() { }; let mut out = ctx.run_ui(raw, &mut add); out.textures_delta.clear(); - out.shapes + popup.take() }; run(0.0, vec![]); let at = field.get().center(); @@ -206,6 +209,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { let ctx = themed(Default::default()); let field = std::cell::Cell::new(Rect::NOTHING); let current = std::cell::RefCell::new(String::from("Row 00")); + let popup = std::cell::RefCell::new(vec![]); let mut add = |ui: &mut Ui| { ui.add_space(above); let shown = current.borrow().clone(); @@ -224,8 +228,10 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { current.replace(items[i].clone()); } field.set(r.response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); }; let mut time = 0.0; + // The shapes of the open list, without the field under it. let mut run = |events: Vec| { time += 0.1; let raw = egui::RawInput { @@ -236,7 +242,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { }; let mut out = ctx.run_ui(raw, &mut add); out.textures_delta.clear(); - out.shapes + popup.take() }; // The rows that show whole, with their tops: inside the open list and the clip they are painted // in. @@ -298,10 +304,12 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { } let scrolled = rows(clipped); assert!(has(&scrolled, row), "{case}: the wheel scrolls {row} into view: {scrolled:?}"); - // Closed and opened again twice: each time its rows are where they were when it closed. + // Closed and opened again twice: each time its rows are where they were when it closed. Escape + // closes it: a list taller than the room beside its field covers the field. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; for time in ["first", "second"] { - run(vec![egui::Event::PointerMoved(at), press(true)]); - run(vec![press(false)]); + run(vec![escape(true)]); + run(vec![escape(false)]); run(vec![]); let reopened = rows(open(&mut run)); assert_eq!(reopened, scrolled, "{case}: the list opens again where it was scrolled, the {time} time"); @@ -894,6 +902,75 @@ fn a_long_dropdown_uses_window_room_and_shows_its_scroll_bar_when_clipped() { assert!(has_scroll_bar, "the overflowing dropdown draws its scroll bar without hover in {popup:?}"); } +// #5941: a drop-down list stopped at the room on one side of its field, so a window with room for +// the whole list still cut it short. The list opens below its field when it fits there, above it +// when it fits there instead, and otherwise moves up from below into the window over its field; +// each time every option shows whole, inside the window. +#[test] +fn a_dropdown_list_shows_every_option_when_the_window_has_room() { + let items: Vec = (0..20).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + // (window height, space above the field, where the list goes) + for (height, above, side) in [(700.0, 16.0, "below"), (700.0, 650.0, "above"), (640.0, 300.0, "over")] { + let case = format!("{height} pt window, field {above} pt down"); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(above); + field.set(ui.horizontal(|ui| dropdown_names(ui, "fit-list", labels[0], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, height)); + // The shapes of the open list, without the field under it. + let mut run = |time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + popup.take() + }; + run(0.0, vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(0.1, vec![egui::Event::PointerMoved(at), press(true)]); + run(0.2, vec![press(false)]); + run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = run(f64::from(i) * 0.1, vec![]); + } + let list = ctx + .memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + .expect("the list is open"); + assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window"); + let field = field.get(); + // The list opens from the button, 1 pt inside the field's border. + match side { + "below" => assert!(list.top() >= field.bottom() - 1.5, "{case}: the list {list:?} opens below the field {field:?}"), + "above" => assert!(list.bottom() <= field.top() + 1.5, "{case}: the list {list:?} opens above the field {field:?}"), + _ => assert!(list.top() < field.bottom() && list.bottom() > field.top(), "{case}: the list {list:?} covers the field {field:?}"), + } + let mut texts = vec![]; + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)), + _ => {} + } + } + clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts)); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}"); + } +} + /// Enter on text that reads as no number in a range field refuses it as a unit field does: the /// field flashes and an open dialog is not confirmed with the old value. #[test] From 57b4575bfd856b0372fa75350799ba243ba09831 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 22:56:11 -0800 Subject: [PATCH 28/51] Contextual Task Bar: choose which actions it shows The bar's More Options menu has Bar Actions, which lists the actions and the Fill, Stroke, Recolor Artwork, Lock or Shape Properties chips the bar offers for the current selection or tool, each checked while it is on. A click turns one off or on. An action that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. Reset Bar Actions turns every one on again. The type font controls are not in Bar Actions. The choice is kept with the preferences and with the workspace, as the Control bar's option groups are, and ids the bar does not have are dropped when they are read. Both items are commands: window.taskBar.actions {action, visible?} and window.taskBar.resetActions, documented in docs/mcp.md. --- crates/mcp/src/ui_catalog.rs | 12 + crates/ui-egui/src/canvas.rs | 3 +- crates/ui-egui/src/canvas/task_bar.rs | 131 +++++++- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/menus/run.rs | 20 ++ crates/ui-egui/src/menus/state.rs | 4 + crates/ui-egui/src/menus/ui_commands.rs | 12 + crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/tests/taskbar.rs | 400 ++++++++++++++++++++++++ crates/ui-egui/src/workspaces.rs | 44 +++ docs/mcp.md | 18 ++ docs/target-app-parity.md | 1 + 39 files changed, 704 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 88f60fd6c8..bfe50afa36 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -675,6 +675,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state", ), ("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"), + ( + "window.taskBar.actions", + "Bar Actions", + "", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true or false, is an error and changes nothing; returns {action, visible}", + ), + ( + "window.taskBar.resetActions", + "Reset Bar Actions", + "", + "{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again", + ), ( "window.dock", "Panels", diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 02833a7c09..316681b493 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -72,8 +72,9 @@ pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; pub use selection_marks::SelectionMarks; use task_bar::task_bar; +pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, is_task_bar_action, read_hidden_task_bar_actions}; #[cfg(test)] -pub(crate) use task_bar::{chip_paints, images_with_other_art}; +pub(crate) use task_bar::{chip_paints, images_with_other_art, task_bar_offered}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index c133c003f8..7ba9ee4e94 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -19,6 +19,13 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) } +/// The actions the Contextual Task Bar offered when it was last drawn, before Bar Actions left any +/// out: each one's name and its id in [`TASK_BAR_ACTIONS`] (none: Bar Actions cannot turn it off). +#[cfg(test)] +pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(String, Option<&'static str>)> { + ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default()) +} + /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { @@ -182,7 +189,9 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// On a blank canvas, a document with no artwork and a selection tool in use, it sits under the /// active artboard and offers Draw (Pencil) and Place Image. /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the -/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). +/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). More Options › Bar Actions +/// turns each action and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); +/// the bar leaves out the ones that are off, and Reset Bar Actions shows them all again. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let t = Tokens::get(ui.ctx()); let on_artboards = app.session.tool_id() == "artboard"; @@ -351,6 +360,17 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let paints = chip_paints(app, ui.ctx()); let colored = has_colors(&st.doc, &st.selection.objects); let doc = st.uid; + // Every action and chip the bar offers here, with its name, for More Options › Bar Actions; + // the ones that are off there are left out of the bar. + let hidden = &app.ui.task_bar_hidden_actions; + #[cfg(test)] + ui.ctx().data_mut(|d| { + let ids: Vec<(String, Option<&'static str>)> = + items.iter().map(|(label, _, cmd, params)| (label.to_string(), action_id(cmd, params))).collect(); + d.insert_temp(task_bar_id().with("offered"), ids); + }); + let mut offered: Vec<(&str, &'static str)> = items.iter().filter_map(|(label, _, cmd, params)| Some((*label, action_id(cmd, params)?))).collect(); + items.retain(|(_, _, cmd, params)| action_id(cmd, params).is_none_or(|a| !hidden.contains(a))); let bounds = xf.rect.shrink(8.0); // The canvas's width less the frame's margins and stroke. let room = bounds.width() - BAR_FRAME; @@ -371,6 +391,10 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .into_iter() .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); + offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), c.id(shape.is_some())))); + let chips: Vec = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect(); + let offered: Vec<(&str, &str, bool)> = offered.into_iter().map(|(label, action)| (label, action, !hidden.contains(action))).collect(); + let any_hidden = !hidden.is_empty(); let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); let fidelity = app.session.tool_options()["fidelity"].as_f64(); let font_w = fonts.then(|| { @@ -498,6 +522,20 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((cmd, json!({}))); } } + // The actions and chips the bar offers for this selection or tool, each + // checked while it shows, which turns it on or off; then Reset Bar + // Actions, which shows every action again. + ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { + ui.set_min_width(170.0); + for (label, action, shown) in &offered { + if widgets::menu_item_name(ui, label.trim_end_matches([':', '…']), true, *shown) { + run = Some(("window.taskBar.actions", json!({ "action": action }))); + } + } + }); + if widgets::menu_item(ui, tl!("Reset Bar Actions"), any_hidden, false) { + run = Some(("window.taskBar.resetActions", json!({}))); + } ui.separator(); if widgets::menu_item(ui, tl!("Show Properties Panel"), true, false) { run = Some(("window.panel", json!({"panel": "properties"}))); @@ -579,6 +617,97 @@ impl Chip { Chip::Recolor | Chip::Lock => 30.0, } } + + /// The chip's id in [`TASK_BAR_CHIPS`]; Lock is `shapeProperties` while it shows a basic + /// `shape`'s properties. + fn id(self, shape: bool) -> &'static str { + match self { + Chip::Fill => "fill", + Chip::Stroke => "stroke", + Chip::Recolor => "recolor", + Chip::Lock if shape => "shapeProperties", + Chip::Lock => "lock", + } + } + + /// The chip's name in More Options › Bar Actions, translated. + fn label(self, shape: bool) -> &'static str { + match self { + Chip::Fill => tl!("Fill"), + Chip::Stroke => tl!("Stroke"), + Chip::Recolor => tl!("Recolor Artwork"), + Chip::Lock if shape => tl!("Shape Properties"), + Chip::Lock => tl!("Lock"), + } + } +} + +/// The Contextual Task Bar's actions that More Options › Bar Actions turns on or off +/// (`window.taskBar.actions {action, visible?}`): each action's id, the command its button runs and +/// the `tool` that command names, if any. An action that is off stays out of the bar, and More +/// Options does not list it either; turning one off changes only the bar. Every action starts on. +pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 37] = [ + ("imageTrace", TASK_BAR_IMAGE_TRACE, None), + ("cropImage", "ui.cropImage", None), + ("removeBackground", crate::addons::image::REMOVE_BACKGROUND, None), + ("removeAnchorPoints", "path.removeAnchors", None), + ("join", "path.join", None), + ("cutPath", "path.cutAtAnchors", None), + ("convertToCorner", TASK_BAR_TO_CORNER, None), + ("convertToSmooth", TASK_BAR_TO_SMOOTH, None), + ("group", "object.group", None), + ("makeClippingMask", "object.clippingMask.make", None), + ("unite", "object.pathfinder.unite", None), + ("expand", "imageTrace.expand", None), + ("editClippingPath", "object.clippingMask.editMask", None), + ("releaseClippingMask", "object.clippingMask.release", None), + ("ungroup", "object.ungroup", None), + ("isolate", "object.isolate", None), + ("editPath", "tool.select", Some("directSelection")), + ("releaseCompoundPath", "object.compoundPath.release", None), + ("createOutlines", "type.createOutlines", None), + ("convertToPointType", "type.convertToPointType", None), + ("convertToAreaType", "type.convertToAreaType", None), + ("typeOnPathOptions", "type.pathOptions", None), + ("centerOnTop", "type.pathCenter.top", None), + ("centerOnBottom", "type.pathCenter.bottom", None), + ("dynamicText", "type.dynamicText", None), + ("offsetPath", "object.path.offsetPath", None), + ("simplify", "object.path.simplify", None), + ("smooth", "object.path.smooth", None), + ("duplicate", "edit.duplicate", None), + ("drawPencil", "tool.select", Some("pencil")), + ("placeImage", "file.place", None), + ("fidelity", TASK_BAR_FIDELITY, None), + ("smoothToolOptions", "tool.options", Some("smooth")), + ("resizeArtboard", TASK_BAR_ARTBOARD_OPTIONS, None), + ("duplicateArtboards", TASK_BAR_DUPLICATE_ARTBOARDS, None), + ("rearrangeArtboards", TASK_BAR_REARRANGE_ARTBOARDS, None), + ("exportArtboards", "file.exportForScreens", None), +]; + +/// The ids of the Contextual Task Bar's chips that More Options › Bar Actions turns on or off, +/// as [`TASK_BAR_ACTIONS`] are. +pub(crate) const TASK_BAR_CHIPS: [&str; 5] = ["fill", "stroke", "recolor", "lock", "shapeProperties"]; + +/// Whether `id` names one of the Contextual Task Bar's actions or chips. +pub(crate) fn is_task_bar_action(id: &str) -> bool { + TASK_BAR_ACTIONS.iter().any(|a| a.0 == id) || TASK_BAR_CHIPS.contains(&id) +} + +/// The id in [`TASK_BAR_ACTIONS`] of the bar's item that runs `cmd` with `params`. +fn action_id(cmd: &str, params: &serde_json::Value) -> Option<&'static str> { + let tool = params.get("tool").and_then(serde_json::Value::as_str); + TASK_BAR_ACTIONS.iter().find(|(_, c, t)| *c == cmd && *t == tool).map(|a| a.0) +} + +/// Reads the Contextual Task Bar's actions and chips that are off, as kept in the preferences. Ids +/// the bar does not have are dropped, and a value that is not a list of strings reads as none off, +/// so the bar shows every action. +pub(crate) fn read_hidden_task_bar_actions<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let value = ::deserialize(d)?; + let ids = value.as_array().into_iter().flatten().filter_map(serde_json::Value::as_str); + Ok(ids.filter(|id| is_task_bar_action(id)).map(str::to_string).collect()) } /// What a click on one of the bar's [`Chip`]s does: make the Fill (`true`) or the Stroke active and diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d371a5f1e4..d1ace795df 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -621,6 +621,8 @@ font-technology Variable Променливи Contextual Task Bar Контекстна лента със задачи Pin Bar Position Закачане на позицията на лентата Reset Bar Position Нулиране на позицията на лентата + Bar Actions Действия на лентата + Reset Bar Actions Нулиране на действията на лентата Resize Преоразмеряване Contrast Контраст Control Контрол diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 00d07d469d..3abddd15e2 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -770,6 +770,8 @@ Contextual Task Bar Kontekstna traka zadataka Pin Bar Position Položaj prikvačene trake Reset Bar Position Vrati položaj trake na početno + Bar Actions Radnje trake + Reset Bar Actions Vrati radnje trake na početno Resize Promijeni veličinu Tools Alati Toolbars Trake s alatima diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 78e5a77c9e..e28998b70c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3851,6 +3851,8 @@ digits Malayalam Malaiàlam Reset all Revolve settings to their defaults. Restableix tots els paràmetres de revolució als valors predeterminats. Reset Automation Restableix Automation Reset Bar Position Restableix la posició de la barra + Bar Actions Accions de la barra + Reset Bar Actions Restableix les accions de la barra Reset Bounding Box Restableix el quadre delimitador Rotate Bounding Box Gira el quadre delimitador Rotate Bounding Box… Gira el quadre delimitador… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bd3e76ec50..0cc88d36f1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -784,6 +784,8 @@ Contextual Task Bar Kontextový panel úloh Pin Bar Position Připnout polohu panelu Reset Bar Position Obnovit polohu panelu + Bar Actions Akce panelu + Reset Bar Actions Obnovit akce panelu Resize Změnit velikost Tools Nástroje Toolbars Panely nástrojů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3fb128a27a..69444597f8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3460,6 +3460,8 @@ liquify-list-end {0}, {1} {0} og {1} Contextual Task Bar Kontekstuel opgavelinje Pin Bar Position Fastgør linjens placering Reset Bar Position Nulstil linjens placering + Bar Actions Linjens handlinger + Reset Bar Actions Nulstil linjens handlinger Tools Værktøjer Toolbars Værktøjslinjer Advanced Avanceret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6ad4e3850b..1967a59a56 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -625,6 +625,8 @@ font-technology Variable Variabel Contextual Task Bar Kontextbezogene Taskleiste Pin Bar Position Position der Leiste fixieren Reset Bar Position Position der Leiste zurücksetzen + Bar Actions Aktionen der Leiste + Reset Bar Actions Aktionen der Leiste zurücksetzen Resize Größe ändern Contrast Kontrast Control Steuerung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7d2e5b6363..48acabe1c9 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -599,6 +599,8 @@ font-technology Variable Μεταβλητές Contextual Task Bar Γραμμή εργασιών βάσει περιβάλλοντος Pin Bar Position Σταθεροποίηση θέσης γραμμής Reset Bar Position Επαναφορά θέσης γραμμής + Bar Actions Ενέργειες γραμμής + Reset Bar Actions Επαναφορά ενεργειών γραμμής Resize Αλλαγή μεγέθους Contrast Αντίθεση Control Έλεγχος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 30678f8a13..70bbddbe01 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -645,6 +645,8 @@ font-technology Variable Variables Contextual Task Bar Barra de tareas contextual Pin Bar Position Fijar posición de la barra Reset Bar Position Restablecer posición de la barra + Bar Actions Acciones de la barra + Reset Bar Actions Restablecer acciones de la barra Resize Cambiar tamaño Contrast Contraste Control Control diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 873d339833..a1a70c7203 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -770,6 +770,8 @@ Contextual Task Bar Kontekstuaalinen tehtäväpalkki Pin Bar Position Kiinnitä palkin sijainti Reset Bar Position Palauta palkin sijainti + Bar Actions Palkin toiminnot + Reset Bar Actions Palauta palkin toiminnot Resize Muuta kokoa Tools Työkalut Toolbars Työkalurivit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 68bcc455b2..189bb24de4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -646,6 +646,8 @@ font-technology Variable Variables Contextual Task Bar Barre des tâches contextuelle Pin Bar Position Épingler la position de la barre Reset Bar Position Réinitialiser la position de la barre + Bar Actions Actions de la barre + Reset Bar Actions Réinitialiser les actions de la barre Resize Redimensionner Contrast Contraste Control Contrôle diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index d7bb081e02..f364d97341 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3176,6 +3176,8 @@ Reselect ફરી પસંદ કરો Reset રીસેટ કરો Reset Bar Position બાર સ્થિતિ રીસેટ કરો + Bar Actions બાર ક્રિયાઓ + Reset Bar Actions બાર ક્રિયાઓ રીસેટ કરો Reset Bounding Box બાઉન્ડિંગ બોક્સ રીસેટ કરો Rotate Bounding Box બાઉન્ડિંગ બોક્સ ફેરવો Rotate Bounding Box… બાઉન્ડિંગ બોક્સ ફેરવો… diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2837a15b67..94b241788b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4471,6 +4471,8 @@ antiAlias Sharp शार्प Reset all Revolve settings to their defaults. सभी रिवॉल्व सेटिंग्स डिफ़ॉल्ट पर रीसेट करें। Reset Automation स्वचालन रीसेट करें Reset Bar Position बार स्थिति रीसेट करें + Bar Actions बार क्रियाएँ + Reset Bar Actions बार क्रियाएँ रीसेट करें Reset Bounding Box बाउंडिंग बॉक्स रीसेट करें Rotate Bounding Box बाउंडिंग बॉक्स घुमाएँ Rotate Bounding Box… बाउंडिंग बॉक्स घुमाएँ… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fbc2e30bd1..053f0acb61 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3689,6 +3689,8 @@ mark-style Japanese Japán Reset all Revolve settings to their defaults. A tengely körüli forgatás minden beállítását visszaállítja az alapértékre. Reset Automation Automation visszaállítása Reset Bar Position Sáv helyének visszaállítása + Bar Actions Sáv műveletei + Reset Bar Actions Sáv műveleteinek visszaállítása Reset Bounding Box Befoglaló keret visszaállítása Rotate Bounding Box Befoglaló keret elforgatása Rotate Bounding Box… Befoglaló keret elforgatása… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ab48475d3d..cbb7589e81 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -724,6 +724,8 @@ Contextual Task Bar Bilah tugas kontekstual Pin Bar Position Sematkan posisi bilah Reset Bar Position Atur ulang posisi bilah + Bar Actions Tindakan bilah + Reset Bar Actions Atur ulang tindakan bilah Tools Alat Toolbars Bilah alat Advanced Lanjutan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a3b493cd1d..17865eea45 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -647,6 +647,8 @@ font-technology Variable Variabili Contextual Task Bar Barra attività contestuale Pin Bar Position Fissa posizione barra Reset Bar Position Ripristina posizione barra + Bar Actions Azioni barra + Reset Bar Actions Ripristina azioni barra Resize Ridimensiona Contrast Contrasto Control Controllo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5de0cae50c..57825abf41 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -812,6 +812,8 @@ digits Malayalam マラヤーラム数字 Contextual Task Bar コンテキストタスクバー Pin Bar Position バーの位置を固定 Reset Bar Position バーの位置をリセット + Bar Actions バーのアクション + Reset Bar Actions バーのアクションをリセット Resize サイズを変更 Tools ツール Toolbars ツールバー diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 81fc06870d..ca35eff072 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2894,6 +2894,8 @@ Contextual Task Bar კონტექსტური ამოცანების ზოლი Pin Bar Position ზოლის პოზიციის ჩამაგრება Reset Bar Position ზოლის პოზიციის ჩამოყრა + Bar Actions ზოლის მოქმედებები + Reset Bar Actions ზოლის მოქმედებების ჩამოყრა Tools ხელსაწყოები Toolbars ხელსაწყოთა ზოლები Advanced დამატებითი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4a6963bbd2..a4ea3eaed4 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -805,6 +805,8 @@ digits Malayalam 말라얄람어 Contextual Task Bar 상황별 작업 표시줄 Pin Bar Position 표시줄 위치 고정 Reset Bar Position 표시줄 위치 재설정 + Bar Actions 표시줄 동작 + Reset Bar Actions 표시줄 동작 재설정 Resize 크기 조절 Tools 도구 Toolbars 도구 모음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 894c7096f6..1bc48d5c19 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1329,6 +1329,8 @@ liquify-list-end {0}, {1} {0} en {1} Contextual Task Bar Contextuele taakbalk Pin Bar Position Balkpositie vastzetten Reset Bar Position Balkpositie herstellen + Bar Actions Balkacties + Reset Bar Actions Balkacties herstellen Tools Gereedschappen Toolbars Werkbalken Advanced Geavanceerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c69ed2cf28..dda7e753d1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -733,6 +733,8 @@ Contextual Task Bar Kontekstowy pasek zadań Pin Bar Position Przypnij położenie paska Reset Bar Position Resetuj położenie paska + Bar Actions Akcje paska + Reset Bar Actions Resetuj akcje paska Resize Zmień rozmiar Tools Narzędzia Toolbars Paski narzędzi diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6bae5e26f1..a3eed4d6f3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -590,6 +590,8 @@ antiAlias Sharp Nítido Contextual Task Bar Barra de Tarefas Contextual Pin Bar Position Fixar Posição da Barra Reset Bar Position Redefinir Posição da Barra + Bar Actions Ações da Barra + Reset Bar Actions Redefinir Ações da Barra Resize Redimensionar Control Controle Convert Converter diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 74156da429..161dca94f7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -643,6 +643,8 @@ font-technology Variable Вариативные Contextual Task Bar Контекстная панель задач Pin Bar Position Закрепить положение панели Reset Bar Position Сбросить положение панели + Bar Actions Действия панели + Reset Bar Actions Сбросить действия панели Resize Изменить размер Contrast Контраст Control Control diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4d683cb1ea..4aad71069a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -628,6 +628,8 @@ font-technology Variable Variabla Contextual Task Bar Kontextuellt aktivitetsfält Pin Bar Position Fäst fältets position Reset Bar Position Återställ fältets position + Bar Actions Fältets åtgärder + Reset Bar Actions Återställ fältets åtgärder Resize Ändra storlek Contrast Kontrast Control Kontroll diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d0e30b8fdc..d18c09be90 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -625,6 +625,8 @@ font-technology Variable Değişken Contextual Task Bar Bağlamsal Görev Çubuğu Pin Bar Position Pim Çubuğu Konumu Reset Bar Position Çubuk Konumunu Sıfırla + Bar Actions Çubuk Eylemleri + Reset Bar Actions Çubuk Eylemlerini Sıfırla Contrast Kontrast Control Kontrol Convert Dönüştür diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 82ba9af243..709f1b62e2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -641,6 +641,8 @@ font-technology Variable Варіативні Contextual Task Bar Контекстна панель завдань Pin Bar Position Закріпити положення панелі Reset Bar Position Скинути положення панелі + Bar Actions Дії панелі + Reset Bar Actions Скинути дії панелі Resize Змінити розмір Contrast Контраст Control Панель керування diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 04ebd9992d..6566a17dd3 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3470,6 +3470,8 @@ mark-style Japanese Kiểu Nhật Reset all 3D settings to their defaults. Đặt lại tất cả cài đặt 3D về mặc định. Reset all Revolve settings to their defaults. Đặt lại tất cả cài đặt Revolve về mặc định. Reset Bar Position Đặt lại vị trí thanh + Bar Actions Thao tác của thanh + Reset Bar Actions Đặt lại thao tác của thanh Reset Bounding Box Đặt lại hộp bao Rotate Bounding Box Xoay hộp bao Rotate Bounding Box… Xoay hộp bao… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d20ae8d9e8..0da7242432 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -592,6 +592,8 @@ antiAlias Sharp 锐利 Contextual Task Bar 上下文任务栏 Pin Bar Position 固定任务栏位置 Reset Bar Position 重置任务栏位置 + Bar Actions 任务栏操作 + Reset Bar Actions 重置任务栏操作 Resize 调整大小 Contrast 对比 Control 控制栏 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d5fde762f9..33a784ef89 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -609,6 +609,8 @@ font-technology Variable 可變 Contextual Task Bar 快捷工作列 Pin Bar Position 釘選工作列位置 Reset Bar Position 重設工作列位置 + Bar Actions 工作列動作 + Reset Bar Actions 重設工作列動作 Resize 調整大小 Contrast 對比 Control 控制 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 909d03b3d2..0fbc656746 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -639,6 +639,26 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option match (s("action").filter(|a| crate::canvas::is_task_bar_action(a)), opt_bool(p, "visible")) { + (None, _) => { + let ids = crate::canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(crate::canvas::TASK_BAR_CHIPS); + Err(format!("`action` must be one of {}", ids.collect::>().join(", "))) + } + (_, Err(e)) => Err(e), + (Some(action), Ok(visible)) => { + let hidden = &mut app.ui.task_bar_hidden_actions; + let visible = visible.unwrap_or_else(|| hidden.contains(&action)); + if visible { + hidden.remove(&action); + } else { + hidden.insert(action.clone()); + } + Ok(json!({ "action": action, "visible": visible })) + } + }, + // More Options › Reset Bar Actions: every action and chip shows again. + "window.taskBar.resetActions" => Ok(json!(std::mem::take(&mut app.ui.task_bar_hidden_actions))), "window.dock" => { let ui = &mut app.ui; // The bars the last Tab hid show again, unless the toolbar or the Control bar was shown diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index a424d98714..b9d1a5fa84 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -94,6 +94,10 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "window.taskBar" => app.ui.task_bar, "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, "window.taskBar.pin" => app.ui.task_bar_place.pinned, + "window.taskBar.actions" => p + .get("action") + .and_then(Value::as_str) + .is_some_and(|a| crate::canvas::is_task_bar_action(a) && !app.ui.task_bar_hidden_actions.contains(a)), "window.learn" => crate::panels::learn::visible(&app.ui), "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fbfd12b24e..0845f5f08b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -676,6 +676,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state", ), ("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"), + ( + "window.taskBar.actions", + "Bar Actions", + "", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true or false, is an error and changes nothing; returns {action, visible}", + ), + ( + "window.taskBar.resetActions", + "Reset Bar Actions", + "", + "{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again", + ), ( "window.dock", "Panels", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d2bc85ba9a..796dadb5c5 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -473,6 +473,10 @@ pub struct UiState { /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, + /// The Contextual Task Bar's actions (`canvas::TASK_BAR_ACTIONS`) that More Options › Bar + /// Actions has off (`window.taskBar.actions`); none: the bar shows every action it offers. + #[serde(deserialize_with = "crate::canvas::read_hidden_task_bar_actions")] + pub task_bar_hidden_actions: std::collections::BTreeSet, /// The Pathfinder panel's Shape Mode buttons make a compound shape on a click, and give the /// permanent Pathfinder result on Alt-click (off, the default: the other way round). #[serde(default)] @@ -1219,6 +1223,7 @@ impl Default for UiState { toolbar_advanced: false, task_bar: true, task_bar_place: TaskBarPlace::default(), + task_bar_hidden_actions: Default::default(), shape_modes_compound: false, context_locked: None, context_intertwine: None, diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index bc4734db5a..9b5ab37031 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1573,3 +1573,403 @@ fn the_task_bar_follows_edits_and_undo() { assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}"); assert!(!locked(&app, rect), "the button doesn't lock the shape"); } + +/// Turns the bar's action or chip `action` on or off (`window.taskBar.actions`). +fn show_action(app: &mut VectorcraftApp, action: &str, visible: bool) { + let r = app.run("window.taskBar.actions", json!({"action": action, "visible": visible})).unwrap(); + assert_eq!(r, json!({"action": action, "visible": visible})); +} + +/// An action turned off in Bar Actions leaves the bar for every selection that offers it, and its +/// Object menu command stays enabled. Toggled, it comes back. +#[test] +fn an_action_turned_off_leaves_the_bar_and_stays_in_its_menu() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path") && has(&texts, "Join"), "{texts:?}"); + show_action(&mut app, "offsetPath", false); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "offsetPath"})), Some(false)); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "join"})), Some(true)); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path"), "{texts:?}"); + assert!(has(&texts, "Join") && has(&texts, "Simplify") && has(&texts, "Edit Path"), "the other actions stay: {texts:?}"); + assert!(crate::menus::enabled(&app, "object.path.offsetPath"), "Object › Path › Offset Path… still runs"); + + // Another selection that offers the same action leaves it out too: a rectangle. + let rect = id(app.run("shape.rectangle", json!({"x": 220, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[rect]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path") && has(&texts, "Edit Path"), "{texts:?}"); + + // Toggled (no `visible`), it shows again. + assert_eq!(app.run("window.taskBar.actions", json!({"action": "offsetPath"})).unwrap(), json!({"action": "offsetPath", "visible": true})); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path"), "{texts:?}"); +} + +/// The Fill, Stroke, Recolor Artwork, Lock and Shape Properties chips each turn off on their own: +/// Lock off leaves a basic shape's Shape Properties, and Shape Properties off leaves Lock. +#[test] +fn a_chip_turned_off_leaves_the_bar() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 150, "x2": 200, "y2": 220})).unwrap()); + select(&mut app, &[rect]); + let names = |app: &mut VectorcraftApp| buttons(app).1.into_iter().map(|(n, _)| n).collect::>(); + let shown = names(&mut app); + for name in ["Fill", "Stroke", "Shape Properties"] { + assert!(shown.iter().any(|n| n == name), "{name}: {shown:?}"); + } + show_action(&mut app, "fill", false); + show_action(&mut app, "lock", false); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n == "Fill"), "{shown:?}"); + assert!(shown.iter().any(|n| n == "Stroke") && shown.iter().any(|n| n == "Shape Properties"), "{shown:?}"); + select(&mut app, &[line]); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n.starts_with("Lock")), "Lock is off: {shown:?}"); + show_action(&mut app, "lock", true); + show_action(&mut app, "shapeProperties", false); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n.starts_with("Lock")), "Lock is on again: {shown:?}"); + select(&mut app, &[rect]); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n == "Shape Properties"), "{shown:?}"); +} + +/// Reset Bar Actions shows every action and chip again and returns the ids it showed. +#[test] +fn reset_bar_actions_shows_every_action_again() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + show_action(&mut app, "simplify", false); + show_action(&mut app, "duplicate", false); + show_action(&mut app, "stroke", false); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Simplify") && !has(&texts, "Duplicate"), "{texts:?}"); + assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!(["duplicate", "simplify", "stroke"])); + assert!(app.ui.task_bar_hidden_actions.is_empty()); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Simplify") && has(&texts, "Duplicate"), "{texts:?}"); + assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!([]), "nothing left to show"); +} + +/// Each of the bar's actions and chips has its own id, and no two actions run the same command +/// with the same tool. +#[test] +fn bar_action_ids_are_distinct() { + let ids: Vec<&str> = canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(canvas::TASK_BAR_CHIPS).collect(); + let set: std::collections::BTreeSet<&str> = ids.iter().copied().collect(); + assert_eq!(set.len(), ids.len(), "{ids:?}"); + let runs: std::collections::BTreeSet<(&str, Option<&str>)> = canvas::TASK_BAR_ACTIONS.iter().map(|a| (a.1, a.2)).collect(); + assert_eq!(runs.len(), canvas::TASK_BAR_ACTIONS.len()); +} + +/// An action the bar does not have, a missing one, or a `visible` that is not true or false is an +/// error and changes nothing. +#[test] +fn bar_actions_refuse_bad_params() { + let mut app = app(); + show_action(&mut app, "group", false); + for p in [json!({"action": "teleport"}), json!({}), json!({"action": 3}), json!({"action": "unite", "visible": "yes"})] { + assert!(app.run("window.taskBar.actions", p.clone()).is_err(), "{p}"); + } + let err = app.run("window.taskBar.actions", json!({"action": "teleport"})).unwrap_err(); + assert!(err.contains("imageTrace") && err.contains("shapeProperties"), "{err}"); + assert_eq!(app.ui.task_bar_hidden_actions.iter().map(String::as_str).collect::>(), ["group"]); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "teleport"})), Some(false)); +} + +/// The actions that are off are kept with the preferences. Ids the bar does not have are dropped, +/// a value that is not a list turns none off, and older preferences without it show every action. +#[test] +fn bar_actions_are_kept_with_the_preferences() { + let mut app = app(); + show_action(&mut app, "unite", false); + show_action(&mut app, "recolor", false); + let mut prefs = serde_json::to_value(&app.ui).unwrap(); + let back: crate::state::UiState = serde_json::from_value(prefs.clone()).unwrap(); + let ids = |ui: &crate::state::UiState| ui.task_bar_hidden_actions.iter().cloned().collect::>(); + assert_eq!(ids(&back), ["recolor", "unite"]); + prefs["task_bar_hidden_actions"] = json!(["unite", "teleport", 7, "fill"]); + assert_eq!(ids(&serde_json::from_value(prefs.clone()).unwrap()), ["fill", "unite"], "ids the bar does not have are dropped"); + prefs["task_bar_hidden_actions"] = json!("unite"); + assert!(ids(&serde_json::from_value(prefs.clone()).unwrap()).is_empty(), "a value that is not a list turns none off"); + prefs.as_object_mut().unwrap().remove("task_bar_hidden_actions"); + assert!(ids(&serde_json::from_value(prefs).unwrap()).is_empty(), "older preferences show every action"); + app.run("window.taskBar.resetActions", json!({})).unwrap(); + assert_eq!(serde_json::to_value(&app.ui).unwrap()["task_bar_hidden_actions"], json!([]), "none off"); +} + +/// More Options › Bar Actions lists the actions and chips the bar offers for the selection, each +/// checked while it shows; a click turns one off, it is listed unchecked after that, and a click on +/// Reset Bar Actions shows it again. +#[test] +fn more_options_bar_actions_turns_an_action_off_and_on() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center(); + let (ctx, _) = bar(&mut app); + let click_at = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p)]); + frame(app, &ctx, vec![press(true)]); + frame(app, &ctx, vec![press(false)]); + frame(app, &ctx, vec![]) + }; + let texts = click_at(&mut app, more); + let item = at(&texts, " Bar Actions"); + frame(&mut app, &ctx, vec![Event::PointerMoved(item)]); + let texts = frame(&mut app, &ctx, vec![]); + for name in ["✓ Join", "✓ Edit Path", "✓ Offset Path", "✓ Simplify", "✓ Duplicate", "✓ Fill", "✓ Stroke", "✓ Lock"] { + assert!(has(&texts, name), "{name}: {texts:?}"); + } + assert!(has(&texts, " Reset Bar Actions"), "{texts:?}"); + let offset = at(&texts, "✓ Offset Path"); + // Along the submenu's row first, so the pointer stays over the menu on its way. + frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(offset.x, item.y))]); + click_at(&mut app, offset); + assert!(app.ui.task_bar_hidden_actions.contains("offsetPath"), "{:?}", app.ui.task_bar_hidden_actions); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path") && has(&texts, "Simplify"), "{texts:?}"); + + // Opened again, Bar Actions lists it unchecked; Reset Bar Actions turns it on. + let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center(); + let (ctx, _) = bar(&mut app); + let click_at = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p)]); + frame(app, &ctx, vec![press(true)]); + frame(app, &ctx, vec![press(false)]); + frame(app, &ctx, vec![]) + }; + let texts = click_at(&mut app, more); + let item = at(&texts, " Bar Actions"); + let reset = at(&texts, " Reset Bar Actions"); + frame(&mut app, &ctx, vec![Event::PointerMoved(item)]); + let texts = frame(&mut app, &ctx, vec![]); + assert!(has(&texts, " Offset Path") && has(&texts, "✓ Simplify"), "{texts:?}"); + // Back along the menu's column to Reset Bar Actions, closing the submenu on the way. + frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(item.x, reset.y))]); + click_at(&mut app, reset); + assert!(app.ui.task_bar_hidden_actions.is_empty(), "{:?}", app.ui.task_bar_hidden_actions); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path"), "{texts:?}"); +} + +/// On a canvas too short for every action, More Options lists the ones that don't fit; an action +/// turned off in Bar Actions is listed neither there nor on the bar, and the others still are. +#[test] +fn an_action_turned_off_is_not_listed_in_more_options() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap()); + select(&mut app, &[a, b]); + let size = vec2(160.0, 150.0); + // More Options' list, opened on a new context, and what the bar itself shows. + let listed = |app: &mut VectorcraftApp| { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (on_bar, r, _) = bar_texts_on_screen(app, &ctx, size, 3); + let more = r.min + vec2(9.0 + 4.0 + 6.0 + 15.0, 7.0 + 15.0); + let press = |pressed| Event::PointerButton { pos: more, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut texts = vec![]; + for events in [vec![Event::PointerMoved(more)], vec![press(true)], vec![press(false)], vec![]] { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + texts = shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()); + } + assert!(texts.iter().any(|(t, _)| t.trim() == "Hide Bar"), "More Options opens: {texts:?}"); + let names = |t: &[(String, Rect)]| t.iter().map(|(t, _)| t.trim().to_string()).collect::>(); + (names(&on_bar), names(&texts)) + }; + let (on_bar, menu) = listed(&mut app); + for label in ["Unite", "Duplicate"] { + assert!(!on_bar.iter().any(|t| t == label) && menu.iter().any(|t| t == label), "{label} in More Options: {menu:?}"); + } + show_action(&mut app, "unite", false); + let (on_bar, menu) = listed(&mut app); + assert!(!on_bar.iter().any(|t| t == "Unite") && !menu.iter().any(|t| t == "Unite"), "{on_bar:?} {menu:?}"); + assert!(on_bar.iter().chain(&menu).any(|t| t == "Duplicate"), "Duplicate is still offered: {on_bar:?} {menu:?}"); +} + +/// Every action the bar offers, for every kind of selection and tool, has an id in Bar Actions, +/// and with all of them turned off the bar shows none of them. That covers Connect and Join (both +/// `join`), the actions matched by the tool they switch to (`editPath`, `drawPencil`, +/// `smoothToolOptions`), the Smooth tool's Fidelity and the Artboard tool's actions. +#[test] +fn every_action_the_bar_offers_can_be_turned_off() { + let dir = crate::tests_folder::Folder::new("ui-taskbar-actions"); + let line = |app: &mut VectorcraftApp| { + id(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 150, "y": 80}, {"x": 250, "y": 200}]})).unwrap()) + }; + let two = |app: &mut VectorcraftApp| { + let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap()); + select(app, &[a, b]); + }; + type Setup<'a> = Box; + let cases: Vec<(&str, Setup, &[&str])> = vec![ + ( + "an open path", + Box::new(|app| { + let l = line(app); + select(app, &[l]); + }), + &["join", "editPath", "offsetPath", "simplify", "duplicate"], + ), + ( + "a path the Direct Selection tool selects whole", + Box::new(|app| { + let l = line(app); + select(app, &[l]); + app.run("tool.select", json!({"tool": "directSelection"})).unwrap(); + }), + &["join", "convertToCorner", "convertToSmooth", "simplify", "smooth", "duplicate"], + ), + ( + "anchors picked out", + Box::new(|app| { + let l = line(app); + app.run("tool.select", json!({"tool": "directSelection"})).unwrap(); + app.run("select.anchors", json!({"id": l, "anchors": [[0, 1]]})).unwrap(); + }), + &["removeAnchorPoints", "join", "cutPath", "convertToCorner", "convertToSmooth"], + ), + ("two paths", Box::new(|app| two(app)), &["group", "unite", "duplicate"]), + ( + "a group", + Box::new(|app| { + two(app); + app.run("object.group", json!({})).unwrap(); + }), + &["ungroup", "isolate", "duplicate"], + ), + ( + "a compound path", + Box::new(|app| { + two(app); + app.run("object.compoundPath.make", json!({})).unwrap(); + }), + &["editPath", "releaseCompoundPath", "duplicate"], + ), + ( + "a clipping group", + Box::new(|app| { + two(app); + let g = id(app.run("object.clippingMask.make", json!({})).unwrap()); + select(app, &[g]); + }), + &["editClippingPath", "releaseClippingMask", "duplicate"], + ), + ( + "point type", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + }), + &["createOutlines", "convertToAreaType"], + ), + ( + "area type", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + app.run("type.convertToAreaType", json!({})).unwrap(); + select(app, &[t]); + }), + &["createOutlines", "convertToPointType"], + ), + ( + "type on a closed path", + Box::new(|app| { + let circle = id(app.run("path.create", json!({"d": "M100 300 A100 100 0 1 1 300 300 A100 100 0 1 1 100 300 Z"})).unwrap()); + let t = id(app.run("text.createInPath", json!({"path": circle, "mode": "onPath", "text": "Round", "at": [90, 300]})).unwrap()); + select(app, &[t]); + }), + &["createOutlines", "typeOnPathOptions", "centerOnTop", "centerOnBottom"], + ), + ( + "an image", + Box::new(|app| { + place_image(app, &dir); + }), + &["imageTrace", "cropImage", "removeBackground", "duplicate"], + ), + ( + "an image with a path", + Box::new(|app| { + let img = place_image(app, &dir); + let r = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(app, &[img, r]); + }), + &["group", "makeClippingMask", "duplicate"], + ), + ( + "a blank canvas", + Box::new(|app| { + let board = app.session.active().unwrap().doc.artboards[0].rect; + bar(app); + let view = app.view_mut().unwrap(); + (view.center, view.zoom) = (board.center(), 0.5); + }), + &["drawPencil", "placeImage"], + ), + ( + "a shape tool after drawing", + Box::new(|app| { + drag_with(app, "rectangle", (60.0, 60.0), (120.0, 120.0)); + }), + &["editPath"], + ), + ( + "the Smooth tool", + Box::new(|app| { + let e = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap()); + select(app, &[e]); + app.run("tool.select", json!({"tool": "smooth"})).unwrap(); + }), + &["fidelity", "smoothToolOptions"], + ), + ( + "the Artboard tool", + Box::new(|app| { + app.run("artboard.new", json!({"x": 420, "y": 0, "width": 200, "height": 200})).unwrap(); + app.run("tool.select", json!({"tool": "artboard"})).unwrap(); + }), + &["resizeArtboard", "duplicateArtboards", "rearrangeArtboards", "exportArtboards"], + ), + ]; + for (case, setup, expected) in cases { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + setup(&mut app); + let (ctx, _) = bar(&mut app); + let offered = canvas::task_bar_offered(&ctx); + assert!(canvas::task_bar_rect(&ctx).is_some() && !offered.is_empty(), "{case}: the bar shows actions"); + for (label, action) in &offered { + assert!(action.is_some(), "{case}: {label} has no id in Bar Actions"); + } + let ids: Vec<&str> = offered.iter().filter_map(|(_, a)| *a).collect(); + for action in expected.iter() { + assert!(ids.contains(action), "{case}: {action} in {ids:?}"); + } + for action in &ids { + show_action(&mut app, action, false); + } + let (_, texts) = bar_texts(&mut app); + for (label, _) in &offered { + assert!(!has(&texts, label), "{case}: {label} is off: {texts:?}"); + } + } +} diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 886589b5f0..b7f16a1c48 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -40,6 +40,10 @@ pub struct Workspace { pub toolbar_double: bool, pub toolbar_advanced: bool, pub task_bar: bool, + /// The Contextual Task Bar's actions and chips its Bar Actions has off (built-in workspaces, and + /// workspaces saved without this field: none). + #[serde(skip_serializing_if = "std::collections::BTreeSet::is_empty", deserialize_with = "crate::canvas::read_hidden_task_bar_actions")] + pub task_bar_hidden_actions: std::collections::BTreeSet, pub dock: bool, pub dock_tab: DockTab, /// The dock's tabbed group is collapsed to icons (built-in workspaces: expanded). @@ -205,6 +209,7 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace { toolbar_double: ui.toolbar_double, toolbar_advanced: ui.toolbar_advanced, task_bar: ui.task_bar, + task_bar_hidden_actions: ui.task_bar_hidden_actions.clone(), dock: ui.dock, dock_tab: ui.dock_tab, dock_collapsed: ui.dock_collapsed, @@ -243,6 +248,7 @@ pub fn apply(ui: &mut UiState, w: &Workspace) { ui.toolbar_double = w.toolbar_double; ui.toolbar_advanced = w.toolbar_advanced; ui.task_bar = w.task_bar; + ui.task_bar_hidden_actions = w.task_bar_hidden_actions.clone(); ui.dock = w.dock; ui.tab_hid = None; ui.dock_tab = w.dock_tab; @@ -905,4 +911,42 @@ mod tests { let read: UiState = serde_json::from_value(prefs).unwrap(); assert!(read.control_bar_hidden_groups.is_empty(), "older preferences show every group"); } + + /// A workspace keeps the Contextual Task Bar's actions its Bar Actions has off: switching + /// brings each workspace's back, Reset turns a built-in workspace's on again, and they survive + /// the preferences' JSON. A workspace saved without them, or with ids the bar does not have, + /// shows every action, or the ones it names that the bar has. + #[test] + fn saved_workspaces_restore_the_task_bar_actions() { + let hidden = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::>(); + let mut ui = UiState { task_bar_hidden_actions: hidden(&["duplicate", "fill"]), ..Default::default() }; + save_as(&mut ui, "Lean").unwrap(); + switch(&mut ui, ESSENTIALS).unwrap(); + assert!(ui.task_bar_hidden_actions.is_empty(), "Essentials shows every action"); + ui.task_bar_hidden_actions = hidden(&["simplify"]); + switch(&mut ui, "Lean").unwrap(); + assert_eq!(ui.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "the saved workspace's actions"); + switch(&mut ui, ESSENTIALS).unwrap(); + assert_eq!(ui.task_bar_hidden_actions, hidden(&["simplify"]), "Essentials as it was left"); + reset(&mut ui); + assert!(ui.task_bar_hidden_actions.is_empty(), "Reset Essentials shows every action again"); + switch(&mut ui, "Lean").unwrap(); + let json = serde_json::to_value(&ui).unwrap(); + assert_eq!(json["custom_workspaces"][0]["taskBarHiddenActions"], serde_json::json!(["duplicate", "fill"])); + let back: UiState = serde_json::from_value(json).unwrap(); + assert_eq!(back.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept in the preferences"); + assert_eq!(back.custom_workspaces[0].task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept with the workspace"); + let mut old = serde_json::to_value(&back.custom_workspaces[0]).unwrap(); + assert!(old.as_object_mut().unwrap().remove("taskBarHiddenActions").is_some()); + let old: Workspace = serde_json::from_value(old).unwrap(); + apply(&mut ui, &old); + assert!(ui.task_bar_hidden_actions.is_empty(), "an older workspace shows every action"); + let mut prefs = serde_json::to_value(&back).unwrap(); + prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!(["fill", "teleport", 3]); + let read: UiState = serde_json::from_value(prefs.clone()).unwrap(); + assert_eq!(read.custom_workspaces[0].task_bar_hidden_actions, hidden(&["fill"]), "ids the bar does not have are dropped"); + prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!("fill"); + let read: UiState = serde_json::from_value(prefs).unwrap(); + assert!(read.custom_workspaces[0].task_bar_hidden_actions.is_empty(), "a value that is not a list shows every action"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 5bc273289c..b7cbb49c0f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8176,6 +8176,24 @@ is kept with the preferences and with the workspace; a workspace or preferences and a group id the bar does not have is dropped when they are read. Another `group`, or none, fails with "`group` must be one of …", and a `visible` that is not true or false fails with "`visible` must be true or false"; either leaves every group as it is. The groups and their contents are VectorCraft's own. +`window.taskBar.actions {action, visible?}` (desktop app) turns one of the Contextual Task Bar's actions or chips on +(`visible: true`), off (`false`) or toggles it (omitted), and returns `{action, visible}`. The actions are `imageTrace`, +`cropImage`, `removeBackground`, `removeAnchorPoints`, `join` (Connect and Join), `cutPath`, `convertToCorner`, +`convertToSmooth`, `group`, `makeClippingMask`, `unite`, `expand`, `editClippingPath`, `releaseClippingMask`, +`ungroup`, `isolate`, `editPath`, `releaseCompoundPath`, `createOutlines`, `convertToPointType`, `convertToAreaType`, +`typeOnPathOptions`, `centerOnTop`, `centerOnBottom`, `dynamicText`, `offsetPath`, `simplify`, `smooth`, `duplicate`, +`drawPencil`, `placeImage`, `fidelity` and `smoothToolOptions` (the Smooth tool's), and `resizeArtboard`, +`duplicateArtboards`, `rearrangeArtboards` and `exportArtboards` (the Artboard tool's); the chips are `fill`, `stroke`, +`recolor` (Recolor Artwork), `lock` and `shapeProperties` (a basic shape's Shape Properties, in Lock's place). The bar's +More Options menu has Bar Actions, which lists the actions and chips the bar offers for the current selection or tool, +each checked while it is on, and runs the command for the one clicked. An action or chip that is off stays out of the +bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. Every action starts +on. The type font controls are not in Bar Actions and stay on the bar. Which actions are off is kept with the preferences +and with the workspace; a workspace or preferences saved without them show every action, and an id the bar does not have +is dropped when they are read. Another `action`, or none, fails with "`action` must be one of …", and a +`visible` that is not true or false fails with "`visible` must be true or false"; either leaves every action as it is. +`window.taskBar.resetActions {}` (More Options › Reset Bar Actions) turns every action and chip on again and returns +the ids it turned on. Choosing the bar's actions is VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1b68855fb..b1eaefd513 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1038,6 +1038,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: ) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`. - The help page describes the contextual task bar as one horizontal row () and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`. + - The contextual task bar's More Options menu has Bar Actions, which lists the actions and the Fill, Stroke, Recolor Artwork, Lock or Shape Properties chips the bar offers for the current selection or tool, each checked while it is on, and Reset Bar Actions, which turns every one on again (`window.taskBar.actions`, `window.taskBar.resetActions`). An action that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. The type font controls are not in Bar Actions. Which actions are off is kept with the preferences and with the workspace. Choosing the bar's actions is VectorCraft's own. Evidence: `an_action_turned_off_leaves_the_bar_and_stays_in_its_menu`, `an_action_turned_off_is_not_listed_in_more_options`, `every_action_the_bar_offers_can_be_turned_off`, `a_chip_turned_off_leaves_the_bar`, `reset_bar_actions_shows_every_action_again`, `bar_actions_are_kept_with_the_preferences` and `more_options_bar_actions_turns_an_action_off_and_on` in `crates/ui-egui/src/tests/taskbar.rs`, and `saved_workspaces_restore_the_task_bar_actions` in `crates/ui-egui/src/workspaces.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Smooth tool is in use with a path it can smooth selected (a path with three or more anchors, or two joined by a curve, on its own or inside a selected group), the contextual task bar shows the tool's Fidelity field and Tool Options…, which opens the Smooth tool's options. The overview says the Smooth tool's bar has its tool options (), and the tool's help page names Fidelity as its option (). A value typed or stepped in the field sets the tool's Fidelity through `tool.setOption`, with the same range, unit (screen pixels) and steps as the field in its options. VectorCraft's own rules: with nothing selected, or only straight lines or type selected, the tool shows no bar; the bar leaves out the selection tools' actions, the Fill and Stroke chips, Recolor Artwork and Lock; on a canvas too narrow for the field, More Options lists Fidelity, which opens the tool's options. Evidence: `the_smooth_tool_shows_fidelity_and_tool_options_for_a_path` and `the_smooth_tool_shows_no_bar_without_a_path_to_smooth` in `crates/ui-egui/src/tests/taskbar.rs`. From ccb9cf93f5fdfef123fde5c5ea858be6a8fbddbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 00:04:51 -0800 Subject: [PATCH 29/51] Contextual Task Bar: Bar Actions names without a full-width colon, wider coverage test Bar Actions listed the Smooth tool's Fidelity with its colon in Chinese, where the catalogs write a full-width colon, and with a trailing no-break space in French. bar_action_name now trims the colon in either width, the space before it and a final ellipsis. every_action_the_bar_offers_can_be_turned_off now also covers an Image Trace object's Expand, Dynamic Text on point, area and path type, the Type tool's bar and the chips. With every action and chip off, it checks that the bar still shows its handle and More Options, where Bar Actions turns them on again; docs/mcp.md and the progress-doc line say so. --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/task_bar.rs | 28 ++++++++----- crates/ui-egui/src/tests/taskbar.rs | 57 +++++++++++++++++++++++---- docs/mcp.md | 6 ++- docs/target-app-parity.md | 2 +- 5 files changed, 74 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 316681b493..1ae7fd0aff 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -74,7 +74,7 @@ pub use selection_marks::SelectionMarks; use task_bar::task_bar; pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, is_task_bar_action, read_hidden_task_bar_actions}; #[cfg(test)] -pub(crate) use task_bar::{chip_paints, images_with_other_art, task_bar_offered}; +pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_offered}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 7ba9ee4e94..c539197aff 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -19,8 +19,9 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) } -/// The actions the Contextual Task Bar offered when it was last drawn, before Bar Actions left any -/// out: each one's name and its id in [`TASK_BAR_ACTIONS`] (none: Bar Actions cannot turn it off). +/// The actions and chips the Contextual Task Bar offered when it was last drawn, before Bar Actions +/// left any out: each one's name and its id in [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: +/// Bar Actions cannot turn it off). #[cfg(test)] pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(String, Option<&'static str>)> { ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default()) @@ -191,7 +192,8 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). More Options › Bar Actions /// turns each action and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); -/// the bar leaves out the ones that are off, and Reset Bar Actions shows them all again. +/// the bar leaves out the ones that are off, and Reset Bar Actions shows them all again. With every +/// one of them off, the bar still shows its handle and More Options, where they turn back on. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let t = Tokens::get(ui.ctx()); let on_artboards = app.session.tool_id() == "artboard"; @@ -364,11 +366,8 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // the ones that are off there are left out of the bar. let hidden = &app.ui.task_bar_hidden_actions; #[cfg(test)] - ui.ctx().data_mut(|d| { - let ids: Vec<(String, Option<&'static str>)> = - items.iter().map(|(label, _, cmd, params)| (label.to_string(), action_id(cmd, params))).collect(); - d.insert_temp(task_bar_id().with("offered"), ids); - }); + let mut probe: Vec<(String, Option<&'static str>)> = + items.iter().map(|(label, _, cmd, params)| (label.to_string(), action_id(cmd, params))).collect(); let mut offered: Vec<(&str, &'static str)> = items.iter().filter_map(|(label, _, cmd, params)| Some((*label, action_id(cmd, params)?))).collect(); items.retain(|(_, _, cmd, params)| action_id(cmd, params).is_none_or(|a| !hidden.contains(a))); let bounds = xf.rect.shrink(8.0); @@ -392,6 +391,11 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), c.id(shape.is_some())))); + #[cfg(test)] + { + probe.extend(chips.iter().map(|c| (c.label(shape.is_some()).to_string(), Some(c.id(shape.is_some()))))); + ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), probe)); + } let chips: Vec = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect(); let offered: Vec<(&str, &str, bool)> = offered.into_iter().map(|(label, action)| (label, action, !hidden.contains(action))).collect(); let any_hidden = !hidden.is_empty(); @@ -528,7 +532,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { ui.set_min_width(170.0); for (label, action, shown) in &offered { - if widgets::menu_item_name(ui, label.trim_end_matches([':', '…']), true, *shown) { + if widgets::menu_item_name(ui, bar_action_name(label), true, *shown) { run = Some(("window.taskBar.actions", json!({ "action": action }))); } } @@ -701,6 +705,12 @@ fn action_id(cmd: &str, params: &serde_json::Value) -> Option<&'static str> { TASK_BAR_ACTIONS.iter().find(|(_, c, t)| *c == cmd && *t == tool).map(|a| a.0) } +/// The name More Options › Bar Actions lists for the bar's item `label`: without a field's colon +/// (a full-width one too), the space some languages put before it, or a final ellipsis. +pub(crate) fn bar_action_name(label: &str) -> &str { + label.trim_end().trim_end_matches([':', ':', '…']).trim_end() +} + /// Reads the Contextual Task Bar's actions and chips that are off, as kept in the preferences. Ids /// the bar does not have are dropped, and a value that is not a list of strings reads as none off, /// so the bar shows every action. diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 9b5ab37031..89ab5d324b 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1803,10 +1803,11 @@ fn an_action_turned_off_is_not_listed_in_more_options() { assert!(on_bar.iter().chain(&menu).any(|t| t == "Duplicate"), "Duplicate is still offered: {on_bar:?} {menu:?}"); } -/// Every action the bar offers, for every kind of selection and tool, has an id in Bar Actions, -/// and with all of them turned off the bar shows none of them. That covers Connect and Join (both -/// `join`), the actions matched by the tool they switch to (`editPath`, `drawPencil`, -/// `smoothToolOptions`), the Smooth tool's Fidelity and the Artboard tool's actions. +/// Every action and chip the bar offers, for every kind of selection and tool, has an id in Bar +/// Actions, and with all of them turned off the bar shows none of them but still shows, with More +/// Options. That covers Connect and Join (both `join`), the actions matched by the tool they switch +/// to (`editPath`, `drawPencil`, `smoothToolOptions`), the Smooth tool's Fidelity, Dynamic Text, +/// an Image Trace object's Expand, the Type tool's Fill and the Artboard tool's actions. #[test] fn every_action_the_bar_offers_can_be_turned_off() { let dir = crate::tests_folder::Folder::new("ui-taskbar-actions"); @@ -1878,7 +1879,16 @@ fn every_action_the_bar_offers_can_be_turned_off() { let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); select(app, &[t]); }), - &["createOutlines", "convertToAreaType"], + &["createOutlines", "convertToAreaType", "dynamicText", "fill", "stroke", "lock"], + ), + ( + "the Type tool with type selected", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + }), + &["fill"], ), ( "area type", @@ -1888,7 +1898,7 @@ fn every_action_the_bar_offers_can_be_turned_off() { app.run("type.convertToAreaType", json!({})).unwrap(); select(app, &[t]); }), - &["createOutlines", "convertToPointType"], + &["createOutlines", "convertToPointType", "dynamicText"], ), ( "type on a closed path", @@ -1897,7 +1907,15 @@ fn every_action_the_bar_offers_can_be_turned_off() { let t = id(app.run("text.createInPath", json!({"path": circle, "mode": "onPath", "text": "Round", "at": [90, 300]})).unwrap()); select(app, &[t]); }), - &["createOutlines", "typeOnPathOptions", "centerOnTop", "centerOnBottom"], + &["createOutlines", "typeOnPathOptions", "centerOnTop", "centerOnBottom", "dynamicText"], + ), + ( + "an Image Trace object", + Box::new(|app| { + place_image(app, &dir); + app.run("imageTrace.make", json!({"params": {}})).unwrap(); + }), + &["expand", "duplicate"], ), ( "an image", @@ -1967,9 +1985,32 @@ fn every_action_the_bar_offers_can_be_turned_off() { for action in &ids { show_action(&mut app, action, false); } - let (_, texts) = bar_texts(&mut app); + let (ctx, texts) = bar_texts(&mut app); for (label, _) in &offered { assert!(!has(&texts, label), "{case}: {label} is off: {texts:?}"); } + // The bar still shows, with More Options, where Bar Actions turns them back on. + assert!(canvas::task_bar_rect(&ctx).is_some(), "{case}: the bar still shows"); + let names: Vec = buttons(&mut app).1.into_iter().map(|(n, _)| n).collect(); + assert!(names.iter().any(|n| n == "More Options"), "{case}: {names:?}"); + for (label, _) in &offered { + assert!(!names.iter().any(|n| n == label), "{case}: {label} is off: {names:?}"); + } } } + +/// Bar Actions lists a field's name without its colon, as each language writes it, and an item +/// that opens a dialog without its ellipsis. +#[test] +fn bar_actions_list_names_without_a_colon_or_an_ellipsis() { + let lang = |code| crate::i18n::Lang::from_code(code).unwrap(); + for (code, label, name) in + [("en", "Fidelity:", "Fidelity"), ("en", "Tool Options…", "Tool Options"), ("fr", "Fidelity:", "Fidélité"), ("ja", "Fidelity:", "精度")] + .into_iter() + .chain([("zh-hans", "Fidelity:", "精确度"), ("zh-hant", "Fidelity:", "精確度"), ("zh-hans", "Tool Options…", "工具选项")]) + { + let label = crate::i18n::tr(lang(code), label); + assert_eq!(canvas::bar_action_name(label), name, "{code}: {label:?}"); + } + assert_eq!(canvas::bar_action_name("Duplicate"), "Duplicate"); +} diff --git a/docs/mcp.md b/docs/mcp.md index b7cbb49c0f..dd02cbefc1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8186,8 +8186,10 @@ every group as it is. The groups and their contents are VectorCraft's own. `duplicateArtboards`, `rearrangeArtboards` and `exportArtboards` (the Artboard tool's); the chips are `fill`, `stroke`, `recolor` (Recolor Artwork), `lock` and `shapeProperties` (a basic shape's Shape Properties, in Lock's place). The bar's More Options menu has Bar Actions, which lists the actions and chips the bar offers for the current selection or tool, -each checked while it is on, and runs the command for the one clicked. An action or chip that is off stays out of the -bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. Every action starts +each checked while it is on and named without a final colon or ellipsis, and runs the command for the one clicked. An +action or chip that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off +changes only the bar. With every action and chip it would offer off, the bar still shows its handle and More Options, +where Bar Actions turns them on again. Every action starts on. The type font controls are not in Bar Actions and stay on the bar. Which actions are off is kept with the preferences and with the workspace; a workspace or preferences saved without them show every action, and an id the bar does not have is dropped when they are read. Another `action`, or none, fails with "`action` must be one of …", and a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1eaefd513..02d20396ea 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1038,7 +1038,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: ) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`. - The help page describes the contextual task bar as one horizontal row () and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`. - - The contextual task bar's More Options menu has Bar Actions, which lists the actions and the Fill, Stroke, Recolor Artwork, Lock or Shape Properties chips the bar offers for the current selection or tool, each checked while it is on, and Reset Bar Actions, which turns every one on again (`window.taskBar.actions`, `window.taskBar.resetActions`). An action that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. The type font controls are not in Bar Actions. Which actions are off is kept with the preferences and with the workspace. Choosing the bar's actions is VectorCraft's own. Evidence: `an_action_turned_off_leaves_the_bar_and_stays_in_its_menu`, `an_action_turned_off_is_not_listed_in_more_options`, `every_action_the_bar_offers_can_be_turned_off`, `a_chip_turned_off_leaves_the_bar`, `reset_bar_actions_shows_every_action_again`, `bar_actions_are_kept_with_the_preferences` and `more_options_bar_actions_turns_an_action_off_and_on` in `crates/ui-egui/src/tests/taskbar.rs`, and `saved_workspaces_restore_the_task_bar_actions` in `crates/ui-egui/src/workspaces.rs`. + - The contextual task bar's More Options menu has Bar Actions, which lists the actions and the Fill, Stroke, Recolor Artwork, Lock or Shape Properties chips the bar offers for the current selection or tool, each checked while it is on, and Reset Bar Actions, which turns every one on again (`window.taskBar.actions`, `window.taskBar.resetActions`). An action that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. With all of them off, the bar still shows its handle and More Options. The type font controls are not in Bar Actions. Which actions are off is kept with the preferences and with the workspace. Choosing the bar's actions is VectorCraft's own. Evidence: `an_action_turned_off_leaves_the_bar_and_stays_in_its_menu`, `an_action_turned_off_is_not_listed_in_more_options`, `every_action_the_bar_offers_can_be_turned_off`, `a_chip_turned_off_leaves_the_bar`, `reset_bar_actions_shows_every_action_again`, `bar_actions_are_kept_with_the_preferences`, `bar_actions_list_names_without_a_colon_or_an_ellipsis` and `more_options_bar_actions_turns_an_action_off_and_on` in `crates/ui-egui/src/tests/taskbar.rs`, and `saved_workspaces_restore_the_task_bar_actions` in `crates/ui-egui/src/workspaces.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Smooth tool is in use with a path it can smooth selected (a path with three or more anchors, or two joined by a curve, on its own or inside a selected group), the contextual task bar shows the tool's Fidelity field and Tool Options…, which opens the Smooth tool's options. The overview says the Smooth tool's bar has its tool options (), and the tool's help page names Fidelity as its option (). A value typed or stepped in the field sets the tool's Fidelity through `tool.setOption`, with the same range, unit (screen pixels) and steps as the field in its options. VectorCraft's own rules: with nothing selected, or only straight lines or type selected, the tool shows no bar; the bar leaves out the selection tools' actions, the Fill and Stroke chips, Recolor Artwork and Lock; on a canvas too narrow for the field, More Options lists Fidelity, which opens the tool's options. Evidence: `the_smooth_tool_shows_fidelity_and_tool_options_for_a_path` and `the_smooth_tool_shows_no_bar_without_a_path_to_smooth` in `crates/ui-egui/src/tests/taskbar.rs`. From faa95b2eedd1c825940ebda96462aa726f470d6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 00:45:46 -0800 Subject: [PATCH 30/51] Contextual Task Bar: record the offered actions as the bar's other probes do The bar now stores the actions and chips it offers in its egui memory on every frame, as it stores whether it shows the font controls and its size, instead of only in test builds. The list holds each name and id without copying the names, and Bar Actions reads the same list, so the bar builds it once per frame. task_bar.rs has no test-only code again; the coverage test reads the list through task_bar_id. --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/task_bar.rs | 34 +++++++++------------------ crates/ui-egui/src/tests/taskbar.rs | 2 +- 3 files changed, 13 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1ae7fd0aff..4dfcd0f0eb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -74,7 +74,7 @@ pub use selection_marks::SelectionMarks; use task_bar::task_bar; pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, is_task_bar_action, read_hidden_task_bar_actions}; #[cfg(test)] -pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_offered}; +pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_id}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index c539197aff..9731d42a90 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -3,7 +3,7 @@ use super::{ }; /// The Contextual Task Bar's area. -fn task_bar_id() -> egui::Id { +pub(crate) fn task_bar_id() -> egui::Id { egui::Id::unique("task-bar") } @@ -19,14 +19,6 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) } -/// The actions and chips the Contextual Task Bar offered when it was last drawn, before Bar Actions -/// left any out: each one's name and its id in [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: -/// Bar Actions cannot turn it off). -#[cfg(test)] -pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(String, Option<&'static str>)> { - ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default()) -} - /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { @@ -362,13 +354,12 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let paints = chip_paints(app, ui.ctx()); let colored = has_colors(&st.doc, &st.selection.objects); let doc = st.uid; - // Every action and chip the bar offers here, with its name, for More Options › Bar Actions; - // the ones that are off there are left out of the bar. + // Every action and chip the bar offers here, with its name and its id in TASK_BAR_ACTIONS or + // TASK_BAR_CHIPS (none: Bar Actions cannot turn it off), for More Options › Bar Actions; the + // ones that are off there are left out of the bar. let hidden = &app.ui.task_bar_hidden_actions; - #[cfg(test)] - let mut probe: Vec<(String, Option<&'static str>)> = - items.iter().map(|(label, _, cmd, params)| (label.to_string(), action_id(cmd, params))).collect(); - let mut offered: Vec<(&str, &'static str)> = items.iter().filter_map(|(label, _, cmd, params)| Some((*label, action_id(cmd, params)?))).collect(); + let mut offered: Vec<(&'static str, Option<&'static str>)> = + items.iter().map(|(label, _, cmd, params)| (*label, action_id(cmd, params))).collect(); items.retain(|(_, _, cmd, params)| action_id(cmd, params).is_none_or(|a| !hidden.contains(a))); let bounds = xf.rect.shrink(8.0); // The canvas's width less the frame's margins and stroke. @@ -390,14 +381,11 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .into_iter() .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); - offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), c.id(shape.is_some())))); - #[cfg(test)] - { - probe.extend(chips.iter().map(|c| (c.label(shape.is_some()).to_string(), Some(c.id(shape.is_some()))))); - ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), probe)); - } + offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), Some(c.id(shape.is_some()))))); let chips: Vec = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect(); - let offered: Vec<(&str, &str, bool)> = offered.into_iter().map(|(label, action)| (label, action, !hidden.contains(action))).collect(); + let bar_actions: Vec<(&str, &str, bool)> = + offered.iter().filter_map(|&(label, action)| action.map(|a| (label, a, !hidden.contains(a)))).collect(); + ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), offered)); let any_hidden = !hidden.is_empty(); let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); let fidelity = app.session.tool_options()["fidelity"].as_f64(); @@ -531,7 +519,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Actions, which shows every action again. ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { ui.set_min_width(170.0); - for (label, action, shown) in &offered { + for (label, action, shown) in &bar_actions { if widgets::menu_item_name(ui, bar_action_name(label), true, *shown) { run = Some(("window.taskBar.actions", json!({ "action": action }))); } diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 89ab5d324b..8717c5dc2b 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1973,7 +1973,7 @@ fn every_action_the_bar_offers_can_be_turned_off() { app.run("tool.select", json!({"tool": "selection"})).unwrap(); setup(&mut app); let (ctx, _) = bar(&mut app); - let offered = canvas::task_bar_offered(&ctx); + let offered: Vec<(&'static str, Option<&'static str>)> = ctx.data(|d| d.get_temp(canvas::task_bar_id().with("offered")).unwrap_or_default()); assert!(canvas::task_bar_rect(&ctx).is_some() && !offered.is_empty(), "{case}: the bar shows actions"); for (label, action) in &offered { assert!(action.is_some(), "{case}: {label} has no id in Bar Actions"); From 8575c41c35926214805f9473bd8c81ede4b549ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 00:46:08 -0800 Subject: [PATCH 31/51] Part of #5941: a click on a drop-down list's scroll bar leaves it open A click on the track of an open drop-down list's scroll bar scrolled the list and then closed it, and the list opened again with its current option in view, so an option scrolled into view that way could not be picked. A click that goes to the list's scroll bar now leaves the list open; any other click closes it as before. --- crates/ui-egui/src/widgets/dropdowns.rs | 18 +++-- crates/ui-egui/src/widgets/look_tests.rs | 92 ++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 2ea0f48276..b8e0d17d6f 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -321,8 +321,9 @@ fn combo_button<'a>(ui: &mut Ui, button_id: egui::Id, current: impl egui::IntoAt /// The list of [`combo_atoms_named`] while it is open, drawn by `list` in a popup of its own that /// opens from `button` and takes the whole list whenever the window has room for it (#5941): below /// the button when it fits there, above it when it fits there instead, and otherwise shifted from -/// below into the window, over the button. A list taller than the window scrolls. Returns what -/// `list` returned, or `None` while the list is closed. +/// below into the window, over the button. A list taller than the window scrolls. A click closes +/// the list, except a click on its scroll bar, which scrolls it. Returns what `list` returned, or +/// `None` while the list is closed. fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> Option { let ctx = ui.ctx(); let id = button.id.with("popup"); @@ -330,8 +331,13 @@ fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> egui::containers::menu::menu_style(style); style.spacing.scroll = list_scroll_style(); }); - let popup = - egui::Popup::menu(button).id(id).width(button.rect.width()).style(style.clone()).close_behavior(egui::PopupCloseBehavior::CloseOnClick); + // The id of the list's scroll area. egui senses its vertical bar under the area's id with the + // axis, 1, and names the widget a click went to at the start of the pass. + let area_key = id.with("scroll-area-id"); + let on_bar = + ctx.data(|d| d.get_temp::(area_key)).is_some_and(|area| ctx.interaction_snapshot(|s| s.clicked == Some(area.with(1_usize)))); + let close = if on_bar { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; + let popup = egui::Popup::menu(button).id(id).width(button.rect.width()).style(style.clone()).close_behavior(close); let screen = ctx.content_rect(); // The room on each side of the rect the popup opens from: the part of the button in view. let anchor = popup.get_anchor_rect().unwrap_or(button.rect); @@ -364,7 +370,9 @@ fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> ui.set_max_height(height); // Labels widen a narrow list rather than wrap, as in egui's combo box. ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); - egui::ScrollArea::vertical().max_height(height).show(ui, list).inner + let shown = egui::ScrollArea::vertical().max_height(height).show(ui, list); + ui.data_mut(|d| d.insert_temp(area_key, shown.id)); + shown.inner }); if shown.is_some() { ctx.accesskit_node_builder(id, |node| node.set_role(egui::Role::ListBox)); diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 13ee6ebd58..24c67e79b4 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -971,6 +971,98 @@ fn a_dropdown_list_shows_every_option_when_the_window_has_room() { } } +// #5941: a click on the scroll bar's track of an open drop-down list scrolls it and leaves it open, +// so an option it scrolled into view can be picked. A list closed by that click would open again +// with its current option in view. +#[test] +fn a_click_on_a_dropdown_lists_scroll_bar_scrolls_it_and_leaves_it_open() { + let items: Vec = (0..40).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let picked = std::cell::Cell::new(None); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + let r = ui.horizontal(|ui| dropdown_names(ui, "bar-click", labels[0], &labels, 160.0)); + field.set(r.response.rect); + if let Some(i) = r.inner { + picked.set(Some(i)); + } + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let mut time = 0.0; + // The options that show whole on the open list, with their rects, and the scroll bar's rects. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let (mut texts, mut bars) = (vec![], vec![]); + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect)>, bars: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out, bars)), + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + if r.top() >= clip.top() && r.bottom() <= clip.bottom() { + out.push((t.galley.text().to_owned(), r)); + } + } + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + _ => {} + } + } + popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars)); + (texts, bars) + }; + let list_rect = || { + ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + }; + let click = + |at: Pos2, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![]); + let at = field.get().center(); + run(vec![egui::Event::PointerMoved(at), click(at, true)]); + run(vec![click(at, false)]); + let (mut before, mut bars) = (vec![], vec![]); + for _ in 0..4 { + (before, bars) = run(vec![]); + } + assert!(list_rect().is_some(), "the list is open"); + assert!(before.iter().any(|(s, _)| s == "Option 00"), "the list opens at its first option: {before:?}"); + // The track, below the handle: near the bottom of the tallest bar rect drawn (the track). + let bar = bars + .iter() + .copied() + .max_by(|a, b| a.height().total_cmp(&b.height())) + .unwrap_or_else(|| panic!("the list {:?} draws its scroll bar: {before:?}", list_rect())); + let track = pos2(bar.center().x, bar.bottom() - 6.0); + run(vec![egui::Event::PointerMoved(track), click(track, true)]); + run(vec![]); + // The button is let go just past the bar's edge, closer than a drag, and the pointer then moves + // sideways onto the rows, in the same pass. + let let_go = pos2(bar.right() + 1.0, track.y); + let onto_row = before.first().map(|(_, r)| pos2(r.center().x, track.y)).expect("a row shows"); + run(vec![egui::Event::PointerMoved(let_go), click(let_go, false), egui::Event::PointerMoved(onto_row)]); + let mut after = vec![]; + for _ in 0..4 { + (after, _) = run(vec![]); + } + assert!(list_rect().is_some(), "a click on the scroll bar leaves the list open"); + let new = after + .iter() + .find(|(s, _)| !before.iter().any(|(b, _)| b == s)) + .cloned() + .unwrap_or_else(|| panic!("the click scrolled options into view: {after:?}")); + let row = new.1.center(); + run(vec![egui::Event::PointerMoved(row), click(row, true)]); + run(vec![click(row, false)]); + run(vec![]); + let index = labels.iter().position(|l| *l == new.0); + assert_eq!(picked.get(), index, "the option scrolled into view is picked: {}", new.0); + assert!(list_rect().is_none(), "picking an option closes the list"); +} + /// Enter on text that reads as no number in a range field refuses it as a unit field does: the /// field flashes and an open dialog is not confirmed with the old value. #[test] From fe426f9bac7d5593ec9ab56310d3de1430cd9413 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 01:13:07 -0800 Subject: [PATCH 32/51] Contextual Task Bar: Bar Actions reads the offered list, coverage test edits type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The list of actions and chips the bar offers, stored on every frame, now holds whether each one shows, and More Options › Bar Actions reads it through task_bar_offered while its menu is open. The bar no longer builds a second list for the menu on every frame. The coverage test reads the same accessor, and it adds a case for the Type tool while it edits type, whose bar offers the Fill chip. --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/task_bar.rs | 20 +++++++++++++++----- crates/ui-egui/src/tests/taskbar.rs | 12 ++++++++++-- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4dfcd0f0eb..1ae7fd0aff 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -74,7 +74,7 @@ pub use selection_marks::SelectionMarks; use task_bar::task_bar; pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, is_task_bar_action, read_hidden_task_bar_actions}; #[cfg(test)] -pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_id}; +pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_offered}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 9731d42a90..4ae3821b2c 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -3,7 +3,7 @@ use super::{ }; /// The Contextual Task Bar's area. -pub(crate) fn task_bar_id() -> egui::Id { +fn task_bar_id() -> egui::Id { egui::Id::unique("task-bar") } @@ -19,6 +19,14 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) } +/// The actions and chips the Contextual Task Bar offered where it was last drawn, before Bar +/// Actions left any out, as More Options › Bar Actions lists them: each one's name, its id in +/// [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: Bar Actions cannot turn it off) and whether it +/// shows. +pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(&'static str, Option<&'static str>, bool)> { + ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default()) +} + /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { @@ -383,8 +391,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .collect(); offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), Some(c.id(shape.is_some()))))); let chips: Vec = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect(); - let bar_actions: Vec<(&str, &str, bool)> = - offered.iter().filter_map(|&(label, action)| action.map(|a| (label, a, !hidden.contains(a)))).collect(); + // Bar Actions reads this list through task_bar_offered while its menu is open. + let offered: Vec<(&'static str, Option<&'static str>, bool)> = + offered.into_iter().map(|(label, action)| (label, action, action.is_none_or(|a| !hidden.contains(a)))).collect(); ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), offered)); let any_hidden = !hidden.is_empty(); let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); @@ -519,8 +528,9 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // Actions, which shows every action again. ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { ui.set_min_width(170.0); - for (label, action, shown) in &bar_actions { - if widgets::menu_item_name(ui, bar_action_name(label), true, *shown) { + for (label, action, shown) in task_bar_offered(ui.ctx()) { + let Some(action) = action else { continue }; + if widgets::menu_item_name(ui, bar_action_name(label), true, shown) { run = Some(("window.taskBar.actions", json!({ "action": action }))); } } diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 8717c5dc2b..5228831202 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1807,7 +1807,8 @@ fn an_action_turned_off_is_not_listed_in_more_options() { /// Actions, and with all of them turned off the bar shows none of them but still shows, with More /// Options. That covers Connect and Join (both `join`), the actions matched by the tool they switch /// to (`editPath`, `drawPencil`, `smoothToolOptions`), the Smooth tool's Fidelity, Dynamic Text, -/// an Image Trace object's Expand, the Type tool's Fill and the Artboard tool's actions. +/// an Image Trace object's Expand, the Type tool's Fill with type selected and while it edits +/// type, and the Artboard tool's actions. #[test] fn every_action_the_bar_offers_can_be_turned_off() { let dir = crate::tests_folder::Folder::new("ui-taskbar-actions"); @@ -1890,6 +1891,13 @@ fn every_action_the_bar_offers_can_be_turned_off() { }), &["fill"], ), + ( + "the Type tool editing type", + Box::new(|app| { + edited_type(app, "type"); + }), + &["fill"], + ), ( "area type", Box::new(|app| { @@ -1973,7 +1981,7 @@ fn every_action_the_bar_offers_can_be_turned_off() { app.run("tool.select", json!({"tool": "selection"})).unwrap(); setup(&mut app); let (ctx, _) = bar(&mut app); - let offered: Vec<(&'static str, Option<&'static str>)> = ctx.data(|d| d.get_temp(canvas::task_bar_id().with("offered")).unwrap_or_default()); + let offered: Vec<(&str, Option<&str>)> = canvas::task_bar_offered(&ctx).into_iter().map(|(label, action, _)| (label, action)).collect(); assert!(canvas::task_bar_rect(&ctx).is_some() && !offered.is_empty(), "{case}: the bar shows actions"); for (label, action) in &offered { assert!(action.is_some(), "{case}: {label} has no id in Bar Actions"); From d15d0e817062793fcc3e2fc901e9cbe17adfdd4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 01:39:50 -0800 Subject: [PATCH 33/51] Contextual Task Bar: Bar Actions drops a three-period ending, null visible is an error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit More Options › Bar Actions now leaves out a final "..." from an item's name, as it already leaves out a final "…". A name that ends in one period keeps it. window.taskBar.actions now fails on a `visible` of null, as its params text and docs/mcp.md say it does for any value that is not true or false, and leaves every action as it is. An omitted `visible` still toggles the action. --- crates/ui-egui/src/canvas/task_bar.rs | 7 +++++-- crates/ui-egui/src/menus/run.rs | 10 +++++++++- crates/ui-egui/src/tests/taskbar.rs | 10 +++++++++- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 4ae3821b2c..74f8fa973a 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -704,9 +704,12 @@ fn action_id(cmd: &str, params: &serde_json::Value) -> Option<&'static str> { } /// The name More Options › Bar Actions lists for the bar's item `label`: without a field's colon -/// (a full-width one too), the space some languages put before it, or a final ellipsis. +/// (a full-width one too), the space some languages put before it, or a final ellipsis (`…` or +/// `...`). pub(crate) fn bar_action_name(label: &str) -> &str { - label.trim_end().trim_end_matches([':', ':', '…']).trim_end() + let label = label.trim_end(); + let label = label.strip_suffix("...").unwrap_or(label); + label.trim_end_matches([':', ':', '…']).trim_end() } /// Reads the Contextual Task Bar's actions and chips that are off, as kept in the preferences. Ids diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 0fbc656746..38c3e50dd3 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -640,7 +640,15 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option match (s("action").filter(|a| crate::canvas::is_task_bar_action(a)), opt_bool(p, "visible")) { + // A `visible` of null is an error, as any other value that is not true or false is; only + // an omitted one toggles. + "window.taskBar.actions" => match ( + s("action").filter(|a| crate::canvas::is_task_bar_action(a)), + match p.get("visible") { + Some(Value::Null) => Err("`visible` must be true or false".to_string()), + _ => opt_bool(p, "visible"), + }, + ) { (None, _) => { let ids = crate::canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(crate::canvas::TASK_BAR_CHIPS); Err(format!("`action` must be one of {}", ids.collect::>().join(", "))) diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 5228831202..c6243adf0c 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1677,7 +1677,13 @@ fn bar_action_ids_are_distinct() { fn bar_actions_refuse_bad_params() { let mut app = app(); show_action(&mut app, "group", false); - for p in [json!({"action": "teleport"}), json!({}), json!({"action": 3}), json!({"action": "unite", "visible": "yes"})] { + for p in [ + json!({"action": "teleport"}), + json!({}), + json!({"action": 3}), + json!({"action": "unite", "visible": "yes"}), + json!({"action": "unite", "visible": null}), + ] { assert!(app.run("window.taskBar.actions", p.clone()).is_err(), "{p}"); } let err = app.run("window.taskBar.actions", json!({"action": "teleport"})).unwrap_err(); @@ -2021,4 +2027,6 @@ fn bar_actions_list_names_without_a_colon_or_an_ellipsis() { assert_eq!(canvas::bar_action_name(label), name, "{code}: {label:?}"); } assert_eq!(canvas::bar_action_name("Duplicate"), "Duplicate"); + assert_eq!(canvas::bar_action_name("Tool Options..."), "Tool Options"); + assert_eq!(canvas::bar_action_name("Offset Path."), "Offset Path."); } From 9fc1a8db3342ff5f95dedb9382786fe7473ad03f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 02:29:06 -0800 Subject: [PATCH 34/51] Part of #5941: a drop-down list wider than the window keeps its bar in view A drop-down list with an option wider than the window ran past the window's right edge, and its scroll bar with it, out of reach. Once a list measures wider than the window, it stays inside the window until it closes: its names are cut short, with the full name on hover, and it grows back to the width its names need, with the bar's column while it scrolls, when the window widens. The Gradient panel's Presets menu asks for 200 pt rows only as far as the window allows. --- crates/ui-egui/src/panels/gradient.rs | 2 +- crates/ui-egui/src/panels/gradient/tests.rs | 14 ++ crates/ui-egui/src/widgets/dropdowns.rs | 48 ++++++- crates/ui-egui/src/widgets/look_tests.rs | 144 ++++++++++++++++++++ 4 files changed, 203 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 7baaa062ab..adf4dd723f 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -466,7 +466,7 @@ fn presets_row(app: &mut VectorcraftApp, ui: &mut Ui, g: Option<&GradientPaint>) /// the name of the one clicked. fn preset_list(app: &VectorcraftApp, ui: &mut Ui, shown: &str) -> Option { let t = Tokens::get(ui.ctx()); - ui.set_min_width(200.0); + widgets::menu_min_width(ui, 200.0); let mut chosen = None; // The library of the rows drawn last (`Some(None)`: the saved presets). let mut library: Option> = None; diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index bbf833b1aa..e4871b0886 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -797,6 +797,20 @@ fn text_at(texts: &[(String, Pos2)], s: &str) -> Option { texts.iter().find(|(t, _)| t.trim_start() == s).map(|(_, at)| *at) } +/// #5941: in a window narrower than the Presets menu's 200 pt rows, the menu stays inside the window, +/// so its scroll bar shows. +#[test] +fn the_presets_menu_stays_inside_a_narrow_window() { + let mut app = app(json!({"gradient": {}})); + let paint = current(&app).expect("a gradient fill"); + let mut window = PopupWindow::new(&mut app, 300.0, move |app, ui| presets_row(app, ui, Some(&paint))); + window.resize(&mut app, 190.0); + let label = window.text("Presets:").expect("the Presets row"); + window.click(&mut app, egui::pos2(label.right() + 40.0, label.center().y)); + let popup = window.popup().expect("the menu is open"); + assert!(popup.left() >= 0.0 && popup.right() <= 190.0, "the menu {popup:?} is inside the window"); +} + /// The Presets menu lists the presets by library (theme) and applies the one chosen to the /// gradient behind the active proxy, as one undo step; the menu then shows that preset. #[test] diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index b8e0d17d6f..e05235b411 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -361,21 +361,61 @@ fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> }; let mut popup_style = (*ctx.global_style()).clone(); style.apply(&mut popup_style); - let frame = egui::Frame::popup(&popup_style).total_margin().sum().y; - let height = (screen.height() - frame).max(ui.spacing().interact_size.y); + let margins = egui::Frame::popup(&popup_style).total_margin().sum(); + let height = (screen.height() - margins.y).max(ui.spacing().interact_size.y); + // A list that was wider than the window keeps its scroll bar in view: until it closes, it is no + // wider than it measured or than the window, its names cut short and shown in full on hover. + // Only a size measured while the list is open counts: egui keeps the last one after it closes. + // The width it needs is its rows' width on the last pass before it was narrowed, with its + // margins, and the bar's column while the rows scroll. + let too_wide_key = id.with("too-wide"); + let natural_key = id.with("natural-width"); + let scrolls_key = id.with("scrolls"); + let open_last_pass = ctx.read_response(id).is_some(); + if popup.get_expected_size().is_some_and(|size| open_last_pass && size.x > screen.width()) { + // The first measurement is kept: later ones are of the list already narrowed. + ctx.data_mut(|d| { + if d.get_temp::(too_wide_key).is_none() { + let rows = d.get_temp::(natural_key).unwrap_or(screen.width()); + d.insert_temp(too_wide_key, rows); + } + }); + } + let (measured, scrolls) = ctx.data(|d| (d.get_temp::(too_wide_key), d.get_temp::(scrolls_key).unwrap_or(false))); + let too_wide = measured.is_some(); let shown = popup.align(align).align_alternatives(&[]).show(|ui| { + if let Some(rows) = measured { + let bar = if scrolls { list_scroll_style().allocated_width() } else { 0.0 }; + ui.set_max_width((rows + bar).min(screen.width() - margins.x).max(0.0)); + } ui.set_min_width(ui.available_width()); // A popup offers its contents the height it had on its last pass; the list is offered the // window's instead. ui.set_max_height(height); // Labels widen a narrow list rather than wrap, as in egui's combo box. - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + ui.style_mut().wrap_mode = Some(if too_wide { egui::TextWrapMode::Truncate } else { egui::TextWrapMode::Extend }); + let painted = ui.ctx().graphics(|g| g.get(ui.layer_id()).map_or(0, |shapes| shapes.all_entries().len())); let shown = egui::ScrollArea::vertical().max_height(height).show(ui, list); - ui.data_mut(|d| d.insert_temp(area_key, shown.id)); + if too_wide { + show_shortened_rows(ui, painted); + } + ui.data_mut(|d| { + if !too_wide { + d.insert_temp(natural_key, shown.content_size.x); + } + d.insert_temp(scrolls_key, shown.content_size.y > shown.inner_rect.height()); + d.insert_temp(area_key, shown.id); + }); shown.inner }); if shown.is_some() { ctx.accesskit_node_builder(id, |node| node.set_role(egui::Role::ListBox)); + } else { + ctx.data_mut(|d| { + d.remove::(too_wide_key); + d.remove::(natural_key); + d.remove::(scrolls_key); + }); } shown.map(|r| r.inner) } diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 24c67e79b4..77c9af796c 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -1063,6 +1063,150 @@ fn a_click_on_a_dropdown_lists_scroll_bar_scrolls_it_and_leaves_it_open() { assert!(list_rect().is_none(), "picking an option closes the list"); } +// #5941: a drop-down list with an option wider than the window ran past the window's right edge, +// and its scroll bar with it. The list stays inside the window and its bar shows; the long option's +// name is cut short. +#[test] +fn a_dropdown_list_wider_than_the_window_keeps_its_scroll_bar_in_view() { + let mut items: Vec = (0..40).map(|i| format!("Option {i:02}")).collect(); + items[1] = "Option 01, whose name is much wider than this window".into(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let short: Vec<&str> = labels.iter().copied().filter(|l| l.len() < 10).collect(); + let two: Vec<&str> = labels[..2].to_vec(); + // Which list the field offers: 0 all, 1 the short names, 2 the first two. + let offered = std::cell::Cell::new(0); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + let options = [&labels, &short, &two][offered.get()]; + field.set(ui.horizontal(|ui| dropdown_names(ui, "wide-list", options[0], options, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0)); + let window = std::cell::Cell::new(screen); + let mut time = 0.0; + // The texts painted on the open list with their clip rects, and the scroll bar's rects. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(window.get()), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let (mut texts, mut bars) = (vec![], vec![]); + fn flat(s: &egui::Shape, clip: Rect, texts: &mut Vec<(String, bool)>, bars: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, texts, bars)), + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.galley.elided)), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect.intersect(clip)), + _ => {} + } + } + popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars)); + (texts, bars) + }; + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let (mut texts, mut bars) = (vec![], vec![]); + for _ in 0..6 { + (texts, bars) = run(vec![]); + } + let list_rect = || { + ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + }; + let list = list_rect().expect("the list is open"); + assert!(screen.contains_rect(list), "the list {list:?} is inside the window"); + assert!( + bars.iter().any(|b| b.width() > 0.0 && screen.contains_rect(*b) && list.contains_rect(*b)), + "the bar shows in the list {list:?}: {bars:?}" + ); + assert!(texts.iter().any(|(s, elided)| *elided && s.starts_with("Option 01")), "the long name is cut short: {texts:?}"); + // The window grows while the list is open: the list grows as wide as its names need, and no + // wider. + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + for _ in 0..6 { + (texts, _) = run(vec![]); + } + let grown = list_rect().expect("the list is still open"); + assert!(grown.width() < 500.0, "the list {grown:?} stays as wide as its names need"); + assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full: {texts:?}"); + // Narrowed and widened again, it comes back to the same width. + for size in [screen.size(), vec2(1000.0, 300.0)] { + window.set(Rect::from_min_size(Pos2::ZERO, size)); + for _ in 0..6 { + run(vec![]); + } + } + let again = list_rect().expect("the list is still open"); + assert!((again.width() - grown.width()).abs() < 0.5, "the list is as wide as before: {again:?}, {grown:?}"); + // Closed, the window narrowed again and the long option gone: the list opens as narrow as its + // names, not as wide as the window. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + run(vec![escape(true)]); + run(vec![escape(false)]); + assert!(list_rect().is_none(), "Escape closes the list"); + window.set(screen); + offered.set(1); + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let mut widths = vec![]; + for _ in 0..4 { + run(vec![]); + widths.push(list_rect().expect("the list is open").width()); + } + assert!(widths.iter().all(|w| *w < 180.0), "the list of short names stays narrow: {widths:?}"); + // Opened in a wide window, narrowed and widened again: it comes back to the width it opened at, + // the long list that scrolls and a list of two that does not. + for (which, count) in [(0, "40"), (2, "2")] { + run(vec![escape(true)]); + run(vec![escape(false)]); + offered.set(which); + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + run(vec![]); + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(990.0, 290.0))]); + for _ in 0..6 { + run(vec![]); + } + let opened = list_rect().expect("the list is open"); + for size in [screen.size(), vec2(1000.0, 300.0)] { + window.set(Rect::from_min_size(Pos2::ZERO, size)); + for _ in 0..6 { + run(vec![]); + } + } + let restored = list_rect().expect("the list is still open"); + // Within the half point that egui rounds a popup's position to. + assert!((restored.width() - opened.width()).abs() < 0.5, "{count} options: the list is as wide as it opened: {restored:?}, {opened:?}"); + } + // Opened in a narrow window tall enough for every option, then made wide and short: the list + // scrolls now, and its bar's column comes on top of the long name, which shows in full. + run(vec![escape(true)]); + run(vec![escape(false)]); + offered.set(0); + window.set(Rect::from_min_size(Pos2::ZERO, vec2(220.0, 1400.0))); + run(vec![]); + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 1390.0))]); + for _ in 0..6 { + run(vec![]); + } + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + for _ in 0..6 { + (texts, _) = run(vec![]); + } + assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full beside the bar: {texts:?}"); +} + /// Enter on text that reads as no number in a range field refuses it as a unit field does: the /// field flashes and an open dialog is not confirmed with the old value. #[test] From e16d59661ce98f91db6e58f1a8884cb235668fed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 02:16:47 -0800 Subject: [PATCH 35/51] Contextual Task Bar: Bar Actions names drop a colon and an ellipsis in any order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit More Options › Bar Actions now leaves out a final colon and a final ellipsis ("…" or "...") whichever comes last, with or without a space between them, so "Name...:" and "Name: ..." are listed as "Name". window.taskBar.actions treats a `visible` of null as omitted again, so the action toggles, as docs/mcp.md says for every command's params and as window.control.options does. Its params text and docs/mcp.md entry now say that null toggles, and a test covers it. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/canvas/task_bar.rs | 14 ++++++++++---- crates/ui-egui/src/menus/run.rs | 10 +--------- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/tests/taskbar.rs | 23 ++++++++++++++++------- docs/mcp.md | 5 +++-- 6 files changed, 32 insertions(+), 24 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index bfe50afa36..2f6851e42c 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -679,7 +679,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.taskBar.actions", "Bar Actions", "", - "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true or false, is an error and changes nothing; returns {action, visible}", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}", ), ( "window.taskBar.resetActions", diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 74f8fa973a..03ced4f7c6 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -705,11 +705,17 @@ fn action_id(cmd: &str, params: &serde_json::Value) -> Option<&'static str> { /// The name More Options › Bar Actions lists for the bar's item `label`: without a field's colon /// (a full-width one too), the space some languages put before it, or a final ellipsis (`…` or -/// `...`). +/// `...`), in whichever order they come. pub(crate) fn bar_action_name(label: &str) -> &str { - let label = label.trim_end(); - let label = label.strip_suffix("...").unwrap_or(label); - label.trim_end_matches([':', ':', '…']).trim_end() + let mut name = label.trim_end(); + loop { + let rest = name.trim_end_matches([':', ':', '…']); + let rest = rest.strip_suffix("...").unwrap_or(rest).trim_end(); + if rest == name { + return name; + } + name = rest; + } } /// Reads the Contextual Task Bar's actions and chips that are off, as kept in the preferences. Ids diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 38c3e50dd3..0fbc656746 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -640,15 +640,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option match ( - s("action").filter(|a| crate::canvas::is_task_bar_action(a)), - match p.get("visible") { - Some(Value::Null) => Err("`visible` must be true or false".to_string()), - _ => opt_bool(p, "visible"), - }, - ) { + "window.taskBar.actions" => match (s("action").filter(|a| crate::canvas::is_task_bar_action(a)), opt_bool(p, "visible")) { (None, _) => { let ids = crate::canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(crate::canvas::TASK_BAR_CHIPS); Err(format!("`action` must be one of {}", ids.collect::>().join(", "))) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 0845f5f08b..03b3a1b62b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -680,7 +680,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.taskBar.actions", "Bar Actions", "", - "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true or false, is an error and changes nothing; returns {action, visible}", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}", ), ( "window.taskBar.resetActions", diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index c6243adf0c..fc01daa133 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1608,6 +1608,9 @@ fn an_action_turned_off_leaves_the_bar_and_stays_in_its_menu() { assert_eq!(app.run("window.taskBar.actions", json!({"action": "offsetPath"})).unwrap(), json!({"action": "offsetPath", "visible": true})); let (_, texts) = bar(&mut app); assert!(has(&texts, "Offset Path"), "{texts:?}"); + // A `visible` of null counts as omitted and toggles too. + let r = app.run("window.taskBar.actions", json!({"action": "offsetPath", "visible": null})).unwrap(); + assert_eq!(r, json!({"action": "offsetPath", "visible": false})); } /// The Fill, Stroke, Recolor Artwork, Lock and Shape Properties chips each turn off on their own: @@ -1677,13 +1680,7 @@ fn bar_action_ids_are_distinct() { fn bar_actions_refuse_bad_params() { let mut app = app(); show_action(&mut app, "group", false); - for p in [ - json!({"action": "teleport"}), - json!({}), - json!({"action": 3}), - json!({"action": "unite", "visible": "yes"}), - json!({"action": "unite", "visible": null}), - ] { + for p in [json!({"action": "teleport"}), json!({}), json!({"action": 3}), json!({"action": "unite", "visible": "yes"})] { assert!(app.run("window.taskBar.actions", p.clone()).is_err(), "{p}"); } let err = app.run("window.taskBar.actions", json!({"action": "teleport"})).unwrap_err(); @@ -2029,4 +2026,16 @@ fn bar_actions_list_names_without_a_colon_or_an_ellipsis() { assert_eq!(canvas::bar_action_name("Duplicate"), "Duplicate"); assert_eq!(canvas::bar_action_name("Tool Options..."), "Tool Options"); assert_eq!(canvas::bar_action_name("Offset Path."), "Offset Path."); + // The colon and the ellipsis go in either order, with or without a space between them. + for label in [ + "Tool Options...:", + "Tool Options... :", + "Tool Options: ...", + "Tool Options …:", + "Tool Options… :", + "Tool Options…\u{a0}:", + "Tool Options...\u{202f}:", + ] { + assert_eq!(canvas::bar_action_name(label), "Tool Options", "{label:?}"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index dd02cbefc1..3121745656 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8192,8 +8192,9 @@ changes only the bar. With every action and chip it would offer off, the bar sti where Bar Actions turns them on again. Every action starts on. The type font controls are not in Bar Actions and stay on the bar. Which actions are off is kept with the preferences and with the workspace; a workspace or preferences saved without them show every action, and an id the bar does not have -is dropped when they are read. Another `action`, or none, fails with "`action` must be one of …", and a -`visible` that is not true or false fails with "`visible` must be true or false"; either leaves every action as it is. +is dropped when they are read. A `visible` of null toggles, as an omitted one does. Another `action`, or none, fails +with "`action` must be one of …", and a `visible` that is not true, false or null fails with "`visible` must be true +or false"; either leaves every action as it is. `window.taskBar.resetActions {}` (More Options › Reset Bar Actions) turns every action and chip on again and returns the ids it turned on. Choosing the bar's actions is VectorCraft's own. From 4d3bd79763de377605b81f7ee3e9c55c92ac1700 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:11:47 -0800 Subject: [PATCH 36/51] Symbols: a release that ends a drag begun in an earlier frame gives no modifiers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New Symbol, Delete Symbol and the panel menu's New Symbol… and Redefine Symbol read the modifiers of a release only when egui reports the control clicked by the pointer. A Click from the keyboard or a screen reader reads the modifiers held now, so an Alt release that ends a drag over Delete Symbol in the same frame no longer deletes without asking. --- crates/ui-egui/src/panels/symbols.rs | 99 ++++++++++++++++++++++++--- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/buttons.rs | 13 +++- 3 files changed, 102 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 204b0742c2..5557b7c8fe 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -459,7 +459,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. // Both are read as the button went up on it. - let m = modifiers_released_in(ui, new.interact_rect); + let m = modifiers_released_in(ui, new.interact_rect, new.clicked_by(egui::PointerButton::Primary)); let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; if m.shift { p["keepArt"] = json!(true); @@ -474,7 +474,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let picked = if marked.contains(&name) { &marked[..] } else { &[] }; delete(app, picked, Some(&name), alt_at_release(ui)); } else if trash.clicked() { - delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.interact_rect).alt); + let pointer = trash.clicked_by(egui::PointerButton::Primary); + delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.interact_rect, pointer).alt); } }); } @@ -496,9 +497,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ]; for (label, enabled, cmd, mut params, keeps_art) in items { let top = ui.cursor().min.y; - if menu_item(ui, label, enabled, false) { + let item = widgets::menu_item_response(ui, label, enabled, false); + if item.clicked() { let row = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.cursor().min.y); - if keeps_art && modifiers_released_in(ui, row).shift { + if keeps_art && modifiers_released_in(ui, row, item.clicked_by(egui::PointerButton::Primary)).shift { params["keepArt"] = json!(true); } app.run(cmd, params).ok(); @@ -609,15 +611,26 @@ fn alt_at_release(ui: &Ui) -> bool { /// distance of where the button went down) over `rect` or within egui's interact radius of it /// (egui counts a release that close as a click on the widget), as it went up (egui reports the /// click of the last such release in the frame), else now, as for a click from the keyboard or a -/// screen reader. A release that ends a drag is not a click and is skipped. -fn modifiers_released_in(ui: &Ui, rect: egui::Rect) -> egui::Modifiers { +/// screen reader. A release that ends a drag is not a click and is skipped, also when the drag +/// began in an earlier frame. `pointer` is whether egui reports the widget clicked by the primary +/// button; when it is false, the click came from the keyboard or a screen reader and the modifiers +/// held now are used. +fn modifiers_released_in(ui: &Ui, rect: egui::Rect, pointer: bool) -> egui::Modifiers { + if !pointer { + return ui.input(|i| i.modifiers); + } let radius = ui.ctx().global_style().interaction.interact_radius; let max_click_dist = ui.ctx().options(|o| o.input_options.max_click_dist); ui.input(|i| { // Where the button went down in this frame, and whether the pointer has since moved too far - // for a click; a press in an earlier frame is taken as the start of a click. + // for a click. let mut origin: Option = None; let mut moved = false; + // Whether a button went down earlier in this frame; until one does, a release ends a press + // of an earlier frame. + let mut pressed_here = false; + // The modifiers of the release over `rect` that ends a press of an earlier frame. + let mut early = None; let mut found = None; for e in &i.events { match e { @@ -627,11 +640,17 @@ fn modifiers_released_in(ui: &Ui, rect: egui::Rect) -> egui::Modifiers { egui::Event::PointerButton { pos, pressed: true, .. } => { origin = Some(*pos); moved = false; + pressed_here = true; } egui::Event::PointerButton { pos, button, pressed: false, modifiers } => { moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist); - if *button == egui::PointerButton::Primary && !moved && rect.distance_sq_to_pos(*pos) <= radius * radius { - found = Some(*modifiers); + let over = rect.distance_sq_to_pos(*pos) <= radius * radius; + if *button == egui::PointerButton::Primary { + if !pressed_here { + early = over.then_some(*modifiers); + } else if !moved && over { + found = Some(*modifiers); + } } origin = None; moved = false; @@ -639,7 +658,9 @@ fn modifiers_released_in(ui: &Ui, rect: egui::Rect) -> egui::Modifiers { _ => {} } } - found.unwrap_or(i.modifiers) + // egui tracks a press of an earlier frame. A widget it reports clicked by the pointer, with + // no click on it after a press of this frame, was clicked by the early release. + found.or(early).unwrap_or(i.modifiers) }) } @@ -1050,6 +1071,21 @@ mod tests { assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); } + /// A Shift-click on New Symbol… in the panel menu that goes down in one frame and up in the next + /// keeps the art as ordinary art, though a plain click elsewhere follows in the same frame. + #[test] + fn a_shift_click_on_new_symbol_in_the_menu_counts_though_a_click_elsewhere_follows() { + let (mut app, _) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let off = pos2(-10.0, -10.0); + let after = vec![egui::Event::PointerMoved(off), button(off, true), button(off, false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; + click_menu_held_then(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT, after); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + } + /// Clicks the panel's New Symbol button with `modifiers` held. fn click_new(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { click_button_then(app, "New Symbol", modifiers, vec![]); @@ -3102,6 +3138,49 @@ mod tests { assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); } + /// A screen reader's Click on Delete Symbol asks first for an unused symbol, though in the same + /// frame an Alt release over the button ends a drag that began in an earlier frame and Alt is + /// let go after. + #[test] + fn a_screen_reader_click_on_delete_does_not_take_alt_from_a_drag_begun_earlier() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = + nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")).map(|(id, _)| *id).expect("a Delete Symbol node"); + let trash = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1; + let off = pos2(-10.0, -10.0); + let press = egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT }; + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(off), press], egui::Modifiers::ALT); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash - vec2(0.0, 80.0))], egui::Modifiers::ALT); + let click = + egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: node, target_tree: TreeId::ROOT, data: None }); + let events = vec![egui::Event::PointerMoved(trash), alt_release(trash), egui::Event::ModifiersChanged(egui::Modifiers::NONE), click]; + frame_held(&ctx, &mut app, events, egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the screen reader's Click asks first"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + } + + /// A click on Delete Symbol that goes down in one frame and up with Alt held in the next deletes + /// an unused symbol without asking, though a plain click elsewhere follows in the same frame. + #[test] + fn an_alt_click_on_delete_across_frames_counts_though_a_click_elsewhere_follows() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let trash = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1; + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash), button(trash, true)], egui::Modifiers::ALT); + let off = pos2(-10.0, -10.0); + let events = vec![alt_release(trash), egui::Event::PointerMoved(off), button(off, true), button(off, false)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt deletes an unused symbol without asking"); + assert_eq!(symbols(&mut app), ["Leaf"]); + } + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new /// symbol and adds no undo step: art of another document, objects the document no longer has, /// no objects, and a release away from the panel are not outlined, and art holding an instance diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index d6a0f7c50e..c0d6459c30 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -31,7 +31,7 @@ pub use buttons::{ primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, }; pub(crate) use buttons::{ - button_width, flat_button_fit_width, icon_button_info, paint_icon_button_named, primary_button_width, secondary_button_width, + button_width, flat_button_fit_width, icon_button_info, menu_item_response, paint_icon_button_named, primary_button_width, secondary_button_width, }; #[cfg(test)] use chips::gradient_chip_colors; diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index 19062eaf4c..6fb586a43c 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -213,9 +213,20 @@ pub fn menu_item(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool menu_item_name(ui, tl!(label), enabled, checked) } +/// [`menu_item`] that returns the row's response, for a caller that needs to know how it was +/// clicked. +pub(crate) fn menu_item_response(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response { + menu_item_name_response(ui, tl!(label), enabled, checked) +} + /// [`menu_item`] for a name that is user or file data (a library, a recent URL), never translated. /// Like the menu bar's items, the row lights up under the pointer. pub fn menu_item_name(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool { + menu_item_name_response(ui, label, enabled, checked).clicked() +} + +/// [`menu_item_name`] that returns the row's response. +fn menu_item_name_response(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response { let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; - ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)).clicked() + ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) } From 54a964d4fa6c9d0fff8bc384204656a210b392f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:21:35 -0800 Subject: [PATCH 37/51] Tools: an option set during a press survives the press being dropped A dropped press puts back the persistent options the tool had when the press began. It also put back an option set while the press was held (tool.setOption or the desktop app's setter), and the next store of the tool's options wrote the old value over the new one. A General > Corner Radius change during a Rounded Rectangle press was undone the same way. - Setting an option of the tool that took the press updates the press's saved options with every option the set changed, so the dropped press keeps them. - Setting an option stores all of the tool's options, the drag's changes included, so a dropped press after such a set stores the options it puts back. - A Corner Radius change updates the held Rounded Rectangle press's saved radius. - Both hold when the tool lent a selection tool for the press (a Cmd-drag). --- crates/engine/src/cmd/prefscmds.rs | 7 +++ crates/engine/src/lib.rs | 3 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/toolsettings.rs | 80 +++++++++++++++++++++++++ crates/engine/src/tooling.rs | 69 ++++++++++++++++++--- 5 files changed, 153 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index f66322498e..49b6680bde 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -752,6 +752,13 @@ impl Session { t.set_option("cornerRadius", &r); } } + // A press of the tool that is dropped keeps the new radius, also when the tool lent a + // selection tool for the press. + if self.press_taken_by("roundedRectangle") + && let Some((_, saved)) = self.press_options.as_mut() + { + saved.insert("cornerRadius".into(), r); + } } if fonts_folder_changed { let folder = self.prefs.fonts_folder.trim(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8cc6b4084e..6e2d79271a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -324,6 +324,9 @@ pub struct Session { /// The id and persistent options of the tool when the press under way began, which a dropped /// press puts back ([`Session::drop_tool_press`]). pub(crate) press_options: Option<(String, serde_json::Map)>, + /// An option of the active tool was set during the press under way, which stored all of its + /// options, so a dropped press stores the options it puts back. + pub(crate) press_options_stored: bool, /// The engine saves the selection and active layer before a Type press and restores them if it drops. pub(crate) press_type_selection: Option<(Selection, Option)>, /// The freeform gradient point selected once the tool took the press under way, which a diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6ad8ed586e..11d8629a6e 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -135,6 +135,7 @@ impl Session { plane_widget_press: false, pointer_held: false, press_options: None, + press_options_stored: false, press_type_selection: None, press_point: None, ruler_guide: None, diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index fbde9edca7..69d382f2dc 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() { assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides"); } +/// An option set with `tool.setOption` while a press is held survives the dropped press, in the +/// tool and in the stored options, while what the drag itself changed is put back in both. +#[test] +fn an_option_set_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "rectangularGrid"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + s.tool_key(ToolKey::Right, Mods::default(), v).unwrap(); + assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6))); + s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap(); + s.drop_tool_press(v).unwrap(); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay"); + let saved = &s.prefs.tool_settings["rectangularGrid"]; + assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are"); + select(&mut s, "selection"); + select(&mut s, "rectangularGrid"); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns"); + // The same through the desktop app's setter. + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + s.set_tool_option("columns", &json!(3)); + s.drop_tool_press(v).unwrap(); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3))); + let saved = &s.prefs.tool_settings["rectangularGrid"]; + assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3))); +} + +/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped +/// press, in the tool and in the preference. +#[test] +fn a_corner_radius_set_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "roundedRectangle"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + let mut p = s.prefs.clone(); + p.corner_radius = 30.0; + s.apply_prefs(p); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius"); + assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); +} + +/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag +/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius +/// preference set while the Rounded Rectangle lends one. +#[test] +fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "rectangularGrid"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let cmd = Mods { cmd: true, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool"); + s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back"); + assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns"); + assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them"); + select(&mut s, "roundedRectangle"); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool"); + let mut p = s.prefs.clone(); + p.corner_radius = 30.0; + s.apply_prefs(p); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius"); + assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); +} + /// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with /// the next click. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 5f36c5a98e..13bda25533 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -611,13 +611,18 @@ impl Session { /// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what /// the tool asks for along the way, only a cancel and a notify run, so a marquee selects /// nothing and a click opens no size dialog. The tool gets back the persistent options it had - /// when the press began, and none of the press's changes to them are stored. A dropped Type - /// press restores the prior selection. The freeform gradient point selected once the tool - /// took the press is selected again. A press held while the tool computes an edit on another - /// thread has not reached the tool: it is removed from the held input with the pointer events - /// and tool keys held after it, and the tool is left as it is. A perspective plane key held - /// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held - /// after the last held release belong to the press the tool has, and are removed with it. + /// when the press began, and none of the press's changes to them are stored. An option set + /// during the press with [`Self::set_tool_option`] or [`Self::set_tool_options`], or a General › + /// Corner Radius change during a Rounded Rectangle press, keeps its new value, also when the + /// tool lent a selection tool for the press (a Cmd-drag). Setting an option stores all of the + /// tool's options, the press's changes included, so the dropped press then stores the options + /// it puts back. A dropped Type press restores the prior selection. The freeform gradient + /// point selected once the tool took the press is selected again. A press held while the tool + /// computes an edit on another thread has not reached the tool: it is removed from the held + /// input with the pointer events and tool keys held after it, and the tool is left as it is. + /// A perspective plane key held after it stays held, since the plane it picks outlasts a + /// dropped press. Pointer events held after the last held release belong to the press the tool + /// has, and are removed with it. pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> { let (from, held) = self.held_press(); let keep: Vec = (self.held_input.iter().enumerate()) @@ -635,6 +640,7 @@ impl Session { // Nothing to roll back without a document; the tool still drops the press and gets the release. let _ = self.cancel_interaction(); let before = self.press_options.take(); + let stored = std::mem::take(&mut self.press_options_stored); let type_selection = self.press_type_selection.take(); let point = self.press_point.take(); let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx)); @@ -669,6 +675,11 @@ impl Session { self.tool.set_option(k, v); } } + // An option set during the press stored every option the tool had then, the press's + // changes included: those stored values are put back too. + if stored { + self.keep_tool_settings(); + } } r.map(drop) } @@ -706,6 +717,7 @@ impl Session { match ev.kind { PointerKind::Down => { self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref()))); + self.press_options_stored = false; self.press_type_selection = if matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") { self.active().map(|st| (st.selection.clone(), st.active_layer)) @@ -715,6 +727,7 @@ impl Session { } PointerKind::Up => { self.press_options = None; + self.press_options_stored = false; self.press_type_selection = None; } _ => {} @@ -1309,9 +1322,12 @@ impl Session { if key == "queue" && self.tool.id() == "place" { self.note_place_queue_roots(); } + let before_press = self.options_before_press_set(); + let sets_pressed = self.press_taken_by(self.tool.id()); self.tool.set_option(key, v); self.tool_set_since_reset = true; self.keep_tool_settings(); + self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed); } /// Keep the automation roots in force now as those the place cursor's queue, being loaded, @@ -1356,6 +1372,8 @@ impl Session { self.note_place_queue_roots(); } let active = id.is_none_or(|id| id == self.tool.id()); + let before_press = self.options_before_press_set(); + let sets_pressed = self.press_taken_by(id.unwrap_or(self.tool.id())); // The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again // when the drag ends. let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id)); @@ -1393,9 +1411,46 @@ impl Session { let set = other.id(); Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } + self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed); out } + /// The tool that took the press under way: the active tool, or the tool that lent a selection + /// tool for it (a Cmd-drag), which the dropped press gives its options back to. + fn pressed_tool(&self) -> Option<&dyn Tool> { + let (pressed, _) = self.press_options.as_ref()?; + std::iter::once(&self.tool).chain(self.lender.as_ref()).map(|t| t.as_ref()).find(|t| t.id() == pressed) + } + + /// Tool `id` took the press under way ([`Self::pressed_tool`]). + pub(crate) fn press_taken_by(&self, id: &str) -> bool { + self.pressed_tool().is_some_and(|t| t.id() == id) + } + + /// The persistent options of the tool that took the press under way ([`Self::pressed_tool`]) + /// before an option is set: a dropped press puts back the options it began with, except those + /// the set changes ([`Self::keep_press_set`]). + fn options_before_press_set(&self) -> Option> { + self.pressed_tool().map(Self::persistent_options) + } + + /// After an option is set during a held press, the press's saved options take the options of + /// the tool that took the press that the set changed from `before` or named (`named`), so a + /// dropped press keeps them. `stored`: the set stored that tool's options, the press's changes + /// included, so a dropped press stores the options it puts back. + fn keep_press_set(&mut self, before: Option>, named: impl Fn(&str) -> bool, stored: bool) { + let Some(before) = before else { return }; + let Some(now) = self.pressed_tool().map(Self::persistent_options) else { return }; + self.press_options_stored |= stored; + if let Some((_, saved)) = self.press_options.as_mut() { + for (k, v) in now { + if before.get(&k) != Some(&v) || named(&k) { + saved.insert(k, v); + } + } + } + } + /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: /// the tool active when the call arrives, named before the edit in progress is finished) → its From 9dcc6913d8bb5c1ae1f7f1008e04c98ec3b15dd7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 02:32:34 -0800 Subject: [PATCH 38/51] Metafile import: text in the opaque background mode fills its character cells A metafile playback starts in the opaque background mode with a white background color, and text drawn in that mode fills its character cells with the background color before the glyphs. EMF and WMF import now adds one filled rectangle of the background color behind each line of such text, before the type, from the font's OS/2 usWinAscent above the baseline to its usWinDescent below it, as far as the line's advances reach (NULs and negative advances included). Files that never set the background mode now import with a background behind their text. Top and bottom aligned text now has the top or the bottom of that cell at the reference point instead of 0.8 and 0.2 of the em. A single line without advances is aligned as long as its glyphs' advances, trailing spaces included. NULs after a line break move the start of that line, and underlined or struck through blanks draw their bars. Face::win_ascent_descent gives the OS/2 usWinAscent and usWinDescent separately, at a variable font's instance. --- crates/metafile/src/import/picture.rs | 270 ++++++++++++++++++++++---- crates/metafile/src/tests/import.rs | 190 +++++++++++++++++- crates/text/src/fontdb/face.rs | 10 +- crates/text/src/tests.rs | 7 +- docs/mcp.md | 8 +- 5 files changed, 434 insertions(+), 51 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 125126790c..5f596e2389 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -16,7 +16,13 @@ //! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between. //! It is also carried on to the end of the last character's advance. Type on more than one line //! is placed a line at a time: each line is aligned by its own advances and split as a single -//! line is. +//! line is. NULs at the start, or after a line break, move the start of their line. A +//! character cell runs from the font's OS/2 usWinAscent above the baseline to its usWinDescent +//! below it, and top or bottom aligned text has the top or the bottom of its cells at the +//! reference point. One line without advances is aligned as long as its glyphs' advances, +//! trailing spaces included. Text drawn in the opaque background mode (the mode a playback +//! starts in) has one rectangle of the background color behind the character cells of each +//! line, as far as its advances reach. //! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around //! the whole picture clips nothing and is left out. //! @@ -539,24 +545,44 @@ impl Mapper { fn text(&mut self, t: &craft_metafile::Text, chain: Vec>) { // The characters without NULs, and each one's advance (text units) when the file gives // one for every character: a NUL's advance goes to the character before it, or moves the - // start when the string begins with one. + // start when the string, or a line after a line break, begins with one. let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite()); - let (mut s, mut dx, mut lead) = (String::new(), Vec::new(), 0.0f64); + let (mut s, mut dx) = (String::new(), Vec::new()); + // How far before and after its start each character's advances (its own and the NULs' + // after it) reach (text units): an advance may be negative. And before each character, + // the advance of the NULs that move its line's start, with how far they reach. + let (mut reach, mut leads) = (Vec::new(), Vec::new()); + let mut lead = Lead::default(); + let breaks = |c: char| matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'); for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) { if c != '\0' { s.push(c); dx.push(d); - } else if let Some(last) = dx.last_mut() { + reach.push((d.min(0.0), d.max(0.0))); + leads.push(std::mem::take(&mut lead)); + } else if let (Some(last), Some(r), false) = (dx.last_mut(), reach.last_mut(), s.chars().next_back().is_none_or(breaks)) { *last += d; + *r = (r.0.min(*last), r.1.max(*last)); } else { - lead += d; + lead.by += d; + lead.reach = (lead.reach.0.min(lead.by), lead.reach.1.max(lead.by)); } } if !advances { dx.clear(); - lead = 0.0; + reach.clear(); + leads.clear(); + lead = Lead::default(); } - if s.trim().is_empty() || t.color[3] == 0 { + // The leading NULs of the first line, or of a string of NULs alone. + let first = leads.first().copied().unwrap_or(lead); + // Type that draws nothing still fills its character cells on an opaque background. Blanks + // draw when they are underlined or struck through. + let background = t.background.filter(|c| c[3] > 0); + let shows = (!s.trim().is_empty() || t.font.underline || t.font.strike) && t.color[3] > 0; + // A string of NULs only fills the cells across its advances. + let nuls = s.is_empty() && first.reach.0 < first.reach.1 && background.is_some(); + if (s.is_empty() && !nuls) || !(shows || background.is_some()) { return; } // Text space → document without the move: its vertical scale gives the type size, and what @@ -613,11 +639,26 @@ impl Mapper { if !dx.is_empty() { style.kerning = Some(0.0); } - // Where the baseline is below the reference point. + // The character cell above and below the baseline (points): the face's OS/2 usWinAscent + // and usWinDescent at the type size (its own ascent and descent when it has no OS/2 + // table), as tall as a positive height asks. + let cell = face + .as_ref() + .map(|face| { + let (a, d) = face.win_ascent_descent().unwrap_or_else(|| face.vertical_metrics()); + (a / face.units_per_em() * size, d / face.units_per_em() * size) + }) + .filter(|(a, d)| a.is_finite() && d.is_finite() && *a >= 0.0 && *d >= 0.0 && a + d > 0.0) + .unwrap_or_else(|| { + let c = if h > 0.0 { size / 0.85 } else { size }; + (0.8 * c, 0.2 * c) + }); + // Where the baseline is below the reference point: the top or the bottom of the cell is at + // the reference point. let drop = match t.v_align { VAlign::Baseline => 0.0, - VAlign::Bottom => -0.2 * size, - VAlign::Top => 0.8 * size, + VAlign::Bottom => -cell.1, + VAlign::Top => cell.0, }; let origin = self.xf * Point::new(t.transform[4], t.transform[5]); let base = Affine::translate(origin.to_vec2()) * shape; @@ -633,19 +674,56 @@ impl Mapper { }; let whole = point(&s); let opacity = f32::from(t.color[3]) / 255.0; + let line = Line { + base, + drop, + align: &t.h_align, + decorated: f.underline || f.strike, + shows, + color: t.color, + opacity, + background, + cell, + point: &point, + }; + // The backgrounds of every line and piece, and the type added after them so that none of + // them covers it. + let mut out = TextOut::default(); if dx.is_empty() { let mut text = whole; - text.xf = base * Affine::translate((0.0, drop)); - text.cached_bounds = Some(vectorcraft_text::layout(db, &text).bounds); - let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); - n.opacity = opacity; - self.push(chain, n); - return; + let laid = vectorcraft_text::layout(db, &text); + // One line is as long as its advances, its trailing blanks included, where the + // alignment puts a line that long. + let along = laid + .glyphs + .iter() + .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); + let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); + let shift = if one { aligned(0.0, along.1, &t.h_align) - along.0 } else { 0.0 }; + text.xf = base * Affine::translate((if shift.is_finite() { shift } else { 0.0 }, drop)); + text.cached_bounds = Some(laid.bounds); + // The cells of one line run across its advances, those of more than one across each + // line's glyphs. NULs alone span their advances, where the alignment puts them. + let cells = if nuls { + let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; + cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) + } else if one { + cell_rect(along.0, along.0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + } else { + cells(&laid, &s, cell, &t.h_align) + }; + out.backs.extend(self.background(&line, cells, text.xf)); + if shows { + let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); + n.opacity = opacity; + out.texts.push(n); + } + return self.add_text(&chain, out); } // Text units grow by `k` along the baseline in the text object's own space. let dx: Vec = dx.iter().map(|d| d * k).collect(); + let reach: Vec<(f64, f64)> = reach.iter().map(|(lo, hi)| (lo * k, hi * k)).collect(); let chars: Vec = s.chars().collect(); - let line = Line { base, drop, align: &t.h_align, decorated: f.underline || f.strike, color: t.color, opacity, point: &point, chain: &chain }; // Type on more than one line is placed a line at a time, each line aligned by its own // advances (layout leaves the tracking after a line's last character out of the width it // aligns, and each line ends with its own) and its underline carried on to its own end. @@ -655,25 +733,68 @@ impl Mapper { // a search. let starts: Vec = s.char_indices().map(|(at, _)| at).collect(); let count = |to: usize| starts.partition_point(|at| *at < to); - let first = laid.lines.first().map_or(0.0, |l| l.baseline); - for (n, l) in laid.lines.iter().enumerate() { + let top = laid.lines.first().map_or(0.0, |l| l.baseline); + for l in &laid.lines { let (from, to) = (count(l.start), count(l.end)); - let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue }; - // A leading NUL's advance comes before the first line only. - let lead = if n == 0 { lead * k } else { 0.0 }; - let down = l.baseline - first; - self.line(&line, cs, dx, lead, if down.is_finite() { down } else { 0.0 }); + let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.get(from..to)) else { continue }; + // The NULs before the line's first character, at the start or after a line break. + let lead = leads.get(from).copied().unwrap_or_default().scaled(k); + let down = l.baseline - top; + self.line(&line, cs, Advances { dx, reach, lead }, if down.is_finite() { down } else { 0.0 }, &mut out); } } else { - self.line(&line, &chars, &dx, lead * k, 0.0); + self.line(&line, &chars, Advances { dx: &dx, reach: &reach, lead: first.scaled(k) }, 0.0, &mut out); + } + self.add_text(&chain, out); + } + + /// Adds a text record's backgrounds and then its type, leaving out backgrounds when there is + /// no room for both. + fn add_text(&mut self, chain: &[Arc], out: TextOut) { + let TextOut { mut backs, texts } = out; + let keep = MAX_NODES.saturating_sub(self.out.len()).saturating_sub(texts.len()); + if backs.len() > keep { + backs.truncate(keep); + self.warn(TOO_MANY); + } + for n in backs.into_iter().chain(texts) { + self.push(chain.to_vec(), n); } } - /// One line of text with advances `dx` (points along the baseline) for its characters `chars`, - /// `down` below the first line's baseline: in pieces, each a text object of its own, a new - /// piece after each cluster that tracking can't space by its advance. - fn line(&mut self, line: &Line, chars: &[char], dx: &[f64], lead: f64, down: f64) { - if chars.is_empty() || (chars.iter().all(|c| c.is_whitespace()) && !line.decorated) { + /// Character cells `cells`, placed by `xf`, filled with the line's background when it has one. + fn background(&self, line: &Line, mut cells: BezPath, xf: Affine) -> Option { + let bg = line.background?; + if cells.elements().is_empty() { + return None; + } + cells.apply_affine(xf); + self.path_node(cells, Some(bg), None, false) + } + + /// One line of text with advances `adv` (points along the baseline) for its characters + /// `chars`, `down` below the first line's baseline: in pieces, each a text object of its own, + /// a new piece after each cluster that tracking can't space by its advance. + fn line(&mut self, line: &Line, chars: &[char], adv: Advances, down: f64, out: &mut TextOut) { + let Advances { dx, reach, lead } = adv; + if chars.is_empty() { + return; + } + // The line's cells, one rectangle behind every piece, run as far each way as its + // advances reach (an advance may be negative), from where the leading NULs' advances + // start, which the alignment puts where it puts a line as long as its advances. + let start = aligned(lead.by, dx.iter().sum(), line.align); + let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); + for (d, r) in dx.iter().zip(reach) { + (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1)); + pos += d; + } + let xf = line.base * Affine::translate((0.0, line.drop + down)); + out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf)); + let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace()); + // A piece's type draws when it shows: blanks only when underlined or struck through. + let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated); + if !draws(chars) { return; } let db = vectorcraft_text::FontDb::global(); @@ -684,13 +805,13 @@ impl Mapper { // Along the baseline (the text object's own space), where the next piece starts from the // reference point: the line as long as its advances (a leading NUL's included), where the // alignment puts it. - let mut at = aligned(lead, dx.iter().sum(), line.align); + let mut at = start; let last = pieces.len().saturating_sub(1); for (i, (from, to)) in pieces.into_iter().enumerate() { - let piece: String = chars.get(from..to).unwrap_or_default().iter().collect(); + let cs = chars.get(from..to).unwrap_or_default(); + let piece: String = cs.iter().collect(); let dx = dx.get(from..to).unwrap_or_default(); - // Blanks of their own draw nothing unless they are underlined or struck through. - if piece.trim().is_empty() && !line.decorated { + if !draws(cs) { at += dx.iter().sum::(); continue; } @@ -715,12 +836,12 @@ impl Mapper { let gap = if (split && i < last) || (i == last && line.decorated) { gaps(&laid, db, &text, x0 + span) } else { BezPath::new() }; let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text.clone()))); n.opacity = line.opacity; - self.push(line.chain.to_vec(), n); + out.texts.push(n); if !gap.elements().is_empty() { let mut gap = gap; gap.apply_affine(text.xf); if let Some(n) = self.path_node(gap, Some(line.color), None, false) { - self.push(line.chain.to_vec(), n); + out.texts.push(n); } } } @@ -785,16 +906,89 @@ fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 { /// What every piece of a text record's lines shares: the text space (`base`, with the baseline /// `drop` below the reference point), the alignment, whether the type is underlined or struck -/// through, its color and opacity, a point type object of a string in its style, and its clips. +/// through, whether the type shows, its color and opacity, its background and the character cell +/// above and below the baseline (points), and a point type object of a string in its style. struct Line<'a> { base: Affine, drop: f64, align: &'a HAlign, decorated: bool, + shows: bool, color: [u8; 4], opacity: f32, + background: Option<[u8; 4]>, + cell: (f64, f64), point: &'a dyn Fn(&str) -> TextObject, - chain: &'a [Arc], +} + +/// What a text record draws: the backgrounds behind its character cells, and its type (with the +/// bars that carry an underline or strikethrough on), added after them. +#[derive(Default)] +struct TextOut { + backs: Vec, + texts: Vec, +} + +/// One line's advances (points along the baseline): each character's own, how far before and +/// after its start the advances from it to the next character reach, and the leading NULs'. +struct Advances<'a> { + dx: &'a [f64], + reach: &'a [(f64, f64)], + lead: Lead, +} + +/// The NULs that move a line's start: their advance, and how far before and after the line's +/// start they reach. +#[derive(Clone, Copy, Default)] +struct Lead { + by: f64, + reach: (f64, f64), +} + +impl Lead { + /// The same NULs with their advances grown by `k`. + fn scaled(self, k: f64) -> Lead { + Lead { by: self.by * k, reach: (self.reach.0 * k, self.reach.1 * k) } + } +} + +/// The character cell from `x0` to `x1` along a baseline at `y`, `cell.0` above and `cell.1` +/// below it (points); empty when it has no area. +fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath { + let r = Rect::new(x0, y - cell.0, x1, y + cell.1).abs(); + if r.width() > 0.0 && r.height() > 0.0 && r.is_finite() { shapes::rectangle(r).to_bezpath() } else { BezPath::new() } +} + +/// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above +/// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout +/// places it (its trailing blanks are left out of the width layout aligns), or for a line of +/// blanks alone as wide as their advances, where `align` puts a line that long. +fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign) -> BezPath { + // Each line's baseline, the sum of its glyphs' advances and whether they are all blanks. + // Glyphs come line by line. + let mut lines: Vec<(usize, f64, f64, bool)> = Vec::new(); + for g in &laid.glyphs { + let blank = s.get(g.byte..).and_then(|r| r.chars().next()).is_none_or(char::is_whitespace); + match lines.last_mut() { + Some((line, _, width, all)) if *line == g.line => { + *width += g.advance; + *all &= blank; + } + _ => lines.push((g.line, g.origin.y, g.advance, blank)), + } + } + let mut bp = BezPath::new(); + for (line, y, width, blank) in lines { + let (x0, x1) = match laid.lines.get(line) { + Some(l) if !blank => (l.x0, l.x1), + _ => { + let x0 = aligned(0.0, width, align); + (x0, x0 + width) + } + }; + bp.extend(cell_rect(x0, x1, y, cell)); + } + bp } /// The most times [`advanced`] lays the type out again to correct its tracking. diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 01883c740b..64f826b16a 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -274,7 +274,9 @@ fn hand_built_emf_plays_like_gdi() { let lines = &children[1]; assert_eq!(lines.appearance.items.len(), 1); assert!(near(lines.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 5.0 * mm, 5.0 * mm), 0.01)); - let NodeKind::Text(t) = &children[2].kind else { panic!("text") }; + // The background mode starts opaque: the text's cells are filled white behind it. + assert_eq!(fill_rgb(&children[2]), Some([255, 255, 255])); + let NodeKind::Text(t) = &children[3].kind else { panic!("text") }; assert_eq!(t.plain_text(), "Hi"); let st = &t.runs[0].style; assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Arial", "Bold")); @@ -884,6 +886,38 @@ fn wmf_font_width_becomes_horizontal_scale() { assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); } +#[test] +fn wmf_text_fills_its_cells_in_the_opaque_background_mode() { + // CREATEFONTINDIRECT and SELECTOBJECT: a 0.1 inch em; SETBKCOLOR green; SETBKMODE `mode` + // (none when 0); TEXTOUT "Hi" at (720, 360), top aligned. + let backgrounds = |mode: i16| { + let mut font = le16(&[-144, 0, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19))); + let mut text = le16(&[2]); + text.extend(b"Hi"); + text.extend(le16(&[360, 720])); + let mut records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0201, 0x0000_ff00u32.to_le_bytes().to_vec())]; + if mode != 0 { + records.push((0x0102, le16(&[mode, 0]))); + } + records.push((0x0521, text)); + paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document) + }; + let mm = 72.0 / 25.4; + // A file that never sets the mode, and one that sets OPAQUE: one green rectangle whose top + // is at the reference point and whose left edge is at the start of the text. + for mode in [0, 2] { + let p = backgrounds(mode); + assert_eq!(p.len(), 1, "{mode}"); + assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0]), "{mode}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.x0 - 12.7 * mm).abs() < 0.01 && (b.y0 - 6.35 * mm).abs() < 0.01 && b.x1 > b.x0 && b.y1 > b.y0, "{mode}: {b:?}"); + } + // TRANSPARENT: no background. + assert!(backgrounds(1).is_empty()); +} + #[test] fn a_clip_whose_box_holds_the_picture_still_clips() { // A diamond around the middle of the picture, whose box holds the whole frame but which cuts @@ -1001,7 +1035,8 @@ fn clipped_text_is_clipped_to_its_rectangle() { let mut font = le(&[2, -1000, 0, 0, 0, 400]); font.extend([0, 1, 1, 0, 0, 0, 0, 0]); font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); - let mut records = vec![(82, font), (37, le(&[2])), (84, text)]; + // SETBKMODE TRANSPARENT: no background behind the text. + let mut records = vec![(18, le(&[1])), (82, font), (37, le(&[2])), (84, text)]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let layer = back.document.layers[0].children().unwrap(); assert_eq!(layer.len(), 1); @@ -1030,6 +1065,142 @@ fn clipped_text_is_clipped_to_its_rectangle() { assert!(matches!(children[1].kind, NodeKind::Text(_))); } +/// The layer of an EMF that sets the background color green, the background mode `mode` (none +/// when 0) and the text alignment `align`, then draws `s` at (`x`, 1500) in `font` with the +/// advances `dx`. +fn on_background(mode: i32, align: i32, x: i32, font: Vec, s: &str, dx: &[i32]) -> Vec> { + let mut records = vec![(25, le(&[0x0000_ff00])), (22, le(&[align])), (82, font), (37, le(&[2])), (84, text_out(x, s, dx))]; + if mode > 0 { + records.insert(0, (18, le(&[mode]))); + } + import(&hand_emf(5000, 3000, &records)).unwrap().document.layers[0].children().unwrap().clone() +} + +#[test] +fn opaque_backgrounds_fill_behind_the_character_cells() { + let mm = 72.0 / 25.4; + let aligned = on_background; + // TA_BASELINE: the baseline at (10, 15) mm. + let drawn = |mode: i32, font: Vec, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx); + let opaque = |font: Vec, s: &str, dx: &[i32]| drawn(2, font, s, dx); + // "Hi" with advances of 20 and 10 mm in a 10 mm em: the cells run across the advances, from + // the face's usWinAscent above the baseline to its usWinDescent below it, behind the type. + let layer = opaque(arial(), "Hi", &[2000, 1000]); + assert_eq!(layer.len(), 2); + assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let face = vectorcraft_text::FontDb::global().style_face(&t.runs[0].style).unwrap(); + let (a, d) = face.win_ascent_descent().unwrap(); + let em = face.units_per_em(); + let b = layer[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(10.0 * mm, (15.0 - 10.0 * a / em) * mm, 40.0 * mm, (15.0 + 10.0 * d / em) * mm), 0.01), "{b:?}"); + // TA_TOP and TA_BOTTOM put the top and the bottom of the cell at the reference point: the + // baseline is usWinAscent below it, or usWinDescent above it. + for (align, top) in [(0, 15.0), (8, 15.0 - 10.0 * (a + d) / em)] { + let layer = aligned(2, align, 1000, arial(), "Hi", &[2000, 1000]); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.y0 - top * mm).abs() < 0.01 && (b.height() - 10.0 * (a + d) / em * mm).abs() < 0.01, "{align}: {b:?}"); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let baseline = (t.xf * vectorcraft_geom::Point::ZERO).y; + assert!((baseline - (top + 10.0 * a / em) * mm).abs() < 0.01, "{align}: {baseline}"); + } + // A leading NUL's advance is filled too: right aligned at 50 mm, "\0Hi" fills from 10 mm. + let b = aligned(2, 26, 5000, arial(), "\0Hi", &[1000, 2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 50.0 * mm).abs() < 0.01, "{b:?}"); + // A positive height is the cell: 10 mm from top to bottom. + let mut font = le(&[2, 1000, 0, 0, 0, 400]); + font.extend([0; 8]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let b = opaque(font, "Hi", &[2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.height() - 10.0 * mm).abs() < 0.01, "{b:?}"); + // Without advances the cells run across the glyphs' own advances. + let layer = opaque(arial(), "Hi", &[]); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let (xs, end) = glyph_xs(t); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); + // Type split where an advance is further than tracking reaches: one background across the + // whole line's advances comes before both pieces of type. + let layer = opaque(arial(), "Hiy", &[12000, 500, 1000]); + let kinds: Vec = layer.iter().map(|n| matches!(n.kind, NodeKind::Text(_))).collect(); + assert_eq!(kinds, [false, true, true]); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 145.0 * mm).abs() < 0.01, "{b:?}"); + // A NUL after a line break moves the start of the line it begins, as it moves the first + // line's: "\0B" on a line of its own is placed and filled as the same record alone. + // Where the last text object's first glyph starts, and the left edges of the backgrounds. + let placed = |layer: &[std::sync::Arc]| { + let last = layer.iter().rev().find_map(|n| match &n.kind { + NodeKind::Text(t) => Some(glyph_xs(t).0[0]), + _ => None, + }); + let backs: Vec = + layer.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).map(|b| b.x0).collect(); + (last.unwrap(), backs) + }; + let (b_alone, _) = placed(&opaque(arial(), "\0B", &[2000, 1000])); + let (b_together, backs) = placed(&opaque(arial(), "A\n\0B", &[1000, 0, 2000, 1000])); + assert!((b_alone - 30.0 * mm).abs() < 0.01 && (b_together - b_alone).abs() < 0.01, "{b_alone} {b_together}"); + assert!(backs.len() == 2 && backs.iter().all(|x| (x - 10.0 * mm).abs() < 0.01), "{backs:?}"); +} + +#[test] +fn opaque_backgrounds_reach_as_far_as_the_advances() { + let mm = 72.0 / 25.4; + let aligned = on_background; + // TA_BASELINE: the baseline at (10, 15) mm. + let drawn = |mode: i32, font: Vec, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx); + let opaque = |font: Vec, s: &str, dx: &[i32]| drawn(2, font, s, dx); + // Two lines: a rectangle behind each, not one block over the space between them. + let layer = opaque(arial(), "Hi\nHi", &[]); + let NodeKind::Path { path, .. } = &layer[0].kind else { panic!("a path") }; + let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count(); + assert_eq!(rects, 2); + // Without advances, a line is aligned as long as its advances, trailing spaces included, and + // its cells run across them: right aligned at 40 mm, "Hi " and its cells end there. + let layer = aligned(2, 26, 4000, arial(), "Hi ", &[]); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let (xs, end) = glyph_xs(t); + let b = layer[0].geometric_bounds().unwrap(); + assert!(xs.len() == 3 && (end - 40.0 * mm).abs() < 0.01, "{xs:?} {end}"); + assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); + // On more than one line, each line is aligned without its trailing spaces, and so are its + // cells: right aligned at 40 mm, neither passes it. + let b = aligned(2, 26, 4000, arial(), "Hi \nHi", &[])[0].geometric_bounds().unwrap(); + assert!((b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}"); + // NULs whose advances go forward and back again still fill as far as they reach. + let layer = opaque(arial(), "\0\0", &[1000, -1000]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 20.0 * mm).abs() < 0.01, "{b:?}"); + let b = opaque(arial(), "H\0i", &[3000, -2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}"); + // An advance that goes back: the cells reach as far as the advances go, here to 30 mm. + let b = opaque(arial(), "Hi", &[2000, -1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}"); + // NULs alone fill across their advances. + let layer = opaque(arial(), "\0", &[2000]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}"); + // Blanks on an opaque background still fill their cells, from the reference point on; on a + // transparent one nothing is left. + let layer = opaque(arial(), " \t", &[]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && b.x1 > 10.0 * mm, "{b:?}"); + assert!(drawn(1, arial(), " \t", &[]).is_empty()); + // Underlined blanks draw their underline, on a transparent background too. + for mode in [1, 2] { + let layer = drawn(mode, font_of("Arial", true), " ", &[]); + assert!(layer.iter().any(|n| matches!(&n.kind, NodeKind::Text(t) if t.runs[0].style.underline)), "{mode}"); + } + // A file that never sets the mode draws in the opaque mode a playback starts in. + let layer = drawn(0, arial(), "Hi", &[]); + assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); + assert!(drawn(1, arial(), "Hi", &[]).iter().all(|n| matches!(n.kind, NodeKind::Text(_)))); +} + /// The first text object of `d`. fn first_text(d: &Document) -> TextObject { all(d) @@ -1195,8 +1366,8 @@ fn multiline_text_with_advances_aligns_each_line() { } assert!(drops.iter().all(|d| (d - drops[0]).abs() < 0.01), "{drops:?}"); // Underlined and left aligned, each line's underline ends with its own advances: no bar runs on - // past either line. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))]; + // past either line (on a transparent background, SETBKMODE). + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. }))); for (align, x, second) in [(6, 2500, [15.0, 30.0]), (2, 4000, [20.0, 35.0])] { @@ -1254,8 +1425,9 @@ fn wmf_text_is_spaced_by_its_advances() { fn split_type_keeps_its_underline_and_right_to_left_order() { let mm = 72.0 / 25.4; // Underlined "Hiy" with an advance further than tracking reaches after the "H": the bar runs on - // from the end of the "H"'s underline to where "iy" starts, at 130 mm. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; + // from the end of the "H"'s underline to where "iy" starts, at 130 mm. The background is + // transparent (SETBKMODE) throughout. + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])]); let bars: Vec = @@ -1265,7 +1437,7 @@ fn split_type_keeps_its_underline_and_right_to_left_order() { assert!(b.x0 > 10.0 * mm && b.x0 < 130.0 * mm && (b.x1 - 130.0 * mm).abs() < 0.01 && b.height() < 2.0 * mm, "{b:?}"); // The "H" and the "i" before the split are tracked apart and draw a bar each: only the bar that // ends the piece runs on, from the end of the "i" to 130 mm. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))]; + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0]), ("y".to_string(), vec![140.0])]); let gaps: Vec = all(&back.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect(); @@ -1276,12 +1448,12 @@ fn split_type_keeps_its_underline_and_right_to_left_order() { let b = gaps[0].geometric_bounds().unwrap(); assert!(b.x0 > 20.0 * mm && (b.x1 - 140.0 * mm).abs() < 0.01, "{b:?}"); // Without an underline, nothing but the type. - let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; + let records = vec![(18, le(&[1])), (82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. }))); // A last advance further than tracking reaches, right aligned at 140 mm: the "H" and the "i" // start at 10 and 20 mm, and the underline runs on from the "i" to 140 mm. - let records = vec![(22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))]; + let records = vec![(18, le(&[1])), (22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0])]); let bars: Vec = diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 5c21fbb4f1..d6e114a33f 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -372,6 +372,12 @@ impl FontFace { /// `usWinDescent`, at the face's location in a variable font), in font units; `None` when the /// font has no OS/2 table or the sum isn't positive. pub fn win_cell_height(&self) -> Option { + self.win_ascent_descent().map(|(a, d)| a + d) + } + /// The face's character cell on Windows above and below the baseline (the OS/2 table's + /// `usWinAscent` and `usWinDescent`, at the face's location in a variable font), in font + /// units; `None` when the font has no OS/2 table or the sum isn't positive. + pub fn win_ascent_descent(&self) -> Option<(f64, f64)> { use skrifa::raw::TableProvider; let f = self.skrifa()?; let o = f.os2().ok()?; @@ -380,8 +386,8 @@ impl FontFace { let varied = |tag: &[u8; 4]| { f.mvar().ok().and_then(|m| m.metric_delta(skrifa::Tag::new(tag), self.location().coords()).ok()).map_or(0.0, |d| d.to_f64()) }; - let h = f64::from(o.us_win_ascent()) + varied(b"hcla") + f64::from(o.us_win_descent()) + varied(b"hcld"); - (h > 0.0 && h.is_finite()).then_some(h) + let (a, d) = (f64::from(o.us_win_ascent()) + varied(b"hcla"), f64::from(o.us_win_descent()) + varied(b"hcld")); + (a + d > 0.0 && (a + d).is_finite()).then_some((a, d)) } /// The average width of the face's characters (the OS/2 table's `xAvgCharWidth`), in font /// units; `None` when the font has no OS/2 table or gives no positive width. diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 38a8d97f69..94709cbb23 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -875,7 +875,8 @@ fn on_path_align_takes_a_variable_font_instances_em_box() { } /// A variable font's instance takes its Windows character cell from the `usWinAscent` and -/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold. +/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold, 120 above the baseline and +/// 80 below it. #[test] fn win_cell_height_takes_a_variable_font_instances_mvar() { use crate::test_fonts::{PATH_ALIGN_VARIABLE_FAMILY, path_align_font}; @@ -885,6 +886,10 @@ fn win_cell_height_takes_a_variable_font_instances_mvar() { let cell = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_cell_height()).unwrap(); let (regular, bold) = (cell("Regular"), cell("Bold")); assert!((bold - regular - 200.0).abs() < 1e-6, "Regular {regular}, Bold {bold}"); + let split = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_ascent_descent()).unwrap(); + let ((ra, rd), (ba, bd)) = (split("Regular"), split("Bold")); + assert!((ba - ra - 120.0).abs() < 1e-6 && (bd - rd - 80.0).abs() < 1e-6, "Regular {ra}/{rd}, Bold {ba}/{bd}"); + assert!((ra + rd - regular).abs() < 1e-6); } /// In vertical type, Align to Path moves the glyphs half an em, with their horizontal scale and not diff --git a/docs/mcp.md b/docs/mcp.md index 79f6183e79..95bce038ca 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9875,7 +9875,13 @@ images and point type in the font the file names. Type keeps the file's characte kerning off. On a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between and on to the end of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and -split as a single line is. An EMF that +split as a single line is. NULs at the start of the text, or after a line break, move the start of their line by their +advances. Blanks that are underlined or struck through draw their bars. A character cell runs from the font's OS/2 +`usWinAscent` above the baseline to its `usWinDescent` below it: top and bottom aligned text has the top or the +bottom of its cells at the reference point. A single line without character advances is aligned as long as its +glyphs' advances, trailing spaces included. Text drawn in the opaque background mode, which a file is in until it +sets the mode to transparent, gets one filled rectangle of the background color behind the character cells of each +line, as far as its advances reach (NULs' included), placed before the type. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. A file, or a metafile image inside it, cut short by one of the reader's limits adds one warning without a count. Each of these adds one warning, with a count: images and pattern brushes whose bitmap can't be read, which are left From 537d8ce10b0b1854cb219b5704d581d85ec84abc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:38:54 -0800 Subject: [PATCH 39/51] Contextual Task Bar: docs and test comment say a null visible toggles The opening sentence of the window.taskBar.actions entry in docs/mcp.md now says the action toggles when visible is omitted or null, as the params text does. The comment above bar_actions_refuse_bad_params now says a visible that is not true, false or null is an error. --- crates/ui-egui/src/tests/taskbar.rs | 4 ++-- docs/mcp.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index fc01daa133..1615681f57 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1674,8 +1674,8 @@ fn bar_action_ids_are_distinct() { assert_eq!(runs.len(), canvas::TASK_BAR_ACTIONS.len()); } -/// An action the bar does not have, a missing one, or a `visible` that is not true or false is an -/// error and changes nothing. +/// An action the bar does not have, a missing one, or a `visible` that is not true, false or null is +/// an error and changes nothing. #[test] fn bar_actions_refuse_bad_params() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 3121745656..1e2c93d7d6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8177,7 +8177,7 @@ and a group id the bar does not have is dropped when they are read. Another `gro be one of …", and a `visible` that is not true or false fails with "`visible` must be true or false"; either leaves every group as it is. The groups and their contents are VectorCraft's own. `window.taskBar.actions {action, visible?}` (desktop app) turns one of the Contextual Task Bar's actions or chips on -(`visible: true`), off (`false`) or toggles it (omitted), and returns `{action, visible}`. The actions are `imageTrace`, +(`visible: true`), off (`false`) or toggles it (omitted or null), and returns `{action, visible}`. The actions are `imageTrace`, `cropImage`, `removeBackground`, `removeAnchorPoints`, `join` (Connect and Join), `cutPath`, `convertToCorner`, `convertToSmooth`, `group`, `makeClippingMask`, `unite`, `expand`, `editClippingPath`, `releaseClippingMask`, `ungroup`, `isolate`, `editPath`, `releaseCompoundPath`, `createOutlines`, `convertToPointType`, `convertToAreaType`, From a5cc1d65483beddd285dc44970ea4f645afd589c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:42:24 -0800 Subject: [PATCH 40/51] Symbols: a click egui counts reads its modifiers wherever the button goes up A click that went down on New Symbol, Delete Symbol or a panel menu item and went up in a later frame within egui's click distance reads the modifiers of that release, also past the interact radius. A click within one frame is matched by where the button went down, as egui does. --- crates/ui-egui/src/panels/symbols.rs | 50 ++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 5557b7c8fe..894e10bb95 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -608,13 +608,13 @@ fn alt_at_release(ui: &Ui) -> bool { /// The modifiers held for a click on the widget whose interact rectangle is `rect`: when the /// primary button last went up in this frame as a click (the pointer stayed within egui's click -/// distance of where the button went down) over `rect` or within egui's interact radius of it -/// (egui counts a release that close as a click on the widget), as it went up (egui reports the -/// click of the last such release in the frame), else now, as for a click from the keyboard or a -/// screen reader. A release that ends a drag is not a click and is skipped, also when the drag -/// began in an earlier frame. `pointer` is whether egui reports the widget clicked by the primary -/// button; when it is false, the click came from the keyboard or a screen reader and the modifiers -/// held now are used. +/// distance of where the button went down) after going down over `rect` or within egui's interact +/// radius of it (egui gives a press that close to the widget), as it went up (egui reports the +/// click of the last such release in the frame); else, when no such click happened in this frame, +/// as the first release of the frame went up, which ends a press of an earlier frame that egui +/// counted as the click; else now. A release that ends a drag is not a click and is skipped. +/// `pointer` is whether egui reports the widget clicked by the primary button; when it is false, +/// the click came from the keyboard or a screen reader and the modifiers held now are used. fn modifiers_released_in(ui: &Ui, rect: egui::Rect, pointer: bool) -> egui::Modifiers { if !pointer { return ui.input(|i| i.modifiers); @@ -629,7 +629,7 @@ fn modifiers_released_in(ui: &Ui, rect: egui::Rect, pointer: bool) -> egui::Modi // Whether a button went down earlier in this frame; until one does, a release ends a press // of an earlier frame. let mut pressed_here = false; - // The modifiers of the release over `rect` that ends a press of an earlier frame. + // The modifiers of the release that ends a press of an earlier frame. let mut early = None; let mut found = None; for e in &i.events { @@ -644,10 +644,10 @@ fn modifiers_released_in(ui: &Ui, rect: egui::Rect, pointer: bool) -> egui::Modi } egui::Event::PointerButton { pos, button, pressed: false, modifiers } => { moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist); - let over = rect.distance_sq_to_pos(*pos) <= radius * radius; + let over = origin.is_some_and(|o| rect.distance_sq_to_pos(o) <= radius * radius); if *button == egui::PointerButton::Primary { if !pressed_here { - early = over.then_some(*modifiers); + early = early.or(Some(*modifiers)); } else if !moved && over { found = Some(*modifiers); } @@ -1347,6 +1347,36 @@ mod tests { assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); } + /// A click that goes down on the edge of New Symbol and, in the next frame, up past egui's + /// interact radius but within its click distance counts as a click on it and reads Shift and Alt + /// as the button goes up, though they are let go later in the same frame. + #[test] + fn a_click_released_past_the_interact_radius_reads_the_modifiers_as_the_button_goes_up() { + let (mut app, _) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let modifiers = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + let out = frame_held(&ctx, &mut app, vec![], modifiers); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let b = nodes + .iter() + .find(|(_, n)| n.label().is_some_and(|l| l.trim() == "New Symbol")) + .and_then(|(_, n)| n.bounds()) + .expect("a New Symbol button"); + let y = ((b.y0 + b.y1) / 2.0) as f32; + let (down, up) = (pos2(b.x0 as f32 + 0.5, y), pos2(b.x0 as f32 - 5.4, y)); + let radius = ctx.global_style().interaction.interact_radius; + let max_click_dist = ctx.options(|o| o.input_options.max_click_dist); + assert!(down.distance(up) <= max_click_dist && b.x0 as f32 - up.x > radius, "the release is a click outside the radius"); + let button = |at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(down), button(down, true)], modifiers); + let events = vec![egui::Event::PointerMoved(up), button(up, false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; + frame_held(&ctx, &mut app, events, modifiers); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + } + /// An Alt-click on Delete Symbol followed in the same frame by a drag that ends just outside /// it without Alt reads Alt from the click: the release that ends the drag is not a click. #[test] From 8993be043f90bbcce70c5916e72318ec00828fba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:42:41 -0800 Subject: [PATCH 41/51] Metafile import: keep the opaque text background to its own change This takes three behavior changes out of the branch, so that it holds the opaque background and the character cell it fills: - A single line without advances is aligned as before, without its trailing spaces. Its cells run across its glyphs' advances from where its type starts; blanks alone, which draw no type, are filled where the alignment puts them. - NULs after a line break add their advance to the character before them, as before. - Blanks that are underlined or struck through draw nothing, as before. A string of NULs alone in an underlined font now fills its cells and adds no empty type object. docs/mcp.md no longer describes the three, and docs/target-app-parity.md lists the background and the cell. The first commit's body names FontFace::win_ascent_descent as Face::win_ascent_descent. A device context starts with a background color that is typically white; the first commit states white as the playback default. --- crates/metafile/src/import/picture.rs | 56 +++++++++++++-------------- crates/metafile/src/tests/import.rs | 30 +++----------- docs/mcp.md | 6 +-- docs/target-app-parity.md | 1 + 4 files changed, 35 insertions(+), 58 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 5f596e2389..29e40ed984 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -16,13 +16,11 @@ //! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between. //! It is also carried on to the end of the last character's advance. Type on more than one line //! is placed a line at a time: each line is aligned by its own advances and split as a single -//! line is. NULs at the start, or after a line break, move the start of their line. A -//! character cell runs from the font's OS/2 usWinAscent above the baseline to its usWinDescent -//! below it, and top or bottom aligned text has the top or the bottom of its cells at the -//! reference point. One line without advances is aligned as long as its glyphs' advances, -//! trailing spaces included. Text drawn in the opaque background mode (the mode a playback -//! starts in) has one rectangle of the background color behind the character cells of each -//! line, as far as its advances reach. +//! line is. A character cell runs from the font's OS/2 usWinAscent above the baseline to its +//! usWinDescent below it, and top or bottom aligned text has the top or the bottom of its cells +//! at the reference point. Text drawn in the opaque background mode (the mode a playback starts +//! in) has one rectangle of the background color behind the character cells of each line, as +//! far as its advances reach. //! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around //! the whole picture clips nothing and is left out. //! @@ -545,22 +543,20 @@ impl Mapper { fn text(&mut self, t: &craft_metafile::Text, chain: Vec>) { // The characters without NULs, and each one's advance (text units) when the file gives // one for every character: a NUL's advance goes to the character before it, or moves the - // start when the string, or a line after a line break, begins with one. + // start when the string begins with one. let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite()); let (mut s, mut dx) = (String::new(), Vec::new()); // How far before and after its start each character's advances (its own and the NULs' - // after it) reach (text units): an advance may be negative. And before each character, - // the advance of the NULs that move its line's start, with how far they reach. - let (mut reach, mut leads) = (Vec::new(), Vec::new()); + // after it) reach (text units): an advance may be negative. And the advance of the NULs + // that move the start, with how far they reach. + let mut reach = Vec::new(); let mut lead = Lead::default(); - let breaks = |c: char| matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'); for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) { if c != '\0' { s.push(c); dx.push(d); reach.push((d.min(0.0), d.max(0.0))); - leads.push(std::mem::take(&mut lead)); - } else if let (Some(last), Some(r), false) = (dx.last_mut(), reach.last_mut(), s.chars().next_back().is_none_or(breaks)) { + } else if let (Some(last), Some(r)) = (dx.last_mut(), reach.last_mut()) { *last += d; *r = (r.0.min(*last), r.1.max(*last)); } else { @@ -571,15 +567,13 @@ impl Mapper { if !advances { dx.clear(); reach.clear(); - leads.clear(); lead = Lead::default(); } - // The leading NULs of the first line, or of a string of NULs alone. - let first = leads.first().copied().unwrap_or(lead); - // Type that draws nothing still fills its character cells on an opaque background. Blanks - // draw when they are underlined or struck through. + // The leading NULs, of the text or of a string of NULs alone. + let first = lead; + // Type that draws nothing still fills its character cells on an opaque background. let background = t.background.filter(|c| c[3] > 0); - let shows = (!s.trim().is_empty() || t.font.underline || t.font.strike) && t.color[3] > 0; + let shows = !s.trim().is_empty() && t.color[3] > 0; // A string of NULs only fills the cells across its advances. let nuls = s.is_empty() && first.reach.0 < first.reach.1 && background.is_some(); if (s.is_empty() && !nuls) || !(shows || background.is_some()) { @@ -692,23 +686,25 @@ impl Mapper { if dx.is_empty() { let mut text = whole; let laid = vectorcraft_text::layout(db, &text); - // One line is as long as its advances, its trailing blanks included, where the - // alignment puts a line that long. + // Where one line's glyphs start, and the sum of their advances, its trailing blanks + // included. let along = laid .glyphs .iter() .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); - let shift = if one { aligned(0.0, along.1, &t.h_align) - along.0 } else { 0.0 }; - text.xf = base * Affine::translate((if shift.is_finite() { shift } else { 0.0 }, drop)); + text.xf = base * Affine::translate((0.0, drop)); text.cached_bounds = Some(laid.bounds); - // The cells of one line run across its advances, those of more than one across each - // line's glyphs. NULs alone span their advances, where the alignment puts them. + // The cells of one line run across its advances, from where its type starts, or for + // blanks alone, which draw no type, where the alignment puts a line that long. Those + // of more than one line run across each line's glyphs. NULs alone span their + // advances, where the alignment puts them. let cells = if nuls { let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) } else if one { - cell_rect(along.0, along.0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; + cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) } else { cells(&laid, &s, cell, &t.h_align) }; @@ -734,11 +730,11 @@ impl Mapper { let starts: Vec = s.char_indices().map(|(at, _)| at).collect(); let count = |to: usize| starts.partition_point(|at| *at < to); let top = laid.lines.first().map_or(0.0, |l| l.baseline); - for l in &laid.lines { + for (n, l) in laid.lines.iter().enumerate() { let (from, to) = (count(l.start), count(l.end)); let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.get(from..to)) else { continue }; - // The NULs before the line's first character, at the start or after a line break. - let lead = leads.get(from).copied().unwrap_or_default().scaled(k); + // A leading NUL's advance comes before the first line only. + let lead = if n == 0 { first.scaled(k) } else { Lead::default() }; let down = l.baseline - top; self.line(&line, cs, Advances { dx, reach, lead }, if down.is_finite() { down } else { 0.0 }, &mut out); } diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 64f826b16a..aebed8a859 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -1126,22 +1126,6 @@ fn opaque_backgrounds_fill_behind_the_character_cells() { assert_eq!(kinds, [false, true, true]); let b = layer[0].geometric_bounds().unwrap(); assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 145.0 * mm).abs() < 0.01, "{b:?}"); - // A NUL after a line break moves the start of the line it begins, as it moves the first - // line's: "\0B" on a line of its own is placed and filled as the same record alone. - // Where the last text object's first glyph starts, and the left edges of the backgrounds. - let placed = |layer: &[std::sync::Arc]| { - let last = layer.iter().rev().find_map(|n| match &n.kind { - NodeKind::Text(t) => Some(glyph_xs(t).0[0]), - _ => None, - }); - let backs: Vec = - layer.iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).map(|b| b.x0).collect(); - (last.unwrap(), backs) - }; - let (b_alone, _) = placed(&opaque(arial(), "\0B", &[2000, 1000])); - let (b_together, backs) = placed(&opaque(arial(), "A\n\0B", &[1000, 0, 2000, 1000])); - assert!((b_alone - 30.0 * mm).abs() < 0.01 && (b_together - b_alone).abs() < 0.01, "{b_alone} {b_together}"); - assert!(backs.len() == 2 && backs.iter().all(|x| (x - 10.0 * mm).abs() < 0.01), "{backs:?}"); } #[test] @@ -1156,13 +1140,13 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let NodeKind::Path { path, .. } = &layer[0].kind else { panic!("a path") }; let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count(); assert_eq!(rects, 2); - // Without advances, a line is aligned as long as its advances, trailing spaces included, and - // its cells run across them: right aligned at 40 mm, "Hi " and its cells end there. + // Without advances, one line's cells run across its glyphs' advances, trailing spaces + // included: right aligned, they run from the "H" to the end of the space after the "i". let layer = aligned(2, 26, 4000, arial(), "Hi ", &[]); let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; let (xs, end) = glyph_xs(t); let b = layer[0].geometric_bounds().unwrap(); - assert!(xs.len() == 3 && (end - 40.0 * mm).abs() < 0.01, "{xs:?} {end}"); + assert!(xs.len() == 3, "{xs:?} {end}"); assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); // On more than one line, each line is aligned without its trailing spaces, and so are its // cells: right aligned at 40 mm, neither passes it. @@ -1190,11 +1174,9 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let b = layer[0].geometric_bounds().unwrap(); assert!((b.x0 - 10.0 * mm).abs() < 0.01 && b.x1 > 10.0 * mm, "{b:?}"); assert!(drawn(1, arial(), " \t", &[]).is_empty()); - // Underlined blanks draw their underline, on a transparent background too. - for mode in [1, 2] { - let layer = drawn(mode, font_of("Arial", true), " ", &[]); - assert!(layer.iter().any(|n| matches!(&n.kind, NodeKind::Text(t) if t.runs[0].style.underline)), "{mode}"); - } + // NULs alone in an underlined font fill their cells and add no type. + let layer = opaque(font_of("Arial", true), "\0", &[2000]); + assert!(layer.len() == 1 && matches!(layer[0].kind, NodeKind::Path { .. }), "{layer:?}"); // A file that never sets the mode draws in the opaque mode a playback starts in. let layer = drawn(0, arial(), "Hi", &[]); assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); diff --git a/docs/mcp.md b/docs/mcp.md index 95bce038ca..20c3c80722 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9875,11 +9875,9 @@ images and point type in the font the file names. Type keeps the file's characte kerning off. On a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between and on to the end of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and -split as a single line is. NULs at the start of the text, or after a line break, move the start of their line by their -advances. Blanks that are underlined or struck through draw their bars. A character cell runs from the font's OS/2 +split as a single line is. A character cell runs from the font's OS/2 `usWinAscent` above the baseline to its `usWinDescent` below it: top and bottom aligned text has the top or the -bottom of its cells at the reference point. A single line without character advances is aligned as long as its -glyphs' advances, trailing spaces included. Text drawn in the opaque background mode, which a file is in until it +bottom of its cells at the reference point. Text drawn in the opaque background mode, which a file is in until it sets the mode to transparent, gets one filled rectangle of the background color behind the character cells of each line, as far as its advances reach (NULs' included), placed before the type. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4c76fcbbd..24bb533a8d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2271,6 +2271,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). + - EMF and WMF text drawn in the opaque background mode, which a playback starts in ([MS-EMF 2.1.4 BackgroundMode](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/2f57054c-2b69-4303-a6f8-5aacd401f759), [SetBkMode](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-setbkmode)), gets one rectangle of the background color behind each line's character cells, placed before the type; transparent text gets none. A character cell runs from the font's OS/2 `usWinAscent` above the baseline to its `usWinDescent` below it, and top or bottom aligned text puts the top or the bottom of the cell at the reference point (`opaque_backgrounds_fill_behind_the_character_cells`, `opaque_backgrounds_reach_as_far_as_the_advances`, `wmf_text_fills_its_cells_in_the_opaque_background_mode`). - EMF and WMF import warns about what the reader leaves out or does not play as the file asks: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), with one warning without a count, and, with counts, images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). From 8b289bf6bbf374fec6a2db0c4dd15b553bcb2bd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:49:14 -0800 Subject: [PATCH 42/51] Direct Selection: Cmd/Ctrl mirrors an ordinary path's handle again The handle drag that keeps Space translation sent path.setHandle without `symmetric`, so Cmd/Ctrl no longer mirrored the opposite handle on an ordinary path. The drag now records the mirror with the handle it accepts and sends it on every preview, so the opposite handle stays mirrored while Space moves the anchor. Alt still takes priority. --- crates/engine/tests/direct_handle_mirror.rs | 23 +++++++++++++++++++++ crates/tools/src/direct.rs | 7 +++++++ 2 files changed, 30 insertions(+) diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/direct_handle_mirror.rs index d7fdfab36f..513824df8c 100644 --- a/crates/engine/tests/direct_handle_mirror.rs +++ b/crates/engine/tests/direct_handle_mirror.rs @@ -122,6 +122,29 @@ fn direct_handle_baseline_cmd_added_mid_drag_mirrors_the_opposite() { pointer(&mut s, PointerKind::Up, q, Mods { cmd: true, ..Mods::default() }); } +#[test] +fn direct_handle_cmd_mirror_holds_through_a_space_translation() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + // Space moves the anchor and both handles; the opposite handle stays mirrored. + let moved = Point::new(200.0, 190.0); + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() }); + let a = anchor(&s, id); + near(a.p, Point::new(120.0, 130.0)); + handles(a, Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth); + // Releasing Space without moving keeps the translated, mirrored handles. + pointer(&mut s, PointerKind::Drag, moved, cmd()); + handles(anchor(&s, id), Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth); + let next = Point::new(220.0, 190.0); + pointer(&mut s, PointerKind::Drag, next, cmd()); + assert_mirrored(anchor(&s, id), next, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, next, cmd()); +} + #[derive(Debug, PartialEq)] struct Snapshot { document: Value, diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 0ea7b79b08..b8394d0472 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -78,6 +78,8 @@ struct HandleDrag { offset: Vec2, space: bool, independent: bool, + /// The opposite handle mirrors this one ([`DirectSelectionTool::mirrors`]). + symmetric: bool, translated: bool, } @@ -948,6 +950,7 @@ impl Tool for DirectSelectionTool { offset: Vec2::ZERO, space: false, independent: false, + symmetric: false, translated: false, }) } @@ -1607,6 +1610,7 @@ impl DirectSelectionTool { self.guides = guides; drag.handle = q; drag.independent = ev.mods.alt; + drag.symmetric = self.mirrors(ev); } } drag.last = p; @@ -1615,6 +1619,9 @@ impl DirectSelectionTool { "id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, "x": drag.handle.x, "y": drag.handle.y, "independent": drag.independent, }); + if drag.symmetric { + params["symmetric"] = json!(true); + } if drag.translated { params["at"] = json!([drag.at.x, drag.at.y]); } From 8dd0824b3f4789a9bde7d817e9d8655ad3fab7b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:49:23 -0800 Subject: [PATCH 43/51] Metafile import: opaque backgrounds cover trailing spaces and NUL-only lines On more than one line without advances, each line's background now runs across its glyphs' advances, trailing spaces included, as a single line's does; layout leaves the trailing spaces out of the width it aligns. A first line that holds only NULs fills its cells across their advances instead of drawing nothing. --- crates/metafile/src/import/picture.rs | 30 ++++++++++++++------------- crates/metafile/src/tests/import.rs | 14 ++++++++++--- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 29e40ed984..ce9d3a902b 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -773,12 +773,10 @@ impl Mapper { /// a new piece after each cluster that tracking can't space by its advance. fn line(&mut self, line: &Line, chars: &[char], adv: Advances, down: f64, out: &mut TextOut) { let Advances { dx, reach, lead } = adv; - if chars.is_empty() { - return; - } // The line's cells, one rectangle behind every piece, run as far each way as its // advances reach (an advance may be negative), from where the leading NULs' advances - // start, which the alignment puts where it puts a line as long as its advances. + // start, which the alignment puts where it puts a line as long as its advances. A line + // of leading NULs alone fills the cells across their advances. let start = aligned(lead.by, dx.iter().sum(), line.align); let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); for (d, r) in dx.iter().zip(reach) { @@ -790,7 +788,7 @@ impl Mapper { let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace()); // A piece's type draws when it shows: blanks only when underlined or struck through. let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated); - if !draws(chars) { + if chars.is_empty() || !draws(chars) { return; } let db = vectorcraft_text::FontDb::global(); @@ -957,26 +955,30 @@ fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath { /// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above /// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout -/// places it (its trailing blanks are left out of the width layout aligns), or for a line of -/// blanks alone as wide as their advances, where `align` puts a line that long. +/// places it and across its glyphs' advances, its trailing blanks included (layout leaves them +/// out of the width it aligns), or for a line of blanks alone as wide as their advances, where +/// `align` puts a line that long. fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign) -> BezPath { - // Each line's baseline, the sum of its glyphs' advances and whether they are all blanks. - // Glyphs come line by line. - let mut lines: Vec<(usize, f64, f64, bool)> = Vec::new(); + // Each line's baseline, the sum of its glyphs' advances, how far before and after the + // reference point they reach, and whether they are all blanks. Glyphs come line by line. + type Row = (usize, f64, f64, (f64, f64), bool); + let mut lines: Vec = Vec::new(); for g in &laid.glyphs { let blank = s.get(g.byte..).and_then(|r| r.chars().next()).is_none_or(char::is_whitespace); + let (from, to) = (g.origin.x.min(g.origin.x + g.advance), g.origin.x.max(g.origin.x + g.advance)); match lines.last_mut() { - Some((line, _, width, all)) if *line == g.line => { + Some((line, _, width, reach, all)) if *line == g.line => { *width += g.advance; + *reach = (reach.0.min(from), reach.1.max(to)); *all &= blank; } - _ => lines.push((g.line, g.origin.y, g.advance, blank)), + _ => lines.push((g.line, g.origin.y, g.advance, (from, to), blank)), } } let mut bp = BezPath::new(); - for (line, y, width, blank) in lines { + for (line, y, width, reach, blank) in lines { let (x0, x1) = match laid.lines.get(line) { - Some(l) if !blank => (l.x0, l.x1), + Some(l) if !blank => (l.x0.min(reach.0), l.x1.max(reach.1)), _ => { let x0 = aligned(0.0, width, align); (x0, x0 + width) diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index aebed8a859..f7937614d4 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -1148,10 +1148,18 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let b = layer[0].geometric_bounds().unwrap(); assert!(xs.len() == 3, "{xs:?} {end}"); assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); - // On more than one line, each line is aligned without its trailing spaces, and so are its - // cells: right aligned at 40 mm, neither passes it. + // Layout aligns a line without its trailing spaces: right aligned at 40 mm, the space after + // the "i" runs on past it. On more than one line, the cells also run across the trailing + // spaces, as far as on one line. + assert!(end > 41.0 * mm, "{end}"); let b = aligned(2, 26, 4000, arial(), "Hi \nHi", &[])[0].geometric_bounds().unwrap(); - assert!((b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}"); + assert!((b.x1 - end).abs() < 0.01, "{b:?} {end}"); + // Leading NULs on a line of their own fill their cells across their advances, before the + // next line: from 10 to 30 mm. + let layer = opaque(arial(), "\0\nA", &[2000, 0, 1000]); + let first = layer[0].geometric_bounds().unwrap(); + assert!((first.x0 - 10.0 * mm).abs() < 0.01 && (first.x1 - 30.0 * mm).abs() < 0.01, "{first:?}"); + assert!(matches!(layer[1].kind, NodeKind::Path { .. }) && matches!(layer[2].kind, NodeKind::Text(_)), "{layer:?}"); // NULs whose advances go forward and back again still fill as far as they reach. let layer = opaque(arial(), "\0\0", &[1000, -1000]); assert_eq!(layer.len(), 1); From 14318099c29ff5f546cfbea9b6b23b671b45015a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:54:13 -0800 Subject: [PATCH 44/51] Metafile import: an underlined blank line's background follows its bar On more than one line without advances, a line of blanks whose underline or strikethrough draws now has its background across its glyphs, where the bar is drawn, instead of where the alignment puts a line that long. Text without a background no longer measures or builds the cells. --- crates/metafile/src/import/picture.rs | 66 +++++++++++++++------------ crates/metafile/src/tests/import.rs | 24 ++++++++++ 2 files changed, 60 insertions(+), 30 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index ce9d3a902b..226ad0380e 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -686,29 +686,31 @@ impl Mapper { if dx.is_empty() { let mut text = whole; let laid = vectorcraft_text::layout(db, &text); - // Where one line's glyphs start, and the sum of their advances, its trailing blanks - // included. - let along = laid - .glyphs - .iter() - .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); - let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); text.xf = base * Affine::translate((0.0, drop)); text.cached_bounds = Some(laid.bounds); - // The cells of one line run across its advances, from where its type starts, or for - // blanks alone, which draw no type, where the alignment puts a line that long. Those - // of more than one line run across each line's glyphs. NULs alone span their - // advances, where the alignment puts them. - let cells = if nuls { - let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; - cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) - } else if one { - let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; - cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) - } else { - cells(&laid, &s, cell, &t.h_align) - }; - out.backs.extend(self.background(&line, cells, text.xf)); + if background.is_some() { + // Where one line's glyphs start, and the sum of their advances, its trailing + // blanks included. + let along = laid + .glyphs + .iter() + .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); + let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); + // The cells of one line run across its advances, from where its type starts, or + // for blanks alone, which draw no type, where the alignment puts a line that long. + // Those of more than one line run across each line's glyphs. NULs alone span + // their advances, where the alignment puts them. + let cells = if nuls { + let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; + cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) + } else if one { + let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; + cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + } else { + cells(&laid, &s, cell, &t.h_align, shows && line.decorated) + }; + out.backs.extend(self.background(&line, cells, text.xf)); + } if shows { let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); n.opacity = opacity; @@ -778,13 +780,15 @@ impl Mapper { // start, which the alignment puts where it puts a line as long as its advances. A line // of leading NULs alone fills the cells across their advances. let start = aligned(lead.by, dx.iter().sum(), line.align); - let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); - for (d, r) in dx.iter().zip(reach) { - (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1)); - pos += d; + if line.background.is_some() { + let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); + for (d, r) in dx.iter().zip(reach) { + (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1)); + pos += d; + } + let xf = line.base * Affine::translate((0.0, line.drop + down)); + out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf)); } - let xf = line.base * Affine::translate((0.0, line.drop + down)); - out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf)); let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace()); // A piece's type draws when it shows: blanks only when underlined or struck through. let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated); @@ -956,9 +960,10 @@ fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath { /// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above /// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout /// places it and across its glyphs' advances, its trailing blanks included (layout leaves them -/// out of the width it aligns), or for a line of blanks alone as wide as their advances, where -/// `align` puts a line that long. -fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign) -> BezPath { +/// out of the width it aligns). A line of blanks alone runs across its glyphs' advances when +/// the type draws its underline or strikethrough (`decorated`), and otherwise as wide as their +/// advances, where `align` puts a line that long. +fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign, decorated: bool) -> BezPath { // Each line's baseline, the sum of its glyphs' advances, how far before and after the // reference point they reach, and whether they are all blanks. Glyphs come line by line. type Row = (usize, f64, f64, (f64, f64), bool); @@ -979,6 +984,7 @@ fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: for (line, y, width, reach, blank) in lines { let (x0, x1) = match laid.lines.get(line) { Some(l) if !blank => (l.x0.min(reach.0), l.x1.max(reach.1)), + _ if decorated => reach, _ => { let x0 = aligned(0.0, width, align); (x0, x0 + width) diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index f7937614d4..217b962dbe 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -1160,6 +1160,30 @@ fn opaque_backgrounds_reach_as_far_as_the_advances() { let first = layer[0].geometric_bounds().unwrap(); assert!((first.x0 - 10.0 * mm).abs() < 0.01 && (first.x1 - 30.0 * mm).abs() < 0.01, "{first:?}"); assert!(matches!(layer[1].kind, NodeKind::Path { .. }) && matches!(layer[2].kind, NodeKind::Text(_)), "{layer:?}"); + // An underlined line of blanks between two others draws its bar across its glyphs, and its + // cells run across the same glyphs. + let layer = opaque(font_of("Arial", true), "A\n \nB", &[]); + let (NodeKind::Path { path, .. }, NodeKind::Text(t)) = (&layer[0].kind, &layer[1].kind) else { panic!("a path and type") }; + let mut rects: Vec<(f64, f64, f64)> = Vec::new(); + for el in path.to_bezpath().elements() { + let p = match el { + vectorcraft_geom::PathEl::MoveTo(p) => { + rects.push((p.x, p.x, p.y)); + *p + } + vectorcraft_geom::PathEl::LineTo(p) => *p, + _ => continue, + }; + if let Some(r) = rects.last_mut() { + *r = (r.0.min(p.x), r.1.max(p.x), r.2.min(p.y)); + } + } + rects.sort_by(|a, b| a.2.total_cmp(&b.2)); + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let spaces: Vec<(f64, f64)> = + laid.glyphs.iter().filter(|g| g.line == 1).map(|g| ((t.xf * g.origin).x, (t.xf * g.origin).x + g.advance)).collect(); + let (from, to) = spaces.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (x0, x1)| (a.min(*x0), b.max(*x1))); + assert!(rects.len() == 3 && (rects[1].0 - from).abs() < 0.01 && (rects[1].1 - to).abs() < 0.01, "{rects:?} {spaces:?}"); // NULs whose advances go forward and back again still fill as far as they reach. let layer = opaque(arial(), "\0\0", &[1000, -1000]); assert_eq!(layer.len(), 1); From 5b25517dc12cb07a5f5d82472739a82870088178 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:59:19 -0800 Subject: [PATCH 45/51] Metafile import: one line's background reaches its furthest glyph edge A single line without advances now has its background from the nearest to the furthest edge its glyphs' advances reach, as a line of several does, instead of from the nearest edge on by the sum of the advances. --- crates/metafile/src/import/picture.rs | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 226ad0380e..1cfb3038cd 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -689,23 +689,28 @@ impl Mapper { text.xf = base * Affine::translate((0.0, drop)); text.cached_bounds = Some(laid.bounds); if background.is_some() { - // Where one line's glyphs start, and the sum of their advances, its trailing - // blanks included. - let along = laid - .glyphs - .iter() - .fold((f64::INFINITY, 0.0), |(from, width), g| (from.min(g.origin.x.min(g.origin.x + g.advance)), width + g.advance)); - let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite(); - // The cells of one line run across its advances, from where its type starts, or - // for blanks alone, which draw no type, where the alignment puts a line that long. + // How far one line's glyphs reach each way, and the sum of their advances, its + // trailing blanks included. + let along = laid.glyphs.iter().fold((f64::INFINITY, f64::NEG_INFINITY, 0.0), |(from, to, width), g| { + let (a, b) = (g.origin.x, g.origin.x + g.advance); + (from.min(a.min(b)), to.max(a.max(b)), width + g.advance) + }); + let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite() && along.2.is_finite(); + // The cells of one line run as far as its glyphs' advances reach, or for blanks + // alone, which draw no type, where the alignment puts a line that long. // Those of more than one line run across each line's glyphs. NULs alone span // their advances, where the alignment puts them. let cells = if nuls { let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) } else if one { - let x0 = if shows { along.0 } else { aligned(0.0, along.1, &t.h_align) }; - cell_rect(x0, x0 + along.1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + let (x0, x1) = if shows { + (along.0, along.1) + } else { + let x0 = aligned(0.0, along.2, &t.h_align); + (x0, x0 + along.2) + }; + cell_rect(x0, x1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) } else { cells(&laid, &s, cell, &t.h_align, shows && line.decorated) }; From ff0b835509f581622b939323707b719ba230e857 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:59:50 -0800 Subject: [PATCH 46/51] Part of #5941: drop-down lists stop above the bottom bars A drop-down list that did not fit on either side of its field was moved up only as far as the window's bottom edge, so it could cover the status bar, the hint bar and a Control bar docked at the bottom. The list now measures the room below its field to those bars, as other menus do (#2086), and a list too tall for either side moves up until it ends at them. Its right-to-left alignment now follows the field's own style. The Gradient panel's Presets menu change is taken out of this branch; the menus that set a fixed minimum width get their own fix. Tests: - a_dropdown_list_stops_above_the_bottom_bars - a_dropdown_option_cut_short_shows_its_full_name_on_hover, which checks the tooltip of an option cut short in a list narrowed to the window --- crates/ui-egui/src/dialogs/tests_export.rs | 2 +- crates/ui-egui/src/panels/gradient.rs | 2 +- crates/ui-egui/src/panels/gradient/tests.rs | 14 --- crates/ui-egui/src/widgets/dropdowns.rs | 32 +++--- crates/ui-egui/src/widgets/look_tests.rs | 116 ++++++++++++++++++++ 5 files changed, 135 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index 51258fbfa9..6d388f7950 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -359,7 +359,7 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format /// #5941: the Format list stopped at the room on one side of its field, so a window with room for /// every format still cut the list short. In windows of 1280×900 and 1000×856 the list shows every -/// built-in format whole, the greyed-out DWG row after them included, inside the window, without a +/// built-in format whole, the grayed-out DWG row after them included, inside the window, without a /// scroll bar. A plug-in format that another test adds or removes meanwhile is not counted. #[test] fn the_format_list_shows_every_format_when_the_window_has_room() { diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index adf4dd723f..7baaa062ab 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -466,7 +466,7 @@ fn presets_row(app: &mut VectorcraftApp, ui: &mut Ui, g: Option<&GradientPaint>) /// the name of the one clicked. fn preset_list(app: &VectorcraftApp, ui: &mut Ui, shown: &str) -> Option { let t = Tokens::get(ui.ctx()); - widgets::menu_min_width(ui, 200.0); + ui.set_min_width(200.0); let mut chosen = None; // The library of the rows drawn last (`Some(None)`: the saved presets). let mut library: Option> = None; diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index e4871b0886..bbf833b1aa 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -797,20 +797,6 @@ fn text_at(texts: &[(String, Pos2)], s: &str) -> Option { texts.iter().find(|(t, _)| t.trim_start() == s).map(|(_, at)| *at) } -/// #5941: in a window narrower than the Presets menu's 200 pt rows, the menu stays inside the window, -/// so its scroll bar shows. -#[test] -fn the_presets_menu_stays_inside_a_narrow_window() { - let mut app = app(json!({"gradient": {}})); - let paint = current(&app).expect("a gradient fill"); - let mut window = PopupWindow::new(&mut app, 300.0, move |app, ui| presets_row(app, ui, Some(&paint))); - window.resize(&mut app, 190.0); - let label = window.text("Presets:").expect("the Presets row"); - window.click(&mut app, egui::pos2(label.right() + 40.0, label.center().y)); - let popup = window.popup().expect("the menu is open"); - assert!(popup.left() >= 0.0 && popup.right() <= 190.0, "the menu {popup:?} is inside the window"); -} - /// The Presets menu lists the presets by library (theme) and applies the one chosen to the /// gradient behind the active proxy, as one undo step; the menu then shows that preset. #[test] diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index e05235b411..b440007a80 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -320,8 +320,9 @@ fn combo_button<'a>(ui: &mut Ui, button_id: egui::Id, current: impl egui::IntoAt /// The list of [`combo_atoms_named`] while it is open, drawn by `list` in a popup of its own that /// opens from `button` and takes the whole list whenever the window has room for it (#5941): below -/// the button when it fits there, above it when it fits there instead, and otherwise shifted from -/// below into the window, over the button. A list taller than the window scrolls. A click closes +/// the button when it fits there, above it when it fits there instead, and otherwise moved up from +/// below, over the button, until it ends at the bottom bars. It stays above the bottom bars +/// ([`menu_floor`]), and a list taller than the room above them scrolls. A click closes /// the list, except a click on its scroll bar, which scrolls it. Returns what `list` returned, or /// `None` while the list is closed. fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> Option { @@ -339,30 +340,31 @@ fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> let close = if on_bar { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; let popup = egui::Popup::menu(button).id(id).width(button.rect.width()).style(style.clone()).close_behavior(close); let screen = ctx.content_rect(); + // The list stops above the bottom bars, as other menus do (#2086). + let floor = menu_floor(ctx).min(screen.bottom()); // The room on each side of the rect the popup opens from: the part of the button in view. let anchor = popup.get_anchor_rect().unwrap_or(button.rect); - let below = screen.bottom() - anchor.bottom(); + let below = floor - anchor.bottom(); let above = anchor.top() - screen.top(); // The list's size from its last pass: egui lays a popup out unseen on the pass it opens, so the // list is measured before it is placed. A right-to-left layout lines the list up with the // button's right edge, as egui's menus do. - let rtl = ctx.global_style().right_to_left; - let align = match popup.get_expected_size() { - Some(size) if size.y > below && size.y <= above => { - if rtl { - egui::RectAlign::TOP_END - } else { - egui::RectAlign::TOP_START - } + let rtl = ui.style().right_to_left; + let expected = popup.get_expected_size(); + let (align, popup) = match expected { + Some(size) if size.y > below && size.y <= above => (if rtl { egui::RectAlign::TOP_END } else { egui::RectAlign::TOP_START }, popup), + // A list too tall for either side moves up from below until it ends at the floor. + Some(size) if size.y > below => { + let top = (floor - size.y).max(screen.top()); + let from = Rect::from_min_max(egui::pos2(anchor.left(), top), egui::pos2(anchor.right(), top)); + (if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup.anchor(from)) } - // egui keeps a popup inside the window, so a list too tall for either side moves up. - _ if rtl => egui::RectAlign::BOTTOM_END, - _ => egui::RectAlign::BOTTOM_START, + _ => (if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup), }; let mut popup_style = (*ctx.global_style()).clone(); style.apply(&mut popup_style); let margins = egui::Frame::popup(&popup_style).total_margin().sum(); - let height = (screen.height() - margins.y).max(ui.spacing().interact_size.y); + let height = (floor - screen.top() - margins.y).max(ui.spacing().interact_size.y); // A list that was wider than the window keeps its scroll bar in view: until it closes, it is no // wider than it measured or than the window, its names cut short and shown in full on hover. // Only a size measured while the list is open counts: egui keeps the last one after it closes. diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 77c9af796c..286be3f10c 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -971,6 +971,67 @@ fn a_dropdown_list_shows_every_option_when_the_window_has_room() { } } +// #5941: a drop-down list stops above the bottom bars, as other menus do (#2086). In a 700 pt window +// whose bars start at 640 pt, the list opens below a field near the top, and from a field in the +// middle it moves up over the field until it ends at the bars; each time every option shows whole. +#[test] +fn a_dropdown_list_stops_above_the_bottom_bars() { + let items: Vec = (0..20).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let floor = 640.0; + for above in [16.0, 300.0] { + let case = format!("field {above} pt down"); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + set_menu_floor(ui.ctx(), floor); + ui.add_space(above); + field.set(ui.horizontal(|ui| dropdown_names(ui, "floor-list", labels[0], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 700.0)); + let mut run = |time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + popup.take() + }; + run(0.0, vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(0.1, vec![egui::Event::PointerMoved(at), press(true)]); + run(0.2, vec![press(false)]); + run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = run(f64::from(i) * 0.1, vec![]); + } + let list = ctx + .memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + .expect("the list is open"); + assert!(list.top() >= 0.0 && list.bottom() <= floor + 0.5, "{case}: the list {list:?} ends above the bars at {floor}"); + let mut texts = vec![]; + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)), + _ => {} + } + } + clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts)); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}"); + } +} + // #5941: a click on the scroll bar's track of an open drop-down list scrolls it and leaves it open, // so an option it scrolled into view can be picked. A list closed by that click would open again // with its current option in view. @@ -1207,6 +1268,61 @@ fn a_dropdown_list_wider_than_the_window_keeps_its_scroll_bar_in_view() { assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full beside the bar: {texts:?}"); } +// #5941: in a drop-down list narrowed to the window, an option whose name is cut short shows the +// full name in a tooltip while the pointer rests on it. +#[test] +fn a_dropdown_option_cut_short_shows_its_full_name_on_hover() { + let mut items: Vec = (0..10).map(|i| format!("Option {i:02}")).collect(); + items[1] = "Option 01, whose name is much wider than this window".into(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + field.set(ui.horizontal(|ui| dropdown_names(ui, "hover-list", labels[0], &labels, 160.0)).response.rect); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0)); + let mut time = 0.0; + // Every text painted, on any layer, with its rect and whether it was cut short. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let mut texts = vec![]; + fn flat(s: &egui::Shape, out: &mut Vec<(String, Rect, bool)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), t.galley.elided)), + _ => {} + } + } + out.shapes.iter().for_each(|c| flat(&c.shape, &mut texts)); + texts + }; + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let mut texts = vec![]; + for _ in 0..6 { + texts = run(vec![]); + } + let full = |texts: &[(String, Rect, bool)]| texts.iter().any(|(s, _, elided)| !*elided && s == labels[1]); + assert!(!full(&texts), "the long name is not shown in full before the hover: {texts:?}"); + let row = texts + .iter() + .find(|(s, _, elided)| *elided && s.starts_with("Option 01")) + .map(|(_, r, _)| r.center()) + .unwrap_or_else(|| panic!("the long name is cut short: {texts:?}")); + run(vec![egui::Event::PointerMoved(row)]); + for _ in 0..10 { + texts = run(vec![]); + } + assert!(full(&texts), "the full name shows on hover: {texts:?}"); +} + /// Enter on text that reads as no number in a range field refuses it as a unit field does: the /// field flashes and an open dialog is not confirmed with the old value. #[test] From 507b3d2d68711f58aabb4e06548ece23cd2ec170 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:00:40 -0800 Subject: [PATCH 47/51] Color Wheel: end an OKLCH row drag when the working RGB space stops being sRGB The OKLCH rows turn gray when Edit > Color Settings picks a working RGB space other than sRGB, so a drag on one reports no release. The panel now keeps that drag's preview as one undo step and ends the interaction, as it does when the rows are hidden or replaced. The ui.colorWheel tests now expect the harmony, harmonyRule, vision and sliders keys that main and this branch report together. --- crates/ui-egui/src/panels/color_wheel.rs | 7 +-- .../ui-egui/src/panels/tests_color_wheel.rs | 46 ++++++++++++++++++- .../src/panels/tests_color_wheel_vision.rs | 5 +- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index a2901b6460..6cf8d5dc24 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -846,10 +846,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { picked_hsl = hsl_rows(app, ui, &tgt, color, &cms); } } - // A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`) reports no release: - // its preview is kept as one undo step and the interaction ends. + // A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`), or turned gray + // (OKLCH rows after the working RGB space stops being sRGB), reports no release: its preview is + // kept as one undo step and the interaction ends. let live = pstate::>(ui.ctx(), ROWS_LIVE); - if live.is_some_and(|rows| rows != app.ui.color_wheel.sliders) { + if live.is_some_and(|rows| rows != app.ui.color_wheel.sliders || (rows == Sliders::Oklch && !cms.rgb_is_srgb())) { if app.session.in_interaction() && let Err(e) = app.session.commit_interaction() { diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index f13f78e8e2..e7ac9d84b3 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -749,6 +749,49 @@ fn oklch_sliders_are_gray_after_the_working_space_changes() { assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); } +/// A drag on an OKLCH row during which Edit › Color Settings picks a working RGB space other than +/// sRGB keeps the color the drag previewed as one undo step and leaves no interaction open, though +/// the gray rows report no release. +#[test] +fn a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_P3_DRAG"; + 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::a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step", + "--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 mut h = oklch_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "Lightness").rect(); + let undo = undo_len(h.state()); + press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE); + for _ in 0..2 { + h.event(Event::PointerMoved(on_rail(rail, 0.25))); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "the drag previews"); + let previewed = fill(h.state()); + h.state_mut().run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + h.run_steps(2); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); + press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE); + assert!(!h.state().session.in_interaction(), "the interaction ended"); + assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1)); +} + /// A CMYK fill's L, C and H are those of its display color, not of its naive separation. #[test] fn a_cmyk_fills_oklch_is_that_of_its_display_color() { @@ -1029,7 +1072,8 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none")); assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hwb"})).unwrap_err(), "`sliders` must be none, oklch or hsl"); let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); - assert_eq!(got, json!({"view": "box", "channel": "red", "sliders": "oklch"})); + let want = json!({"view": "box", "channel": "red", "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch"}); + assert_eq!(got, want); let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hwb"})).unwrap_err(); assert_eq!(e, "`sliders` must be none, oklch or hsl"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs index 7c07b71f90..31bb3bc48b 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs @@ -225,8 +225,7 @@ fn the_panel_menu_turns_the_row_on_and_off() { #[test] fn ui_color_wheel_sets_and_reads_the_settings() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let settings = - |view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision}); + let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none"}); assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false)); assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true)); assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["vision"], true); @@ -237,7 +236,7 @@ fn ui_color_wheel_sets_and_reads_the_settings() { assert_eq!(app.run("ui.colorWheel", json!(5)).unwrap_err(), "the params must be an object, not 5"); assert_eq!( app.run("ui.colorWheel", json!({"visoin": false})).unwrap_err(), - "unknown parameter `visoin`; the command takes: view, channel, harmony, harmonyRule, vision" + "unknown parameter `visoin`; the command takes: view, channel, sliders, harmony, harmonyRule, vision" ); assert!(app.ui.color_wheel.vision); assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true); From 88cac70e8b53b1c81e372b3277d5e03bb1d75a18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:23:20 -0800 Subject: [PATCH 48/51] Color Wheel: find the largest OKLCH chroma on every stretch of the ray The chromas sRGB holds along a ray of fixed lightness and hue can come in several stretches, and the search looked past the first one only near a primary color's hue. Near black the gamut slack opens stretches at other hues: at L 0.02 and H 242 degrees the ray fits up to about 0.022 but the search stopped near 0.012, so the chroma tick sat too low and a pick past the gamut lost more chroma than it had to. Each linear sRGB channel is a cubic in the chroma, so the search now takes the chromas where a channel meets a gamut bound, between each cubic's turning points, and keeps the largest one that fits. A test compares the result with a scan of the ray at 720 lightness and hue pairs. --- crates/color/src/libraries.rs | 10 ++- crates/color/src/oklab.rs | 121 ++++++++++++++++++++-------------- 2 files changed, 80 insertions(+), 51 deletions(-) diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index 9c756256a3..c2946d92a2 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -103,16 +103,20 @@ pub fn builtin_library(id: &str) -> Option> { /// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does /// (). pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { + oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) }) +} + +/// Linear sRGB of OKLab `(l, a, b)`, unclamped. +pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b; let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b; let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b; let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_); - let lin = [ + [ 4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3, -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3, -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3, - ]; - lin.map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) }) + ] } /// OKLab `[l, a, b]` of a colour's display RGB. diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 1df3c4b1df..31500d1ac5 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -3,7 +3,7 @@ //! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take //! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`]. -use crate::libraries::{oklab_to_srgb, srgb_to_oklab}; +use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab}; /// The chroma CSS reads as 100%. pub const CHROMA_FULL: f64 = 0.4; @@ -41,65 +41,75 @@ pub fn max_chroma(l: f64, h: f64) -> f64 { largest_fitting_chroma(l, h, f64::INFINITY) } -/// The primary and secondary colors of sRGB: the corners of its cube next to black. -const PRIMARIES: [[f32; 3]; 6] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0]]; - /// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or /// outside black and white. +/// +/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of +/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313, +/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic +/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The +/// search finds each such chroma between the cubic's turning points and takes the largest one that +/// fits. fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 { if !(l > 0.0 && l < 1.0) || !h.is_finite() { return 0.0; } - let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h)); - // An edge of the chromas sRGB holds, searched no higher than `limit`, so `lo` always fits. - let (mut lo, mut hi) = (0.0, limit.min(0.5)); - for _ in 0..40 { - let mid = (lo + hi) / 2.0; - if fits(mid) { lo = mid } else { hi = mid } + let top = limit.min(0.5); + if top <= 0.0 { + return 0.0; } - // Past that edge the ray can come back into sRGB near a line from black to a primary or - // secondary color. Such a line is straight in Oklab, so it keeps that color's hue and its - // chroma grows with its lightness. At the lightness and hue of blue, for example, the ray leaves - // sRGB at a chroma of about 0.266 and meets blue itself at about 0.313; at L 0.44 and a hue - // 0.01° past blue's, a second stretch runs from about 0.3042 to 0.3048. Each such stretch ends - // at or just below the line's chroma, so the search walks down from there in small steps to the - // first chroma that fits and then finds the stretch's end between it and the step above. - let past = PRIMARIES.iter().filter_map(|rgb| { - let [pl, a, b] = srgb_to_oklab(*rgb); - let edge = l / pl * a.hypot(b); - let off = (h - b.atan2(a).to_degrees()).rem_euclid(360.0); - if l > pl || edge <= lo || off.min(360.0 - off) > NEAR_PRIMARY_HUE { - return None; - } - let start = edge.min(limit); - let mut c = start; - while c > lo && start - c <= PAST_WALK { - if fits(c) { - let (mut inside, mut outside) = (c, (c + PAST_STEP).min(start)); - if outside > inside && !fits(outside) { - for _ in 0..20 { - let mid = (inside + outside) / 2.0; - if fits(mid) { inside = mid } else { outside = mid } - } - } else { - inside = outside; + let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h)); + if fits(top) { + return top; + } + let (sin, cos) = h.to_radians().sin_cos(); + let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin); + // The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s. + let s = top / 3.0; + let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)]; + let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)]; + let mut ends = vec![0.0]; + for ch in 0..3 { + let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]]; + let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0); + let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0]; + let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0]; + // The cubic rises or falls on each stretch between its turning points. + let mut cuts = vec![0.0, 3.0]; + cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0)); + cuts.sort_by(f64::total_cmp); + ends.extend(cuts.iter().map(|t| t * s)); + for w in cuts.windows(2) { + for bound in bounds { + let (mut a, mut b) = (w[0], w[1]); + let fa = p(a) - bound; + if fa * (p(b) - bound) > 0.0 { + continue; } - return Some(inside); + for _ in 0..60 { + let mid = (a + b) / 2.0; + if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid } + } + ends.extend([a * s, b * s]); } - c -= PAST_STEP; } - None - }); - past.fold(lo.min(limit), f64::max) + } + ends.sort_by(|a, b| b.total_cmp(a)); + ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0) } -/// How near a primary or secondary color's hue, in degrees, the ray must pass for -/// [`largest_fitting_chroma`] to look past the first edge. -const NEAR_PRIMARY_HUE: f64 = 2.0; -/// The step of that walk. -const PAST_STEP: f64 = 2e-4; -/// How far below the line's chroma that walk goes. -const PAST_WALK: f64 = 0.06; +/// The real roots of `a t² + b t + c`. +fn turning_points(a: f64, b: f64, c: f64) -> Vec { + if a.abs() < 1e-15 { + return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] }; + } + let disc = b * b - 4.0 * a * c; + if disc < 0.0 { + return Vec::new(); + } + let r = disc.sqrt(); + vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)] +} /// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: /// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that @@ -229,6 +239,21 @@ mod tests { assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}"); } + /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at + /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from + /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012). + #[test] + fn the_largest_chroma_is_never_below_a_scan_of_the_ray() { + let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max); + assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0)); + for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] { + for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) { + let max = max_chroma(l, h); + assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h)); + } + } + } + #[test] fn black_white_and_bad_numbers_hold_no_chroma() { assert_eq!(max_chroma(0.0, 30.0), 0.0); From c4c1495c044ad24b516e08b02b05c5546534e4b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:23:27 -0800 Subject: [PATCH 49/51] Direct Selection: Alt and Cmd/Ctrl apply while Space moves a handle A handle drag kept the Alt and Cmd/Ctrl state it had before Space was pressed, so pressing Alt or releasing Cmd/Ctrl during a Space translation changed nothing until Space was released and the pointer moved. Both modifiers are now read on every drag event. The Space translation still keeps the accepted handle position. --- crates/engine/tests/direct_handle_mirror.rs | 20 ++++++++++++++++++++ crates/tools/src/direct.rs | 5 +++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/direct_handle_mirror.rs index 513824df8c..30326d8e74 100644 --- a/crates/engine/tests/direct_handle_mirror.rs +++ b/crates/engine/tests/direct_handle_mirror.rs @@ -145,6 +145,26 @@ fn direct_handle_cmd_mirror_holds_through_a_space_translation() { pointer(&mut s, PointerKind::Up, next, cmd()); } +#[test] +fn direct_handle_modifiers_changed_during_a_space_translation_apply_at_once() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + press_handle(&mut s, Point::new(180.0, 100.0)); + pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd()); + let moved = Point::new(200.0, 190.0); + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() }); + handles(anchor(&s, id), Point::new(40.0, 70.0), moved, AnchorKind::Smooth); + // Releasing Cmd while Space is held gives the opposite handle its own length again. + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..Mods::default() }); + let a = anchor(&s, id); + near(a.p, Point::new(120.0, 130.0)); + handles(a, Point::new(80.0, 100.0), moved, AnchorKind::Smooth); + // Alt while Space is held leaves the opposite handle where the translation put it. + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, alt: true, ..cmd() }); + handles(anchor(&s, id), Point::new(70.0, 130.0), moved, AnchorKind::Corner); + pointer(&mut s, PointerKind::Up, moved, Mods { alt: true, ..cmd() }); +} + #[derive(Debug, PartialEq)] struct Snapshot { document: Value, diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index b8394d0472..c14dfd4c2b 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1609,10 +1609,11 @@ impl DirectSelectionTool { self.snapped = snapped(q.to_vec2(), input.to_vec2(), ev.mods.shift, &guides); self.guides = guides; drag.handle = q; - drag.independent = ev.mods.alt; - drag.symmetric = self.mirrors(ev); } } + // Alt and Cmd/Ctrl take effect on every event, while Space is held too. + drag.independent = ev.mods.alt; + drag.symmetric = self.mirrors(ev); drag.last = p; drag.space = ev.mods.space; let mut params = json!({ From e6a4fbc523b1526852afc90ffc17c86f4d989bce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:52:49 -0800 Subject: [PATCH 50/51] Color Wheel: the slider rows show a color outside sRGB clipped to sRGB A fill whose display RGB lies outside 0 to 1 (an RGB fill given as [1.6, 0.2, -0.4], for example) showed in the HSL and OKLCH rows with the components of the unclipped color, so an edit started from a color other than the one the panel shows. The rows now take their values from the display color clipped to sRGB. --- crates/ui-egui/src/panels/color_wheel.rs | 14 ++++++++++---- crates/ui-egui/src/panels/tests_color_wheel.rs | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 6cf8d5dc24..78f10e0cf6 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -581,7 +581,13 @@ fn replaced(app: &VectorcraftApp, tgt: &Target, behind: bool) -> Option { /// then displayed as the sRGB `shown`: `lch` while `c` still displays as `shown` (a chroma past the /// gamut and the hue of a gray stay), else `c`'s own. pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; 3]) -> [f64; 3] { - if cms.display_rgb(c) == shown { lch } else { oklab::to_oklch(cms.display_rgb(c)) } + if cms.display_rgb(c) == shown { lch } else { oklab::to_oklch(clipped_rgb(cms, c)) } +} + +/// The display sRGB of `c` through `cms` clipped to sRGB: the color the slider rows show and edit +/// for a color outside sRGB. +fn clipped_rgb(cms: &Cms, c: &Color) -> [f32; 3] { + cms.display_rgb(c).map(|v| v.clamp(0.0, 1.0)) } /// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed. @@ -621,7 +627,7 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: let enabled = color.is_some() && cms.rgb_is_srgb(); let lch = match (color, recall::<[f64; 3]>(app, ui, OKLCH_MEMORY, tgt, color, cms)) { (Some(c), Some((shown, lch))) => remembered_oklch(cms, &c, shown, lch), - (Some(c), _) => oklab::to_oklch(cms.display_rgb(&c)), + (Some(c), _) => oklab::to_oklch(clipped_rgb(cms, &c)), (None, _) => [0.0; 3], }; // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. @@ -707,7 +713,7 @@ const TRACK_SAMPLES: usize = 128; /// then displayed as the sRGB `shown`: `hsl` while `c` still displays as `shown` (the hue of a gray /// and the saturation of black and white stay), else `c`'s own. pub(crate) fn remembered_hsl(cms: &Cms, c: &Color, shown: [f32; 3], hsl: [f32; 3]) -> [f32; 3] { - if cms.display_rgb(c) == shown { hsl } else { rgb_to_hsl(cms.display_rgb(c)) } + if cms.display_rgb(c) == shown { hsl } else { rgb_to_hsl(clipped_rgb(cms, c)) } } /// The color a track shows at HSL `hsl`. @@ -725,7 +731,7 @@ pub(crate) fn hsl_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: O let enabled = color.is_some(); let hsl = match (color, recall::<[f32; 3]>(app, ui, HSL_MEMORY, tgt, color, cms)) { (Some(c), Some((shown, hsl))) => remembered_hsl(cms, &c, shown, hsl), - (Some(c), _) => rgb_to_hsl(cms.display_rgb(&c)), + (Some(c), _) => rgb_to_hsl(clipped_rgb(cms, &c)), (None, _) => [0.0; 3], }; // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. The diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index e7ac9d84b3..103e3f4823 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -1095,6 +1095,24 @@ fn a_hue_on_a_gray_color_leaves_its_paint_gray() { } } +/// For a fill outside sRGB, the HSL and OKLCH rows show the components of its display color +/// clipped to sRGB, the color the panel shows, not of the unclipped one. +#[test] +fn the_rows_show_a_color_outside_srgb_clipped_to_srgb() { + let rgb = json!([1.6, 0.2, -0.4]); + let raw = cms::active().display_rgb(&fill(&app(rgb.clone()))); + let clipped = raw.map(|v| v.clamp(0.0, 1.0)); + assert_ne!(raw, clipped, "the fill lies outside sRGB"); + let want_hsl = (f64::from(vectorcraft_color::rgb_to_hsl(clipped)[2]) * 100.0).round(); + assert_ne!(want_hsl, (f64::from(vectorcraft_color::rgb_to_hsl(raw)[2]) * 100.0).round(), "the unclipped lightness differs"); + let h = hsl_harness(app(rgb.clone())); + assert_eq!(oklch_slider(&h, "HSL Lightness").accesskit_node().numeric_value(), Some(want_hsl)); + let want_l = (vectorcraft_color::oklab::to_oklch(clipped)[0] * 100.0).round(); + assert_ne!(want_l, (vectorcraft_color::oklab::to_oklch(raw)[0] * 100.0).round(), "the unclipped OKLCH lightness differs"); + let h = oklch_harness(app(rgb)); + assert_eq!(oklch_slider(&h, "Lightness").accesskit_node().numeric_value(), Some(want_l)); +} + /// The hue given to a gray is dropped once the panel shows another color, so the same gray applied /// again later shows its own hue, 0°. #[test] From abcb2a40b7adb7f8adc0b6ae742d296864b1ef21 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 23:36:30 +0700 Subject: [PATCH 51/51] xtask: pdf-deps expects the craft-libs pin main moved to in #8703 --- xtask/src/pdf_deps.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index e0877302a9..0b9653830a 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b"; +const REV: &str = "50b0ee7bf811e363b5f238382b5c77318cf33e46"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),