From b04780190396e8d35c0ffa4129401d4be94353f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:25:14 -0800 Subject: [PATCH 01/25] Command Palette: keys in one frame move the highlight in the order pressed Page Down, Up and the other keys that move the highlighted result now apply in the order they were pressed, so Page Down then Up in one frame lands one row above the page rather than on the last result. A scroll by any amount, not only steps over half a point, moves the highlight onto a row in view, so slow scrolling cannot carry the highlighted result out of sight while Enter still runs it. --- crates/ui-egui/src/palette.rs | 122 +++++++++++++++++++++++++--------- 1 file changed, 89 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 9219328a1f..20186a555f 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -411,29 +411,30 @@ fn footer(listed: usize, total: usize) -> String { } } -/// How many times each key that moves the highlighted result was pressed this frame. +/// The keys that move the highlighted result, in the order they were pressed this frame. #[derive(Default)] -struct Moves { - down: usize, - up: usize, - page_down: usize, - page_up: usize, -} +struct Moves(Vec); impl Moves { + /// The keys that move the highlighted result. + const KEYS: [egui::Key; 4] = [egui::Key::ArrowDown, egui::Key::ArrowUp, egui::Key::PageDown, egui::Key::PageUp]; + fn any(&self) -> bool { - self.down + self.up + self.page_down + self.page_up > 0 + !self.0.is_empty() } - /// The highlighted result of `n` after these moves from `sel`, a page being `page` rows: Up and - /// Down wrap at the ends, Page Up and Page Down stop at them. + /// The highlighted result of `n` after these moves from `sel`, taken in the order they were + /// pressed, a page being `page` rows: Up and Down wrap at the ends, Page Up and Page Down stop + /// at them. fn apply(&self, sel: usize, n: usize, page: usize) -> usize { let Some(last) = n.checked_sub(1) else { return 0 }; - let sel = sel.min(last); - let sel = (sel + self.down % n) % n; - let sel = (sel + n - self.up % n) % n; - let sel = sel.saturating_add(page.saturating_mul(self.page_down)).min(last); - sel.saturating_sub(page.saturating_mul(self.page_up)) + self.0.iter().fold(sel.min(last), |sel, key| match key { + egui::Key::ArrowDown => (sel + 1) % n, + egui::Key::ArrowUp => (sel + last) % n, + egui::Key::PageDown => sel.saturating_add(page).min(last), + egui::Key::PageUp => sel.saturating_sub(page), + _ => sel, + }) } } @@ -569,13 +570,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut moves = Moves::default(); if n > 0 && !list_open { ctx.input_mut(|i| { - let mut key = |k| i.count_and_consume_key(egui::Modifiers::NONE, k); - moves = Moves { - down: key(egui::Key::ArrowDown), - up: key(egui::Key::ArrowUp), - page_down: key(egui::Key::PageDown), - page_up: key(egui::Key::PageUp), - }; + i.events.retain(|e| match e { + egui::Event::Key { key, pressed: true, modifiers, .. } + if Moves::KEYS.contains(key) && modifiers.matches_logically(egui::Modifiers::NONE) => + { + moves.0.push(*key); + false + } + _ => true, + }); }); } let screen = ctx.content_rect(); @@ -683,9 +686,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); let before = offset; offset = out.state.clamped_offset().y; - // After a scroll with the wheel or the scroll bar, the highlight moves to the - // nearest row in view, so Enter runs a result that can be seen. - if !new_query && !moves.any() && (offset - before).abs() > 0.5 { + // After a scroll with the wheel or the scroll bar, by any amount, the highlight + // moves to the nearest row in view, so Enter runs a result that can be seen. + if !new_query && !moves.any() && (offset - before).abs() > 0.0 { sel = nearest_in_view(sel, offset, view, n); } }); @@ -1917,14 +1920,17 @@ mod tests { /// Down wrap. #[test] fn page_keys_move_by_a_page_without_wrapping() { - let moves = |down, up, page_down, page_up| Moves { down, up, page_down, page_up }; - assert_eq!(moves(0, 0, 1, 0).apply(0, 50, 12), 12); - assert_eq!(moves(0, 0, 1, 0).apply(45, 50, 12), 49); - assert_eq!(moves(0, 0, 0, 1).apply(5, 50, 12), 0); - assert_eq!(moves(1, 0, 0, 0).apply(49, 50, 12), 0); - assert_eq!(moves(0, 1, 0, 0).apply(0, 50, 12), 49); - assert_eq!(moves(3, 0, 0, 0).apply(48, 50, 12), 1); - assert_eq!(moves(1, 0, 0, 0).apply(0, 0, 12), 0); + use egui::Key::{ArrowDown, ArrowUp, PageDown, PageUp}; + let moves = |keys: &[egui::Key]| Moves(keys.to_vec()); + assert_eq!(moves(&[PageDown]).apply(0, 50, 12), 12); + assert_eq!(moves(&[PageDown]).apply(45, 50, 12), 49); + assert_eq!(moves(&[PageUp]).apply(5, 50, 12), 0); + assert_eq!(moves(&[ArrowDown]).apply(49, 50, 12), 0); + assert_eq!(moves(&[ArrowUp]).apply(0, 50, 12), 49); + assert_eq!(moves(&[ArrowDown; 3]).apply(48, 50, 12), 1); + assert_eq!(moves(&[ArrowDown]).apply(0, 0, 12), 0); + assert_eq!(moves(&[PageDown, ArrowUp]).apply(0, 50, 12), 11, "in the order pressed"); + assert_eq!(moves(&[ArrowUp, PageDown]).apply(0, 50, 12), 49, "in the order pressed"); let mut open = Open::new("select", WINDOW); open.press(egui::Key::PageDown, 1); assert_eq!(open.highlighted(), VISIBLE_ROWS); @@ -1976,6 +1982,56 @@ mod tests { assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); } + /// Page Down, Up and Enter pressed in one frame move the highlight in that order, and Enter + /// runs the result they moved it to. + #[test] + fn keys_in_one_frame_move_the_highlight_in_the_order_pressed() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + assert!(listed.len() > VISIBLE_ROWS, "{listed:?}"); + let panel = listed[VISIBLE_ROWS - 1].strip_prefix("panel:").expect("a panel's result").to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + open.frame(vec![key(egui::Key::PageDown), key(egui::Key::ArrowUp), key(egui::Key::Enter)]); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + + /// A scroll in steps of less than half a point a frame still moves the highlight onto a row in + /// view once the highlighted row leaves it. + #[test] + fn a_scroll_in_small_steps_keeps_the_highlight_in_view() { + let mut open = Open::new("select", WINDOW); + let nodes = open.frame(vec![]); + let first = rows(&nodes).into_iter().next().unwrap(); + let at = egui::pos2(open.popup().center().x, ((first.2 + first.3) / 2.0) as f32); + open.frame(vec![egui::Event::PointerMoved(at)]); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -0.4), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + let mut nodes = Vec::new(); + for _ in 0..200 { + nodes = open.frame(vec![wheel.clone()]); + } + for _ in 0..120 { + if !open.repaint { + break; + } + nodes = open.frame(vec![]); + } + let offset = open.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().2; + assert!(offset > ROW_HEIGHT, "the list scrolled past the first row: {offset}"); + assert!(open.highlighted() > 0, "the highlight left the row scrolled out of view"); + let popup = open.popup(); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); + } + /// When the window shrinks so the list shows fewer rows, the list scrolls to keep the /// highlighted result in view, and Enter runs that result. #[test] From d998629b8dc5716b762746d4351b8c8328fe8500 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:49:59 -0800 Subject: [PATCH 02/25] Eyedropper: Escape ends a gradient stop's or Key Color's pick and returns to the previous tool Escape with a gradient stop's or Brush Options' Key Color eyedropper armed now ends the pick without sampling and switches back to the tool that armed it. The stop keeps its color. With Brush Options open, the first Escape ends only the pick and the dialog stays open with its Key Color; a new Escape cancels the dialog as before. The plain Eyedropper keeps its Escape behavior, and a dropped touch leaves an armed pick waiting for its click. Fixes #8024 --- crates/tools/src/xform/eyedropper.rs | 72 ++++++++++++++++++- .../src/dialogs/brush_options/tests.rs | 21 ++++++ crates/ui-egui/src/panels/gradient/tests.rs | 21 ++++++ crates/ui-egui/src/shortcuts.rs | 14 ++++ docs/target-app-parity.md | 1 + 5 files changed, 128 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index c5e05f004b..79c5116887 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,6 +16,9 @@ //! //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. +//! +//! Escape ends either pick without sampling and switches back to that tool. With neither pick +//! armed, Escape is left to the application. use std::collections::HashSet; @@ -28,7 +31,7 @@ use vectorcraft_geom::{Affine, Point, Rect}; use super::paint_owner; use crate::params::color_json; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; #[derive(Default)] pub struct EyedropperTool { @@ -530,6 +533,38 @@ impl Tool for EyedropperTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { Cursor::Eyedropper } + + /// Escape ends a gradient stop's or Key Color's pick without sampling and switches back to the + /// tool that armed it. + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key != ToolKey::Escape || !self.picking() { + return vec![]; + } + let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); + self.brush_key_color = false; + vec![Action::SwitchTool(back)] + } + + /// A dropped press (a long or canceled touch) leaves an armed pick waiting for its click. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + vec![] + } + + /// Escape is the tool's while a pick is armed, so it switches back and ends nothing else. + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.picking() + } + + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.picking() + } +} + +impl EyedropperTool { + /// Is a one-shot pick armed (a gradient stop's or Brush Options' Key Color)? + fn picking(&self) -> bool { + self.stop.is_some() || self.brush_key_color + } } #[cfg(test)] @@ -619,6 +654,41 @@ mod tests { assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only"); } + /// #8024: Escape ends a gradient stop's pick and a Key Color pick without sampling and + /// switches back; the plain Eyedropper leaves Escape alone. + #[test] + fn escape_ends_a_pick_and_switches_back() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let mut cx = cx(&d, &s, &p); + cx.gradient_stop = Some(1); + let none = Mods::default(); + let mut t = EyedropperTool::default(); + assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx), "nothing armed"); + assert!(t.key(&cx, ToolKey::Escape, none).is_empty()); + + t.set_option("stop", &json!("gradient")); + assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx)); + assert!(!t.claims_key(&cx, ToolKey::Enter)); + assert!(t.drop_press(&cx).is_empty(), "a dropped press leaves the pick armed"); + assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("gradient".into())]); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + assert!(!t.claims_key(&cx, ToolKey::Escape) && t.key(&cx, ToolKey::Escape, none).is_empty(), "one cancel only"); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert!(!a.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("stop").is_some())), "no stop sample after the cancel: {a:?}"); + + t.set_option("brushKeyColor", &json!(true)); + t.set_option("stop", &json!("paintbrush")); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("paintbrush".into())]); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + + // A Key Color pick with no tool to return to goes back to the Selection tool. + t.set_option("brushKeyColor", &json!(true)); + assert_eq!(t.key(&cx, ToolKey::Escape, none), vec![Action::SwitchTool("selection".into())]); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + } + #[test] fn brush_key_color_samples_into_the_dialog_then_switches_back() { let (d, _) = doc_with_rect(); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 9ff55da454..df45452a02 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -204,6 +204,27 @@ fn brush_key_color_eyedropper_updates_the_open_dialog() { assert_eq!(app.session.tool_id(), back); } +/// #8024: the first Escape ends the Key Color pick and returns to the tool that armed it, leaving +/// Brush Options open with its Key Color; a new press then cancels the dialog. +#[test] +fn escape_ends_the_key_color_pick_and_leaves_brush_options_open() { + let (mut app, ctx) = (app(), ctx()); + app.select_tool("paintbrush"); + app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap(); + set(&mut app, json!({"colorization": "hueShift"})); + let before = app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned()); + app.select_tool("eyedropper"); + app.session.set_tool_option("brushKeyColor", &json!(true)); + app.session.set_tool_option("stop", &json!("paintbrush")); + frame(&ctx, &mut app, vec![], ""); + escape(&ctx, &mut app); + assert!(app.ui.dialog.is_some(), "Brush Options stays open"); + assert_eq!(app.ui.dialog.as_ref().and_then(|d| d.fields.get("keyColor").cloned()), before, "the Key Color stays"); + assert_eq!(app.session.tool_id(), "paintbrush"); + escape(&ctx, &mut app); + assert!(app.ui.dialog.is_none(), "a new press cancels Brush Options"); +} + #[test] fn art_options_set_width_scale_direction_flips_and_colorization() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index d5362b8bab..14a711bf57 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -711,6 +711,27 @@ fn the_stop_eyedropper_arms_the_eyedropper_for_the_stop() { assert_eq!((app.session.tool_id(), app.session.tool_options()), ("eyedropper", json!({"stop": "gradient", "brushKeyColor": false}))); } +/// #8024: Escape ends the stop eyedropper's pick and returns to the Gradient tool. The stop keeps +/// its color, the selection stays, and a held Escape's repeats end nothing else. +#[test] +fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() { + let mut app = app(json!({"gradient": {}})); + crate::shortcut_editor::sync(&app.ui); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + let (paint, selected) = (current(&app), app.session.active().unwrap().selection.objects.clone()); + stop_eyedropper(&mut app); + let key = |pressed, repeat| Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat, modifiers: Modifiers::NONE }; + let ctx = egui::Context::default(); + for events in [vec![key(true, false)], vec![key(true, true)], vec![key(false, false)]] { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + assert_eq!(app.session.tool_id(), "gradient"); + assert_eq!(current(&app), paint, "the stop keeps its color"); + assert_eq!(app.session.active().unwrap().selection.objects, selected, "the selection stays"); +} + /// The gradient panel names its Angle and Aspect Ratio inputs. #[test] fn angle_and_aspect_fields_are_named() { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 6329f489b1..781bec4e74 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -231,6 +231,14 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { || crate::dialogs::new_document_popup_open(d) || crate::dialogs::export_artboard_name_editing(app, d) }); + // Escape ends Brush Options' Key Color pick and leaves the dialog open: the Eyedropper + // switches back to the tool that armed it. + if !popup && pressed_anew(ctx, Key::Escape) && key_color_pick_armed(app) { + let view = app.view_info(); + let r = app.session.tool_key(ToolKey::Escape, Mods::default(), view); + crate::canvas::apply_requests(app, r); + return; + } // Escape in Preferences' search field with text clears the field first. if !popup && pressed_anew(ctx, Key::Escape) && !crate::prefs_dialog::clear_search_on_escape(app, ctx) { crate::dialogs::cancel(app); @@ -387,6 +395,12 @@ pub(crate) fn pressed_anew(ctx: &egui::Context, key: Key) -> bool { ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: k, pressed: true, repeat: false, .. } if *k == key))) } +/// Is Brush Options open with its Key Color eyedropper armed, waiting for a click on the art? +fn key_color_pick_armed(app: &VectorcraftApp) -> bool { + let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::brush_options::KIND); + open && app.session.tool_id() == "eyedropper" && app.session.tool_options()["brushKeyColor"] == true +} + /// Takes this frame's repeats of `key` when the tool claims it: a press acts once, and they stay out /// of the shortcuts. A chord a command is bound to keeps its repeats. fn take_claimed_repeat(app: &mut VectorcraftApp, ctx: &egui::Context, key: Key, tool_key: ToolKey, view: ViewInfo) -> bool { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc4082ad68..c1d8b60559 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1692,6 +1692,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Hue Clockwise and Hue Counterclockwise, VectorCraft's own gradient methods, in the Gradient panel's Method menu and on `paint.editGradient` and `paint.setFill` (`method`: `hue-clockwise`, `hue-counterclockwise`): a linear, radial, conic or diamond gradient's colors mix around the hue wheel, with hue, saturation and brightness each changing evenly from one stop to the next and the hue angle keeping one direction, as the fixed-direction rules of [CSS Color 4](https://www.w3.org/TR/css-color-4/#hue-interpolation) do: falling with Hue Clockwise (red, magenta, blue), which is clockwise on the color wheels, and rising with Hue Counterclockwise (red, yellow, green). Hues less than half a color level apart count as one hue, so a color and its tint do not turn the wheel. A gray stop takes the hue of the stop it mixes with, and black its saturation too. The canvas and raster exports draw it through stops on that curve, within half a color level; Reverse Gradient turns the method the other way with the stops, so the ramp keeps its colors. SVG and PDF write it as an RGB image, EPS as a shading in process colors, and a legacy `.ai` file and the `.ai` editing data with the colors between its stops as stops of their own, with a warning. - Gradient spread, VectorCraft's own setting: Pad, Repeat or Reflect, with a Repeats count of 1 to 100, in the Gradient panel and on `paint.editGradient` and `paint.setFill`; Repeat and Reflect run a linear, radial, conic or diamond gradient's stops that many times along the vector and on past its ends, the Gradient tool marks where the runs meet, and SVG writes and reads `spreadMethod`, CSS writes repeating gradients, PDF writes a conic's sweep shading over one run and the other kinds with their stops repeated across the shape, as EPS, legacy `.ai` and the `.ai` editing data do. - The stop popover a double-click on a stop opens (the Gradient tool's annotator or the Gradient panel) has an eyedropper beside its Color and Swatches tabs: it closes the popover and samples the next colour clicked on the art into the stop, as the Gradient panel's eyedropper does (#4681). + Escape ends that eyedropper's pick, and Brush Options' Key Color pick, without sampling and returns to the tool that started it; the stop keeps its color, and Brush Options stays open with its Key Color until a new Escape cancels it (#8024, [Modify gradients, archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=264)). Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. From 069f6963c6df1de9945d5eb933bef25c1e66cf15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:18:48 -0800 Subject: [PATCH 03/25] SVG glyphs: a glyph from a shared SVG document reads only what it refers to A font's SVG table can keep many glyphs in one document. Each glyph's art was read by handing the importer the whole document, with every other glyph moved into defs. The importer now gets the glyph's element and only what it refers to: elements named by its effective link (plain href, else xlink:href) or by url(#id) in attributes, style attributes and sheets, what those refer to in turn, the start and end tags of the elements holding them, and every + + {other}"## + ), + // Clip paths, masks, filters, markers and patterns, a cycle, the glyph using itself, a + // non-ASCII id. + format!( + r##" + + + + + + + {other}"## + ), + // A rule on the glyph's own parent, which it leaves either way; a quoted, spaced URL to + // an id with punctuation in it. + format!( + r##" + + {other}"## + ), + // A pattern whose art takes its paint from the group holding it. + format!( + r##" + + {other}"## + ), + ]; + for doc in &docs { + let (reduced, whole) = (rewrite(doc, 1, true), rewrite(doc, 1, false)); + assert!(reduced.len() < whole.len() && !reduced.contains("#123456"), "reduced: {reduced}"); + assert_eq!(art(doc, 1, true), art(doc, 1, false), "{reduced}"); + } + } + + /// Whatever the reduction can't follow keeps the whole document in the `defs`. + #[test] + fn what_cant_be_followed_keeps_the_whole_document() { + let glyph = |defs: &str, art: &str| { + format!( + r##"{defs}{art}"## + ) + }; + let gradient = r##""##; + let path = |fill: &str| format!(r##""##); + let docs = [ + glyph("", &path("#000")), + glyph("", &path("#000")), + glyph("", &path("#000")), + glyph("", &path("#000")), + glyph(r"", &path("#000")), + glyph("", &path("#000")), + glyph(gradient, &path(r"url(#\67)")), + glyph(gradient, r#""#), + glyph(gradient, &path("url(#%67)")), + glyph(gradient, &path("url('#g)")), + glyph(gradient, &path("url(#g) url(#g x)")), + glyph(gradient, &path("url(#nothing)")), + glyph(gradient, &path("url(other.svg#g)")), + glyph(gradient, r##""##), + glyph(&format!("{gradient}{gradient}"), &path("url(#g)")), + glyph(&format!(r#"{gradient}"#), &path("url(#g)")), + glyph(&format!("{gradient}"), &path("url(#g)")), + r##""## + .to_string(), + r##"]>"## + .to_string(), + ]; + for doc in &docs { + assert_eq!(rewrite(doc, 1, true), rewrite(doc, 1, false), "{doc}"); + } + } + + #[test] + fn edits_apply_inside_the_range_asked_for() { + let edits = vec![(0..1, "A".to_string()), (2..2, "B".into()), (3..5, String::new()), (4..6, "C".into())]; + // An edit overlapping one already made is passed by; one not inside the range is not made. + assert_eq!(edited("0123456", 0..7, &edits).as_deref(), Some("A1B256")); + assert_eq!(edited("0123456", 2..5, &edits).as_deref(), Some("B2")); + assert_eq!(edited("0123456", 4..7, &edits).as_deref(), Some("C6")); + assert_eq!(edited("0123456", 1..2, &edits).as_deref(), Some("1B")); + } + + /// Of an element's `href` and `xlink:href`, only the plain one is followed, as the importer + /// follows it: the other's element stays out, and one that isn't there doesn't keep the whole + /// document. + #[test] + fn only_the_link_the_importer_follows_is_kept() { + let doc = |xlink: &str| { + format!( + r##" + "## + ) + }; + for xlink in ["#nothing", "other.svg#b"] { + let doc = doc(xlink); + let reduced = rewrite(&doc, 1, true); + assert!(reduced.len() < rewrite(&doc, 1, false).len() && !reduced.contains("#123456"), "{reduced}"); + assert_eq!(art(&doc, 1, true), art(&doc, 1, false)); + } + let doc = doc("#b").replace(r##""##, ""); + let reduced = rewrite(&doc, 1, true); + assert!(reduced.contains(r#"id="a""#) && !reduced.contains(r#"id="b""#), "{reduced}"); + assert_eq!(art(&doc, 1, true), art(&doc, 1, false)); + } + + /// A glyph inside an element that gives a prefix (or the default namespace) another namespace + /// than the root does keeps its own after it leaves that element. + #[test] + fn a_glyph_keeps_its_namespaces_when_the_root_gives_them_others() { + let flat = r##" + "##; + let nested = r##" + "##; + // The glyph declaring the prefix itself keeps it as it is. + let declared = r##" + "##; + for reduce in [true, false] { + assert_eq!(art(nested, 1, reduce), art(flat, 1, reduce), "{}", rewrite(nested, 1, reduce)); + assert_eq!(art(declared, 1, reduce), art(flat, 1, reduce), "{}", rewrite(declared, 1, reduce)); + } + assert_eq!(rewrite(declared, 1, true).matches("xmlns:v=").count(), 2); + // A path in another default namespace is no SVG path, out of that element too. + let other = r##" + "##; + let only = r##""##; + for reduce in [true, false] { + assert_eq!(art(other, 1, reduce), art(only, 1, reduce), "{}", rewrite(other, 1, reduce)); + } + } + + /// Many references to the same elements keep each of them once. + #[test] + fn repeated_references_keep_each_element_once() { + let uses: String = (0..2000).map(|i| format!(r##""##)).collect(); + let doc = format!( + r##" + + {uses}"## + ); + let reduced = rewrite(&doc, 1, true); + for id in ["g", "a", "b"] { + assert_eq!(reduced.matches(&format!(r#"id="{id}""#)).count(), 1, "{id}"); + } + assert!(!reduced.contains("#123456")); + } + + /// An empty document, or one without the glyph, has no art; one of exactly the cap reads, one a + /// byte larger doesn't. + #[test] + fn empty_and_capped_documents() { + assert!(glyph_art(b"", 1, 1000.0, Color::BLACK, None).is_none()); + assert!(glyph_art(br#""#, 1, 1000.0, Color::BLACK, None).is_none()); + let doc = shared(20); + let at = doc.len() - "".len(); + let padded = |len: u64| { + let pad = "x".repeat(len as usize - doc.len() - "".len()); + format!("{}{}", &doc[..at], &doc[at..]) + }; + let (full, over) = (padded(MAX_SVG_GLYPH_BYTES), padded(MAX_SVG_GLYPH_BYTES + 1)); + assert_eq!(full.len() as u64, MAX_SVG_GLYPH_BYTES); + assert_eq!(art(&full, 3, true), art(&doc, 3, true)); + assert!(glyph_art(over.as_bytes(), 3, 1000.0, Color::BLACK, None).is_none()); + } + + /// This thread's CPU time in seconds where the system reports it, else the time since a first + /// call. + fn cpu_seconds() -> f64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { + Some(ns) => ns / 1e9, + None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(), + } + } + + /// The importer's time for 50 distinct glyphs of shared documents, read whole and reduced, the + /// two alternating in one process: `cargo test -p vectorcraft-svg --lib glyph::tests::timing -- + /// --ignored --nocapture`. + #[test] + #[ignore = "timing, run by hand"] + fn timing() { + for n in [100, 500, 2000] { + let doc = shared(n); + let gids: Vec = (0..50).map(|i| (i * n / 50) as u32).collect(); + let run = |reduce: bool| { + let t = cpu_seconds(); + for g in &gids { + assert!(glyph_art_with(doc.as_bytes(), *g, 1000.0, Color::BLACK, None, reduce).is_some()); + } + cpu_seconds() - t + }; + run(false); + run(true); + let (mut whole, mut reduced) = (vec![], vec![]); + for round in 0..9 { + if round % 2 == 0 { + whole.push(run(false)); + reduced.push(run(true)); + } else { + reduced.push(run(true)); + whole.push(run(false)); + } + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::>().join(" "); + println!("{n} glyphs, {} bytes: whole {} ms, reduced {} ms", doc.len(), ms(&whole), ms(&reduced)); + println!("{n} glyphs: median whole {:.1} ms, reduced {:.1} ms", median(&mut whole) * 1e3, median(&mut reduced) * 1e3); + } + } +} diff --git a/crates/svg/tests/it/svg_glyphs.rs b/crates/svg/tests/it/svg_glyphs.rs index 20e5342412..3e4ba8b697 100644 --- a/crates/svg/tests/it/svg_glyphs.rs +++ b/crates/svg/tests/it/svg_glyphs.rs @@ -241,13 +241,10 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() { let svg = vectorcraft_svg::base64_encode( br##""##, ); - let image = |href: &str, xlink: &str| { - format!( - r##""##, - if href == "png" { &png } else { &svg }, - if xlink == "png" { &png } else { &svg } - ) - }; + let data = |kind: &str| format!("data:image/{kind};base64,{}", if kind == "png" { &png } else { &svg }); + let image = |href: &str, xlink: &str| format!(r##""##, data(href), data(xlink)); + // The same, `xlink:href` written first. + let xlink_first = |href: &str, xlink: &str| format!(r##""##, data(xlink), data(href)); let images = |inner: String| { let doc = format!( r##"{inner}"## @@ -258,6 +255,38 @@ fn an_images_plain_href_decides_whether_it_is_an_svg_image() { }; assert_eq!(images(image("png", "svg+xml")), 1, "the PNG stays"); assert_eq!(images(image("svg+xml", "png")), 0, "the document goes"); + assert_eq!(images(xlink_first("png", "svg+xml")), 1, "the PNG stays, its link written last"); + assert_eq!(images(xlink_first("svg+xml", "png")), 0, "the document goes, its link written last"); +} + +/// A glyph draws what it refers to wherever its document defines it: here a sheet's `url()` to a +/// gradient inside another glyph's element, which takes its stops from one in `defs`. The other +/// glyph's own art is not drawn. +#[test] +fn a_glyph_draws_what_it_refers_to_from_anywhere_in_its_document() { + let doc = r##" + + + + "##; + let fills = fills(&art(doc, 5).unwrap()); + let stops = fills.iter().find_map(|p| match p { + Paint::Gradient(g) => Some(g.gradient.stops.iter().map(|s| s.color).collect::>()), + _ => None, + }); + assert_eq!(stops, Some(vec![Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)]), "{fills:?}"); + assert!(!fills.contains(&Paint::solid(Color::rgb8(0, 255, 0))), "not the other glyph's art: {fills:?}"); +} + +/// A glyph in colors of its own doesn't use the text's because another glyph of its document does. +#[test] +fn another_glyphs_current_color_does_not_color_a_glyph() { + let doc = r##" + + + "##; + assert!(!glyph_art(doc.as_bytes(), 1, 1000.0, BLUE, None).unwrap().1); + assert!(glyph_art(doc.as_bytes(), 2, 1000.0, BLUE, None).unwrap().1); } /// A glyph's `` draws its art but keeps no link: outlined text must not export a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..3f46017fe5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -718,6 +718,7 @@ since 2026-10-01. - **Colour emoji with bitmap glyphs:** `sbix` (Apple Color Emoji) and `CBDT` (Noto Color Emoji) glyphs draw as their largest strike's PNG, placed with the type and unpainted by its fill; PDF writes them in Type 3 glyphs or as images, SVG as images with outlined text, EPS and legacy `.ai` as images, and Create Outlines makes embedded images. Synthetic test fonts in `crates/text/src/test_fonts.rs`; tests `crates/text/src/tests/bitmaps.rs`, `crates/render/src/tests/bitmapglyphs.rs`, `crates/svg/tests/it/colour_glyphs.rs`, `pdf::tests::colour_bitmap_glyphs_export_as_images`, the `eps` `colour_bitmap_glyphs_*` tests and `tests_pathops::create_outlines_turns_bitmap_glyphs_into_images`. COLR and OpenType SVG fonts remain. - **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, including ones that repeat or reflect, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients, Porter-Duff compositing and radial gradients that repeat or reflect and start at a circle draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated). - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). +- **OpenType SVG glyphs from a shared document:** when one SVG document holds many glyphs, the importer reads only the glyph's element and what it refers to (by `href` or `url(#id)`, through other elements, the elements holding them and every `