From b61e57e3f51bac6e46c79baa49e5b02c14637188 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:43:44 -0500 Subject: [PATCH 01/63] Scale tool: a Shift-drag along one axis scales along it alone (#6324) --- crates/tools/src/xform/transform.rs | 31 ++++++++++++++++++++++++++++- docs/target-app-parity.md | 5 +++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 5cabbed6b8..f70b6c91fa 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -143,7 +143,15 @@ impl TransformTool { let d1 = p - o; let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 }; let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y)); - if shift { + // Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal + // one uniformly (#6324). + let moved = p - start; + let angle = moved.y.abs().atan2(moved.x.abs()).to_degrees(); + if shift && moved.hypot() > 1e-9 && angle <= 22.5 { + sy = 1.0; + } else if shift && moved.hypot() > 1e-9 && angle >= 67.5 { + sx = 1.0; + } else if shift { let l2 = d0.hypot2(); let k = if l2 > 1e-12 { d1.dot(d0) / l2 } else { 1.0 }; sx = k; @@ -450,6 +458,27 @@ mod tests { assert!((c[0] - c[3]).abs() < 1e-9 && c[0] > 1.0); } + /// A Shift-drag along one axis scales along that axis alone, and a diagonal one scales + /// uniformly (#6324): the drag's own direction decides, within 22.5° of an axis. + #[test] + fn scale_shift_follows_the_drag_direction() { + let t = TransformTool::new(TransformKind::Scale); + let o = Point::new(100.0, 100.0); + let scales = |p: Point| { + let c = t.matrix_for(o, Point::new(150.0, 140.0), p, true, Rect::ZERO).0.as_coeffs(); + (c[0], c[3]) + }; + // Sideways, a little off the level: width only. + let (sx, sy) = scales(Point::new(200.0, 145.0)); + assert!((sx - 2.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9, "{sx} {sy}"); + // Up or down: height only. + let (sx, sy) = scales(Point::new(148.0, 180.0)); + assert!((sx - 1.0).abs() < 1e-9 && (sy - 2.0).abs() < 1e-9, "{sx} {sy}"); + // Diagonal: both, by the same factor. + let (sx, sy) = scales(Point::new(200.0, 180.0)); + assert!((sx - sy).abs() < 1e-9 && sx > 1.0, "{sx} {sy}"); + } + #[test] fn alt_click_opens_dialog_and_alt_release_copies() { let (d, id) = doc_with_rect(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 23080e57ee..76fbdb71d9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (#6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (#6324: Scale tool: Shift scales along the axis the drag follows; scores unchanged; previously minor: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -53,6 +53,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-13 | minor | Scale tool: a Shift-drag within 22.5° of horizontal or vertical scales along that axis alone, a diagonal one uniformly (#6324); scores unchanged. | | 2026-11-09 | minor | Stroke panel: Line Arrow, a 41st generated arrowhead: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, a sharp tip and square-cut ends, twice as wide as the other heads; bounds and clicks follow each head's own reach (`stroke.set` `LineArrow`, #5421); scores and estimates unchanged | | 2026-11-09 | minor | Canvas: a 3D effect (Extrude & Bevel, Inflate, Rotate, Revolve) changed on type or a group draws again where its art was and is, measured by that art; the canvas measures through its renderer and draws the part with the art it made to measure it. Exports and Object › Rasterize take the solid of 3D type. Fit to Artwork Bounds and per-artboard SVG export measure every artboard through one renderer, building each solid once. A 3D effect on a fill or stroke that builds nothing (Revolve after Roughen) no longer overflows the stack on the canvas, in Object › Rasterize and in raster and EPS exports: the fill or stroke draws as without it. Tests `tests::changed::a_3d_effect_changed_on_type_or_a_group_changes_where_its_solid_was`, `fx::tests::a_renderer_measures_the_art_on_each_artboard_building_each_solid_once`, `canvas::tests::an_edit_to_a_3d_effect_redraws_with_the_art_measured`, `fx::tests::a_3d_effect_that_builds_nothing_draws_the_item_as_without_it`. Scores and estimates unchanged. | | 2026-11-08 | minor | Style panels: a double-click on a user character style's row opens its Character Style Options (`ui.charStyleOptions`), and on a paragraph style's row its Paragraph Style Options (rename); the Character Style Options dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | @@ -1009,7 +1010,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). + - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Scale tool drag with Shift held scales along one axis when it runs within 22.5° of horizontal or vertical and uniformly when it runs diagonally ([Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); #6324; `scale_shift_follows_the_drag_direction` in `crates/tools/src/xform/transform.rs`). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. From e7e1978464a9e39b6f5c87b8c84c01ad5f9280dd Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:54:02 -0500 Subject: [PATCH 02/63] Scale tool (#6324): a Shift-drag that starts level with the reference point on its axis stays uniform --- crates/tools/src/xform/transform.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index f70b6c91fa..d64c9d23a0 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -144,12 +144,14 @@ impl TransformTool { let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 }; let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y)); // Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal - // one uniformly (#6324). + // one uniformly (#6324). A drag that starts level with the reference point on that + // axis has nothing to scale it by, so it stays uniform. let moved = p - start; let angle = moved.y.abs().atan2(moved.x.abs()).to_degrees(); - if shift && moved.hypot() > 1e-9 && angle <= 22.5 { + let along = moved.hypot() > 1e-9; + if shift && along && angle <= 22.5 && d0.x.abs() > 1e-6 { sy = 1.0; - } else if shift && moved.hypot() > 1e-9 && angle >= 67.5 { + } else if shift && along && angle >= 67.5 && d0.y.abs() > 1e-6 { sx = 1.0; } else if shift { let l2 = d0.hypot2(); @@ -477,6 +479,16 @@ mod tests { // Diagonal: both, by the same factor. let (sx, sy) = scales(Point::new(200.0, 180.0)); assert!((sx - sy).abs() < 1e-9 && sx > 1.0, "{sx} {sy}"); + // A drag that starts straight above (beside) the reference point has no width (height) to + // scale, so a sideways (up or down) Shift-drag from there scales uniformly, as before. + let from = |start: Point, p: Point| { + let c = t.matrix_for(o, start, p, true, Rect::ZERO).0.as_coeffs(); + (c[0], c[3]) + }; + let (sx, sy) = from(Point::new(100.0, 150.0), Point::new(150.0, 160.0)); + assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}"); + let (sx, sy) = from(Point::new(150.0, 100.0), Point::new(160.0, 150.0)); + assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}"); } #[test] From 0fc66110eb865035653a036931a6aca81bb5aa56 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:50:51 -0500 Subject: [PATCH 03/63] Scale tool (#6324): the pointer's own movement picks a Shift-drag's axis --- crates/tools/src/xform/transform.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index d64c9d23a0..f1e416e0ca 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -125,6 +125,12 @@ impl TransformTool { /// Transform for dragging from `start` to `p` about `o`; returns the matrix and a readout. pub fn matrix_for(&self, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) { + self.matrix_moved(o, start, p, p - start, shift, bounds) + } + + /// [`Self::matrix_for`] with `moved`, the pointer's own movement since the press: a snapped + /// press or point can turn a level drag diagonal, so it picks a Shift-drag's axis for Scale. + fn matrix_moved(&self, o: Point, start: Point, p: Point, moved: Vec2, shift: bool, bounds: Rect) -> (Affine, String) { match self.kind { TransformKind::Rotate => { let (a, deg) = rotate_for_drag(o, start, p, shift); @@ -146,7 +152,6 @@ impl TransformTool { // Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal // one uniformly (#6324). A drag that starts level with the reference point on that // axis has nothing to scale it by, so it stays uniform. - let moved = p - start; let angle = moved.y.abs().atan2(moved.x.abs()).to_degrees(); let along = moved.hypot() > 1e-9; if shift && along && angle <= 22.5 && d0.x.abs() > 1e-6 { @@ -252,9 +257,10 @@ impl Tool for TransformTool { self.snap = Some(PointSnap::new(cx, || Targets::collect(cx.doc, &cx.selection.objects, None))); out.push(Action::Begin(self.kind.label().into())); } + let moved = p - d.start; let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p)); self.hover = guides; - let (m, text) = self.matrix_for(d.origin, d.pick, p, ev.mods.shift, d.bounds); + let (m, text) = self.matrix_moved(d.origin, d.pick, p, moved, ev.mods.shift, d.bounds); d.last = m; self.drag = Some(d); self.measure = Some((p, text)); @@ -491,6 +497,23 @@ mod tests { assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}"); } + /// The axis of a Shift-drag comes from the pointer's own movement: a press near a corner + /// snaps to it, and a level drag from there still scales the width alone. + #[test] + fn scale_shift_axis_follows_the_pointer_not_the_snapped_press() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = TransformTool::new(TransformKind::Scale); + t.pointer(&cx, &ev(PointerKind::Down, 198.0, 203.0).with_mods(shift)); + let drag = t.pointer(&cx, &ev(PointerKind::Drag, 205.0, 203.0).with_mods(shift)); + let c = matrix(drag.last().expect("a preview")).as_coeffs(); + assert!((c[0] - 1.1).abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9, "the width alone: {c:?}"); + } + #[test] fn alt_click_opens_dialog_and_alt_release_copies() { let (d, id) = doc_with_rect(); From 02c4ef3d66d33f1792f575a037db793dec650675 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:29:27 -0500 Subject: [PATCH 04/63] =?UTF-8?q?Scale=20tool=20(#6324)=20docs:=20the=2022?= =?UTF-8?q?.5=C2=B0=20split=20and=20the=20level-start=20case=20are=20Vecto?= =?UTF-8?q?rCraft's?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e15085e6b8..54af764262 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1021,7 +1021,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Scale tool drag with Shift held scales along one axis when it runs within 22.5° of horizontal or vertical and uniformly when it runs diagonally ([Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); #6324; `scale_shift_follows_the_drag_direction` in `crates/tools/src/xform/transform.rs`). + - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Scale tool drag with Shift held scales along one axis when it runs horizontally or vertically and uniformly when it runs diagonally ([Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); #6324). The page gives no angle: in VectorCraft a drag within 22.5° of an axis runs along it, judged from the pointer's own movement, and a drag that starts level with the reference point on that axis scales uniformly, having nothing to scale along it (`scale_shift_follows_the_drag_direction` and `scale_shift_axis_follows_the_pointer_not_the_snapped_press` in `crates/tools/src/xform/transform.rs`). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. From 6b83aa05113870c6c1717a7b933ef4b686dc879a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:00:41 +0700 Subject: [PATCH 05/63] clippy: pack TransformTool::solve's drag arguments into SolveDrag Hosted `cargo xtask ci` failed clippy with -D clippy::too-many-arguments after merging main: solve already had seven arguments, and the merge added `moved` (the unsnapped pointer movement Scale's Shift-axis uses). Same behaviour; the 16 transform unit tests still pass. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/tools/src/xform/transform.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 898ec36b10..e1fd634f57 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -95,6 +95,16 @@ impl Drag { } } +/// The pointer drag [`TransformTool::solve`] turns into a transform. +struct SolveDrag { + start: Point, + p: Point, + /// The pointer's own movement since the press, before snapping (#6324). + moved: Vec2, + shift: bool, + bounds: Rect, +} + pub struct TransformTool { kind: TransformKind, /// Custom reference point and the selection it was set for. @@ -159,7 +169,7 @@ impl TransformTool { /// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the /// line the pointer draws on the page. pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) { - let (m, a, b) = self.solve(angle, o, start, p, p - start, shift, bounds); + let (m, a, b) = self.solve(angle, o, SolveDrag { start, p, moved: p - start, shift, bounds }); (m, self.label(a, b)) } @@ -190,7 +200,8 @@ impl TransformTool { /// axis in degrees counter-clockwise (Reflect), the scale along the box's width and height /// (Scale), or the angle of the shear axis (0 horizontal, 90 vertical) and the shear angle as /// `object.shear` takes it (Shear). - fn solve(&self, angle: f64, o: Point, start: Point, p: Point, moved: Vec2, shift: bool, bounds: Rect) -> (Affine, f64, f64) { + fn solve(&self, angle: f64, o: Point, d: SolveDrag) -> (Affine, f64, f64) { + let SolveDrag { start, p, moved, shift, bounds } = d; let frame = OrientedBox { angle, rect: Rect::ZERO }; let local = |v: Vec2| frame.to_doc().inverse() * v.to_point(); match self.kind { @@ -349,7 +360,11 @@ impl Tool for TransformTool { let moved = p - d.start; let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p)); self.hover = guides; - let (m, a, b) = self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, moved, ev.mods.shift, d.bounds); + let (m, a, b) = self.solve( + d.angle_for(ev.mods.alt, ev.backquote), + d.origin, + SolveDrag { start: d.pick, p, moved, shift: ev.mods.shift, bounds: d.bounds }, + ); (d.last, d.pointer, d.shift, d.moved) = (m, p, ev.mods.shift, moved); self.drag = Some(d); self.measure = Some((p, self.label(a, b))); @@ -364,7 +379,12 @@ impl Tool for TransformTool { // or moves only pattern tiles, and with anchors selected, whether it acts // along the box or the page. let m = if d.anchors { - self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.moved, d.shift, d.bounds).0 + self.solve( + d.angle_for(ev.mods.alt, ev.backquote), + d.origin, + SolveDrag { start: d.pick, p: d.pointer, moved: d.moved, shift: d.shift, bounds: d.bounds }, + ) + .0 } else { d.last }; From 88f496d873397729617a4bc707d2eb8fcbc4d191 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:54:54 -0800 Subject: [PATCH 06/63] Tangent Circle Tool: Add Points to Existing Paths adds anchors where the circle touches The tool gets an `addPoints` option (Add Points to Existing Paths in its options, off to start). When it is on, drawing a circle also adds an anchor point where the circle touches the first segment and the second segment, splitting them without changing their shape. The anchors and the circle are one undo step. A touch at an existing anchor adds none. Alt held at the release turns the option the other way for that circle, and a dot beside the pointer shows while it is in effect. When a touched path was not selected, the selection is put back before the circle is drawn, so Draw Behind places the circle behind the selected objects. The option label has a row in every complete catalog. Part of #7178. --- .../engine/src/cmd/addons/pathtools/tests.rs | 58 ++++ crates/tools/src/addons/tangent_circle.rs | 273 +++++++++++++++++- crates/tools/src/settings.rs | 2 +- crates/ui-egui/src/addons/pathtools.rs | 4 + crates/ui-egui/src/addons/pathtools/tests.rs | 7 +- 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/tests.rs | 10 + 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 + docs/mcp.md | 13 +- docs/target-app-parity.md | 2 + docs/ui-parity.md | 2 +- 37 files changed, 378 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 8cd83bacfd..6bcfdbfc6c 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -1086,6 +1086,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() { assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn"); } +/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where +/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it +/// back. +#[test] +fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() { + let mut s = session(); + let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + let n = steps(&s); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + assert_eq!(steps(&s), n + 1, "one undo step"); + let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(); + let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6) + }; + assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a)); + assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b)); + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap(); + assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2)); + assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too"); +} + +/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the +/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected. +#[test] +fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() { + let mut s = session(); + line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false); + select(&mut s, &[other]); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + s.set_tool_option("addPoints", &json!(true)); + for (kind, x, y) in + [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)] + { + s.pointer(&PointerEvent::new(kind, x, y), view).unwrap(); + } + let st = s.doc().unwrap(); + let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) }; + let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index)); + let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") }; + assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}"); +} + fn ids(v: &Value) -> Vec { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index b40cffd8e7..22cbe4d6ba 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -15,9 +15,12 @@ //! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either -//! segment's shape differs from the one they were found on. +//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at +//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the +//! segments the circle touches get an anchor point at each touch, which splits them without changing +//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. -use kurbo::{CubicBez, Shape}; +use kurbo::{CubicBez, ParamCurveNearest, Shape}; use serde_json::{Value, json}; use vectorcraft_doc::NodeId; use vectorcraft_geom::{BezPath, ParamCurve, Point}; @@ -42,6 +45,12 @@ pub const NO_CIRCLE: &str = "No tangent circle here"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +/// The label of the `addPoints` option in the tool's options. +pub const ADD_POINTS: &str = "Add Points to Existing Paths"; +/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in +/// effect, and its size. +const DOT_PX: f64 = 10.0; +const DOT_SIZE: f32 = 4.0; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -72,6 +81,11 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether drawing a circle adds anchor points where it touches the segments. + add_points: bool, + /// The keys held at the last pointer event, and whether the pointer is over the canvas. + mods: Mods, + over: bool, first: Option, hover: Option, press: Option, @@ -91,7 +105,20 @@ type CacheKey = (NodeId, usize, usize, Option, CubicBez, Vec); impl Default for TangentCircleTool { fn default() -> Self { - Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + Self { + radius: RADIUS, + add_points: false, + mods: Mods::default(), + over: false, + first: None, + hover: None, + press: None, + picking: false, + found: None, + looked: false, + pointer: Point::ZERO, + cache: None, + } } } @@ -120,6 +147,11 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { + second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect() +} + +/// [`second_set`] with each segment's index on the second pick's subpath. +fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> { if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { return vec![]; } @@ -136,7 +168,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { indices.sort_unstable(); indices.dedup(); let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; - indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() + indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect() +} + +/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either +/// end, where the segment already has an anchor point. +fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option { + if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol { + return None; + } + let t = curve.nearest(p, 1e-12).t; + (t > 0.0 && t < 1.0).then_some(t) +} + +/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment +/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath +/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the +/// anchor added before it does not move it along. +fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec { + let mut at: Vec<(NodeId, usize, usize, f64)> = vec![]; + if let Some(t) = split_at(&first.curve, c.first, tol) { + at.push((first.id, first.subpath, first.segment, t)); + } + let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq)); + if let Some((k, curve)) = nearest + && let Some(t) = split_at(curve, c.second, tol) + { + at.push((pick.id, pick.subpath, *k, t)); + } + at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2))); + at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect() } /// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot @@ -173,6 +234,14 @@ fn round_step(least: f64) -> f64 { /// distance from the origin, or too large, in floating point), or when the circle would reach past /// the canvas ([`crate::circle::circle_of`]), which the command refuses. fn draw(c: &SegmentCircle, tol: f64) -> Option { + circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p)) +} + +/// The command [`draw`] runs. +const CIRCLE: &str = "shape.circleThroughPoints"; + +/// The params of the [`CIRCLE`] command that [`draw`] runs. +fn circle_params(c: &SegmentCircle, tol: f64) -> Option { let (at, r) = (c.circle.center, c.circle.radius); let points: Vec = [90.0f64, 210.0, 330.0] .iter() @@ -186,7 +255,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option { return None; } let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect(); - Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points }))) + Some(json!({ "points": points })) } fn segment_path(c: &CubicBez) -> BezPath { @@ -302,6 +371,8 @@ impl Tool for TangentCircleTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.pointer = ev.pos; + self.mods = ev.mods; + self.over = true; match ev.kind { PointerKind::Move => { self.hover = pick_at(cx, ev.pos); @@ -335,15 +406,34 @@ impl Tool for TangentCircleTool { // The release's own position and keys set the radius of a drag. self.drag_to(cx, ev); self.picking = false; - if self.press.take().is_none() { - return vec![]; - } + let Some(press) = self.press.take() else { return vec![] }; // No circle, or one the three points cannot draw: the first segment stays picked, // for another try. It also stays when the command fails: only a drawn circle tells // the tool (`notify`) to forget it. - let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + let Some(c) = self.found.take() else { return vec![] }; + let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] }; self.looked = false; - vec![action, Action::Notify(DRAWN.into())] + // Alt at the release turns `addPoints` the other way. + let steps = match &self.first { + Some(first) if self.add_points != ev.mods.alt => { + let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] }; + anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX)) + } + _ => vec![], + }; + if steps.is_empty() { + return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())]; + } + let mut commands = steps; + // A path that was not selected becomes the selection when it gets an anchor; the + // selection is put back before the circle, which Draw Behind places behind it. + if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) { + let ids: Vec = cx.selection.objects.iter().map(|id| id.0).collect(); + commands.push(json!({ "command": "select.set", "params": { "ids": ids } })); + } + commands.push(json!({ "command": CIRCLE, "params": params })); + // One undo step for the anchors and the circle, and none of them when a step fails. + vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())] } // The canvas sends a double-click after the second click's `Up`, which drew the circle. PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -394,6 +484,7 @@ impl Tool for TangentCircleTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.over = false; if self.press.is_none() { self.found = None; self.looked = false; @@ -431,6 +522,11 @@ impl Tool for TangentCircleTool { // A label, which the canvas shows in the interface language. out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color: RED }); } + // `addPoints` in effect, with Alt as it is now. + if (self.over || self.press.is_some()) && self.add_points != self.mods.alt { + let off = cx.tol(DOT_PX); + out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE }); + } out } @@ -439,14 +535,22 @@ impl Tool for TangentCircleTool { } fn options(&self) -> Value { - json!({ "radius": self.radius }) + json!({ "radius": self.radius, "addPoints": self.add_points }) } fn set_option(&mut self, key: &str, v: &Value) { - if key == "radius" - && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) - { - self.radius = r; + match key { + "radius" => { + if let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) { + self.radius = r; + } + } + "addPoints" => { + if let Some(on) = v.as_bool() { + self.add_points = on; + } + } + _ => {} } } @@ -454,6 +558,7 @@ impl Tool for TangentCircleTool { use crate::option_check as c; match key { "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + "addPoints" => c::boolean(key, v), _ => Err(c::unknown(key)), } } @@ -812,6 +917,144 @@ mod tests { assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); } + /// The steps of the `command.batch` an action list runs: (command, params) each. + fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> { + let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") }; + assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN)); + p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect() + } + + /// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment. + fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) { + let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap()); + let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize]; + (id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap())) + } + + fn alt(mut e: PointerEvent) -> PointerEvent { + e.mods.alt = true; + e + } + + #[test] + fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y)).map(|p| p.id.0).unwrap(); + let (top, below) = (line_at(100.0), line_at(140.0)); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + assert_eq!(t.options()["addPoints"], json!(true)); + // The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter + // along each line, then the circle, in one batch. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}"); + let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + anchors.sort_by_key(|a| a.0); + let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))]; + want.sort_by_key(|a| a.0); + assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}"); + // The lines were not selected, so the selection (none) is put back before the circle. + assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}"); + let (cmd, params) = &steps[3]; + let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]); + assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}"); + assert!(t.first.is_none(), "ready for the next circle"); + // With both lines selected, the anchors leave the selection as it is: no step puts it back. + let mut both = Selection::default(); + both.add(NodeId(top)); + both.add(NodeId(below)); + let selected = self::cx(&d, &both, &p); + t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0))); + assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}"); + // Alt at the release turns it off for that circle, and with the option off turns it on. + for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] { + t.set_option("addPoints", &json!(on)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0))); + let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) }; + let released = up(&mut t, &cx, &release); + if adds { + assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}"); + } else { + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}"); + } + } + } + + #[test] + fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + t.set_option("radius", &json!(10)); + // The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310) + // on its second: the second segment's anchor comes first, so the first one's index holds. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + let l = pick_at(&cx, Point::new(300.0, 350.0)).map(|p| p.id.0); + let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))]; + assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}"); + assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE)); + // A circle touching both lines at their right ends: no anchor is added on top of an anchor, + // so only the circle is drawn, as without the option. + t.set_option("radius", &json!(36)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0)); + assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!(t.options()["addPoints"], json!(false), "off to start"); + let dot = + |t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(!dot(&t)); + // Alt turns it on while held, and back off with the option on. + t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0))); + assert!(dot(&t)); + t.set_option("addPoints", &json!(true)); + assert!(!dot(&t)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(dot(&t)); + let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else { + panic!("no dot") + }; + assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}"); + // The pointer off the canvas: no dot left behind. + t.hover_ended(&cx); + assert!(!dot(&t)); + for bad in [json!(1), json!("true"), Value::Null] { + assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}"); + t.set_option("addPoints", &bad); + assert_eq!(t.options()["addPoints"], json!(true), "{bad}"); + } + assert_eq!(t.check_option("addPoints", &json!(false)), Ok(())); + } + #[test] fn a_circle_that_would_reach_past_the_canvas_is_not_offered() { // Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..eab6c4d8c2 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -108,7 +108,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 3e7b864c05..8e95ef0b35 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -245,6 +245,10 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("radius".into(), json!(x)); } }); + if widgets::check(ui, tangent_circle_tool::ADD_POINTS, d.bool("addPoints"), true) { + let on = !d.bool("addPoints"); + d.fields.insert("addPoints".into(), json!(on)); + } return false; } let rows = [ diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 2c49c661fe..41c7a083b5 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -99,14 +99,17 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("arc")); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); - // The Tangent Circle tool's radius for Shift. + // The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start). app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0); + assert!(!app.ui.dialog.as_ref().unwrap().bool("addPoints")); let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); - assert!(text.contains("Tangent Circle Tool Options") && text.contains("Radius:"), "{text}"); + assert!(text.contains("Tangent Circle Tool Options") && text.contains("Radius:") && text.contains("Add Points to Existing Paths"), "{text}"); app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(12.5)); + app.ui.dialog.as_mut().unwrap().fields.insert("addPoints".into(), json!(true)); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); + assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true)); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..f0ab467d55 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7587,6 +7587,7 @@ breakText Glyphs Глифи Tangent Circle Допирателна окръжност Tangent Circle Tool Инструмент „Допирателна окръжност“ No tangent circle here Тук няма допирателна окръжност + Add Points to Existing Paths Добавяне на точки към съществуващите пътища Circle: Окръжност: @msg `ids` names an object twice `ids` посочва обект два пъти @msg select two or three paths or compound paths изберете два или три пътя или съставни пътя diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..e44d6cf775 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7636,6 +7636,7 @@ shape Open Otvoren Tangent Circle Tangentna kružnica Tangent Circle Tool Alat tangentna kružnica No tangent circle here Ovdje nema tangentne kružnice + Add Points to Existing Paths Dodaj tačke postojećim putanjama Circle: Kružnica: @msg `ids` names an object twice `ids` navodi objekat dvaput @msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..723ed98280 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8468,6 +8468,7 @@ breakText Glyphs Glifs Tangent Circle Cercle tangent Tangent Circle Tool Eina de cercle tangent No tangent circle here Aquí no hi ha cap cercle tangent + Add Points to Existing Paths Afegeix punts als traçats existents Circle: Cercle: @msg `ids` names an object twice `ids` indica un objecte dues vegades @msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..2482c2a79f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8449,6 +8449,7 @@ breakText Glyphs Glyfy Tangent Circle Tečná kružnice Tangent Circle Tool Nástroj Tečná kružnice No tangent circle here Zde není žádná tečná kružnice + Add Points to Existing Paths Přidat body do existujících cest Circle: Kružnice: @msg `ids` names an object twice `ids` uvádí některý objekt dvakrát @msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..f45c4105ec 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10505,6 +10505,7 @@ breakText Glyphs Glyffer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkel-værktøj No tangent circle here Ingen tangentcirkel her + Add Points to Existing Paths Tilføj punkter til eksisterende stier Circle: Cirkel: @msg `ids` names an object twice `ids` nævner et objekt to gange @msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..d9d92b5777 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8074,6 +8074,7 @@ breakText Glyphs Glyphen Tangent Circle Tangentialkreis Tangent Circle Tool Tangentialkreis-Werkzeug No tangent circle here Hier kein Tangentialkreis + Add Points to Existing Paths Punkte zu vorhandenen Pfaden hinzufügen Circle: Kreis: @msg `ids` names an object twice `ids` nennt ein Objekt zweimal @msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..34c2319db8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8440,6 +8440,7 @@ breakText Glyphs Γλύφοι Tangent Circle Εφαπτόμενος κύκλος Tangent Circle Tool Εφαπτόμενος κύκλος (Tangent Circle Tool) No tangent circle here Δεν υπάρχει εφαπτόμενος κύκλος εδώ + Add Points to Existing Paths Προσθήκη σημείων σε υπάρχουσες διαδρομές Circle: Κύκλος: @msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές @msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..6eca1a8abe 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8426,6 +8426,7 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Herramienta Círculo tangente No tangent circle here No hay círculo tangente aquí + Add Points to Existing Paths Agregar puntos a trazados existentes Circle: Círculo: @msg `ids` names an object twice `ids` indica un objeto dos veces @msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..bb99ebe8e8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8516,6 +8516,7 @@ breakText Glyphs Merkit Tangent Circle Sivuava ympyrä Tangent Circle Tool Sivuava ympyrä -työkalu No tangent circle here Tässä ei ole sivuavaa ympyrää + Add Points to Existing Paths Lisää pisteitä olemassa oleviin polkuihin Circle: Ympyrä: @msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti @msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..da45f1758a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8445,6 +8445,7 @@ breakText Glyphs Glyphes Tangent Circle Cercle tangent Tangent Circle Tool Outil Cercle tangent No tangent circle here Aucun cercle tangent ici + Add Points to Existing Paths Ajouter des points aux tracés existants Circle: Cercle : @msg `ids` names an object twice `ids` désigne deux fois le même objet @msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..eaaff584d8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4336,6 +4336,7 @@ arrowhead Feather પીંછું Tangent Circle સ્પર્શક વર્તુળ Tangent Circle Tool સ્પર્શક વર્તુળ ટૂલ No tangent circle here અહીં કોઈ સ્પર્શક વર્તુળ નથી + Add Points to Existing Paths હાલના પાથમાં બિંદુઓ ઉમેરો Tangent Circle… સ્પર્શક વર્તુળ… Taper ટેપર Target લક્ષ્ય diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..1c3714447f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5889,6 +5889,7 @@ arrowhead Feather पंख Tangent Circle स्पर्शी वृत्त Tangent Circle Tool स्पर्शी वृत्त टूल No tangent circle here यहाँ कोई स्पर्शी वृत्त नहीं है + Add Points to Existing Paths मौजूदा पाथ में पॉइंट जोड़ें Tangent Circle… स्पर्शी वृत्त… Taper टेपर Target लक्ष्य diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..78e5f306ea 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8435,6 +8435,7 @@ breakText Glyphs Glifák Tangent Circle Érintőkör Tangent Circle Tool Érintőkör eszköz No tangent circle here Itt nincs érintőkör + Add Points to Existing Paths Pontok hozzáadása a meglévő útvonalakhoz Circle: Kör: @msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg @msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..a48310fbbe 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8290,6 +8290,7 @@ breakText Glyphs Glif Tangent Circle Lingkaran singgung Tangent Circle Tool Alat lingkaran singgung No tangent circle here Tidak ada lingkaran singgung di sini + Add Points to Existing Paths Tambahkan titik ke jalur yang ada Circle: Lingkaran: @msg `ids` names an object twice `ids` menyebut satu objek dua kali @msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..02797ebe67 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8112,6 +8112,7 @@ breakText Glyphs Glifi Tangent Circle Cerchio tangente Tangent Circle Tool Strumento Cerchio tangente No tangent circle here Nessun cerchio tangente qui + Add Points to Existing Paths Aggiungi punti ai tracciati esistenti Circle: Cerchio: @msg `ids` names an object twice `ids` indica due volte lo stesso oggetto @msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..5a92e57adc 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10001,6 +10001,7 @@ breakText Glyphs 字形 Tangent Circle 接円 Tangent Circle Tool 接円ツール No tangent circle here ここに接円はありません + Add Points to Existing Paths 既存のパスにポイントを追加 Circle: 円: @msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています @msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..9f3cb89761 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10623,6 +10623,7 @@ breakText Glyphs გლიფები Tangent Circle მხები წრე Tangent Circle Tool მხები წრის ხელსაწყო No tangent circle here აქ მხები წრე არ არის + Add Points to Existing Paths არსებულ ტრაექტორიებზე წერტილების დამატება Circle: წრე: @msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს @msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..1c5588142e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8084,6 +8084,7 @@ breakText Glyphs 글리프 Tangent Circle 접원 Tangent Circle Tool 접원 도구 No tangent circle here 여기에는 접원이 없음 + Add Points to Existing Paths 기존 패스에 포인트 추가 Circle: 원: @msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다 @msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..1ca547d523 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10343,6 +10343,7 @@ breakText Glyphs Glyphs Tangent Circle Raakcirkel Tangent Circle Tool Raakcirkel-gereedschap No tangent circle here Hier geen raakcirkel + Add Points to Existing Paths Punten toevoegen aan bestaande paden Circle: Cirkel: @msg `ids` names an object twice `ids` noemt een object twee keer @msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..554c02ee05 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8308,6 +8308,7 @@ breakText Glyphs Glify Tangent Circle Okrąg styczny Tangent Circle Tool Narzędzie Okrąg styczny No tangent circle here Brak okręgu stycznego w tym miejscu + Add Points to Existing Paths Dodaj punkty do istniejących ścieżek Circle: Okrąg: @msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy @msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..deb2dd67c6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8468,6 +8468,7 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Ferramenta Círculo tangente No tangent circle here Nenhum círculo tangente aqui + Add Points to Existing Paths Adicionar Pontos aos Caminhos Existentes Circle: Círculo: @msg `ids` names an object twice `ids` indica um objeto duas vezes @msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..59f7ef391c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8440,6 +8440,7 @@ breakText Glyphs Глифы Tangent Circle Касательная окружность Tangent Circle Tool Инструмент «Касательная окружность» No tangent circle here Здесь нет касательной окружности + Add Points to Existing Paths Добавить точки к существующим контурам Circle: Окружность: @msg `ids` names an object twice `ids` указывает объект дважды @msg select two or three paths or compound paths выделите два или три контура или составных контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..6c161e74d3 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8484,6 +8484,7 @@ breakText Glyphs Glyfer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkelverktyget No tangent circle here Ingen tangentcirkel här + Add Points to Existing Paths Lägg till punkter i befintliga banor Circle: Cirkel: @msg `ids` names an object twice `ids` anger ett objekt två gånger @msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..81253fbab6 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -937,6 +937,16 @@ fn tangent_circle_tool_note_is_in_complete_catalogs() { } } +/// The label of the Tangent Circle tool's Add Points to Existing Paths option, which its options +/// dialog takes from the tools crate. +#[test] +fn tangent_circle_tool_add_points_label_is_in_complete_catalogs() { + let label = vectorcraft_tools::addons::tangent_circle::ADD_POINTS; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } +} + /// The Artboard tool's add buttons take their tooltips from the tools crate, which the `tl!` scan /// does not read, so each complete catalog is checked for them here. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..1b1a25a9c5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10339,6 +10339,7 @@ breakText Glyphs Glifler Tangent Circle Teğet Daire Tangent Circle Tool Teğet Daire Aracı No tangent circle here Burada teğet daire yok + Add Points to Existing Paths Mevcut Yollara Nokta Ekle Circle: Daire: @msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor @msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..faf64996bf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8094,6 +8094,7 @@ breakText Glyphs Гліфи Tangent Circle Дотичне коло Tangent Circle Tool Інструмент «Дотичне коло» No tangent circle here Тут немає дотичного кола + Add Points to Existing Paths Додати точки до наявних контурів Circle: Коло: @msg `ids` names an object twice `ids` указує об’єкт двічі @msg select two or three paths or compound paths виділіть два або три контури чи складені контури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..2903e0539e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8140,6 +8140,7 @@ breakText Glyphs Glyph Tangent Circle Đường tròn tiếp xúc Tangent Circle Tool Công cụ Đường tròn tiếp xúc No tangent circle here Không có đường tròn tiếp xúc ở đây + Add Points to Existing Paths Thêm điểm vào đường dẫn hiện có Circle: Đường tròn: @msg `ids` names an object twice `ids` nêu một đối tượng hai lần @msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..08bd68d3e8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8318,6 +8318,7 @@ breakText Glyphs 字形 Tangent Circle 相切圆 Tangent Circle Tool 相切圆工具 No tangent circle here 此处没有相切圆 + Add Points to Existing Paths 在现有路径上添加锚点 Circle: 圆: @msg `ids` names an object twice `ids` 重复指定了同一个对象 @msg select two or three paths or compound paths 请选择两个或三个路径或复合路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..eae2ba19a1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8142,6 +8142,7 @@ breakText Glyphs 字符 Tangent Circle 相切圓 Tangent Circle Tool 相切圓工具 No tangent circle here 此處沒有相切圓 + Add Points to Existing Paths 在現有路徑上增加錨點 Circle: 圓: @msg `ids` names an object twice `ids` 將同一個物件指定了兩次 @msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..87eb6c5986 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14566,8 +14566,17 @@ Tools: change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a canceled preview does not leave a circle worked out on the previewed paths. - Option (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36). `tool.setOption` - gives an error for a value outside that range or one that is not a number, and for any other option. + With `addPoints` on, the circle also adds an anchor point to the first segment and to the second segment (or the + one beside it) where it touches them, with `path.insertAnchor` at that point, so the segments are split without + changing their shape; the anchors and the circle are one `command.batch` undo step, and one Undo removes all of them. + When a touched path was not selected, a `select.set` step puts the selection back before the circle is drawn, so + Draw Behind places the circle behind the objects that were selected. + A touch within 0.05 screen pixels of an existing anchor adds no anchor there; when neither touch adds one, only the + circle is drawn. Alt (Option on macOS) held at the release turns `addPoints` the other way for that circle, and a + dot right of and below the pointer shows while it is in effect, following Alt as it is pressed and let go. + Options (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36) and `addPoints` + (Add Points to Existing Paths, true or false, false). `tool.setOption` gives an error for a `radius` outside that + range or not a number, an `addPoints` that is not true or false, and any other option. - **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed, on any path that can be edited, selected or not. A click runs `addon.pathtools.trim` with `at`, for the path within 4 screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..fefd8b7352 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2997,6 +2997,8 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +Add Points to Existing Paths (2026-11-20): the tool's `addPoints` option (in its options, off to start) also adds an anchor point where the circle touches each of the two segments, splitting them without changing their shape, in the circle's undo step; a touch at an existing anchor adds none. Alt held at the release turns the option the other way for that circle, and a dot beside the pointer shows while it is in effect. Tests: `addons::tangent_circle::tests::add_points_*` in `vectorcraft-tools`, `the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step` in `vectorcraft-engine`, and the options dialog and catalog tests in `vectorcraft-ui-egui`. + ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..37e1f716c7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -554,7 +554,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle Tool (also in the All Tools drawer): a click on a path segment, then on another, draws the circle tangent to the first at the point clicked that touches the second or a segment beside it; Shift uses the tool's radius (36 pt to start, set in its options) and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it; the circle shows with its center and radii first, or a note when there is none; Add Points to Existing Paths (in its options; Alt at the release turns it the other way, a dot beside the pointer while it is in effect) also adds an anchor point where the circle touches each segment; one undo step | done | tool `tangentCircle` (in `crates/tools/src/addons/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | From ea78ee5022c61e7435345391d8487f6c40ee25a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:59:11 -0800 Subject: [PATCH 07/63] Windows: the Paintbrush reads an airbrush pen's stylus wheel through Wintab Pointer messages carry no field for an airbrush pen's finger wheel, so a brush set to Stylus Wheel drew the half-way value on Windows. The new windows_wintab module reads the wheel from the tablet driver's Wintab interface as the tangential pressure of a cursor the driver reports as an airbrush, placed within its device's DVC_TPRESSURE range. - Wintab32.dll is loaded at run time from the system directory only (LoadLibraryExW with LOAD_LIBRARY_SEARCH_SYSTEM32). Without it, without one of its exports, or when a call fails, Windows pens read no wheel and draw as before. - The context is opened from the driver's default context with packet messages on and CXO_SYSTEM and CXO_PEN off, so it moves no cursor and makes no press. It follows the top-level window the pen is over. - WTInfoW answers are size-checked against a null-buffer call and read into a larger buffer; packets are read into a buffer larger than any packet and decoded from the fields the context asked for; a value outside the axis range reads as no wheel. - Pointer messages keep the pressure, end, tilt and rotation. A pen's message takes the airbrush's last wheel since it came near, or, when several cursors were read, the one whose latest packet came within 200 ms of the message, and none when more than one or none did. 0 counts as no wheel until the pen reports another value, as on macOS, and the readings start afresh on proximity, a cursor change, the other end, a canceled press and leaving the window. Docs: docs/mcp.md, docs/target-app-parity.md. --- apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/windows_stylus.rs | 71 ++- apps/vectorcraft/src/windows_wintab.rs | 816 +++++++++++++++++++++++++ crates/ui-egui/src/stylus.rs | 5 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 4 +- 6 files changed, 887 insertions(+), 17 deletions(-) create mode 100644 apps/vectorcraft/src/windows_wintab.rs diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 29cb56bdfa..8ef7f04e6b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -79,6 +79,7 @@ mod windows_alt_codes; mod windows_cores; mod windows_screen_color; mod windows_stylus; +mod windows_wintab; mod xwayland; use vectorcraft_engine::Session; diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index e1ea35104d..15fcd4b9e2 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -24,6 +24,8 @@ //! `rotation` in degrees 0..359 clockwise //! (). //! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come. +//! An airbrush pen's finger wheel comes from the tablet driver's Wintab interface instead, when it +//! has one ([`crate::windows_wintab`]). #![cfg_attr(not(windows), allow(dead_code))] use std::cell::RefCell; @@ -38,6 +40,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020; /// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left /// detection range. const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002; +/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled. +const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000; /// At most this many pointer contacts wait for their touch event. const MAX_PENDING: usize = 16; /// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`. @@ -101,13 +105,19 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let Some(feed) = FEED.get() else { return false; }; + crate::windows_wintab::msg_hook(msg); + if forgets_wheel(msg.message, msg.wParam.0) { + crate::windows_wintab::forget(); + } let read_pen = || { let mut info = POINTER_PEN_INFO::default(); // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; - let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); + let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; + let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, eraser); + let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation, wheel); Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) }; // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. @@ -134,12 +144,27 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, po /// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is /// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the /// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no -/// field for an airbrush pen's finger wheel, so the pose has none. -fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose { +/// field for an airbrush pen's finger wheel: `wheel` is the one the tablet driver's Wintab +/// interface reported for the message, if any ([`crate::windows_wintab`]). +fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32, wheel: Option) -> PenPose { let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 }; let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]); let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32); - PenPose { tilt, rotation, wheel: None }.sanitized() + PenPose { tilt, rotation, wheel }.sanitized() +} + +/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message +/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the +/// window. +fn forgets_wheel(message: u32, wparam: usize) -> bool { + let flags = wparam >> 16; + match message { + WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => { + flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0 + } + WM_POINTERLEAVE => true, + _ => false, + } } /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, @@ -427,16 +452,42 @@ mod tests { #[test] fn a_pens_tilt_and_rotation_come_where_it_reports_them() { let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; - assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None }); - assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither"); - assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis"); - assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel"); - let wild = pen_pose(all, 400, i32::MIN, 720); + assert_eq!(pen_pose(all, 30, -45, 90, None), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None }); + assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90, None), PenPose::default(), "a pen that reports neither"); + assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90, None), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis"); + assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359, None), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel"); + let wild = pen_pose(all, 400, i32::MIN, 720, None); assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges"); - let pose = pen_pose(all, 10, 20, 180); + let pose = pen_pose(all, 10, 20, 180, None); assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose); } + #[test] + fn an_airbrush_wheel_goes_into_the_pose() { + let pose = pen_pose(PEN_MASK_PRESSURE, 0, 0, 0, Some(0.25)); + assert_eq!(pose, PenPose { wheel: Some(0.25), ..PenPose::default() }); + let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; + let pose = pen_pose(all, 10, 20, 180, Some(0.75)); + assert_eq!(pose, PenPose { tilt: Some([10.0, 20.0]), rotation: Some(180.0), wheel: Some(0.75) }, "with the tilt and rotation"); + assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, pose), PenSample { pressure: 0.5, eraser: false, pose }, "the pressure as before"); + assert_eq!(pen_pose(0, 0, 0, 0, Some(f32::NAN)).wheel, None, "not a number"); + } + + #[test] + fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7; + for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!forgets_wheel(m, in_range), "{m:#x}"); + assert!(forgets_wheel(m, 7), "out of range: {m:#x}"); + assert!(forgets_wheel(m, canceled), "canceled: {m:#x}"); + } + assert!(forgets_wheel(WM_POINTERLEAVE, in_range)); + // WM_MOUSEMOVE and WT_PACKET. + assert!(!forgets_wheel(0x0200, 0)); + assert!(!forgets_wheel(0x7FF0, 7)); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5); diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs new file mode 100644 index 0000000000..2c4166821a --- /dev/null +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -0,0 +1,816 @@ +//! Windows: an airbrush pen's finger wheel. `POINTER_PEN_INFO` has no field for it +//! (), so +//! [`crate::windows_stylus`] keeps reading the pressure, end, tilt and rotation from pointer +//! messages, and this module reads only the wheel from the tablet driver's Wintab interface, as +//! its tangential pressure (`pkTangentPressure`), when the driver installs one. The Wintab +//! reference describes the context, packet and message calls used here +//! (), and the +//! Windows Ink comparison says the wheel comes only through Wintab +//! (). +//! +//! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen +//! comes over a window. Without it, without one of its exports, or when a call fails, the pens +//! read no wheel and draw as before; the user sees no error. +//! - The context is opened from the driver's default context for the window that owns the pen's +//! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor +//! and makes no press. When the pen comes over another top-level window, such as a separate +//! document window, the context closes and opens again for that window, and the readings start +//! afresh ([`next_context`]). Each `WT_PACKET` for that window and context is read with `WTPacket` into +//! a buffer larger than any packet, and decoded from the fields the context asked for +//! ([`decode`]). +//! - Only a cursor the driver reports as an airbrush (`(CSR_TYPE & 0x0F06) == 0x0902`, from the +//! Wintab basics page: ) +//! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, +//! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 +//! ([`Axis::wheel`]); a value outside it reads as none. +//! - A pointer message of a pen takes the wheel of the airbrush read since the readings started +//! afresh, however long ago its last packet came, since a pen held still sends none. When +//! several cursors were read, it takes the one whose latest packet came within [`MAX_SKEW_MS`] of +//! the message, and none when two are that recent or none is ([`Readings::wheel_at`]). As on +//! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the +//! readings start afresh when a cursor +//! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns +//! to its other end, a press is canceled, the pen leaves the window or detection range, or the +//! context closes. These rules are VectorCraft's own. +//! +//! The context closes when the driver closes it or its information changes (`WT_INFOCHANGE`), and +//! is dropped when its window no longer exists; a later pen message opens it again. +#![cfg_attr(not(windows), allow(dead_code))] + +/// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. +const WT_DEFBASE: u32 = 0x7FF0; +/// `WT_PACKET`, `WT_CTXCLOSE`, `WT_PROXIMITY`, `WT_INFOCHANGE` and `WT_CSRCHANGE` at that base. +const WT_PACKET: u32 = WT_DEFBASE; +const WT_CTXCLOSE: u32 = WT_DEFBASE + 2; +const WT_PROXIMITY: u32 = WT_DEFBASE + 5; +const WT_INFOCHANGE: u32 = WT_DEFBASE + 6; +const WT_CSRCHANGE: u32 = WT_DEFBASE + 7; + +/// `CXO_SYSTEM`, `CXO_PEN`, `CXO_MESSAGES` and `CXO_CSRMESSAGES` (`wintab.h`), in `lcOptions`. +const CXO_SYSTEM: u32 = 0x0001; +const CXO_PEN: u32 = 0x0002; +const CXO_MESSAGES: u32 = 0x0004; +const CXO_CSRMESSAGES: u32 = 0x0008; + +/// The packet fields (`PK_*`, `pktdef.h`) in the order a packet holds them, each with its size in +/// bytes: `pkContext` is a handle, `pkOrientation` and `pkRotation` three 32-bit values each, and +/// the others one 32-bit value. +const PK_CONTEXT: u32 = 0x0001; +const PK_STATUS: u32 = 0x0002; +const PK_TIME: u32 = 0x0004; +const PK_CHANGED: u32 = 0x0008; +const PK_SERIAL_NUMBER: u32 = 0x0010; +const PK_CURSOR: u32 = 0x0020; +const PK_BUTTONS: u32 = 0x0040; +const PK_X: u32 = 0x0080; +const PK_Y: u32 = 0x0100; +const PK_Z: u32 = 0x0200; +const PK_NORMAL_PRESSURE: u32 = 0x0400; +const PK_TANGENT_PRESSURE: u32 = 0x0800; +const PK_ORIENTATION: u32 = 0x1000; +const PK_ROTATION: u32 = 0x2000; +const FIELDS: [(u32, usize); 14] = [ + (PK_CONTEXT, std::mem::size_of::()), + (PK_STATUS, 4), + (PK_TIME, 4), + (PK_CHANGED, 4), + (PK_SERIAL_NUMBER, 4), + (PK_CURSOR, 4), + (PK_BUTTONS, 4), + (PK_X, 4), + (PK_Y, 4), + (PK_Z, 4), + (PK_NORMAL_PRESSURE, 4), + (PK_TANGENT_PRESSURE, 4), + (PK_ORIENTATION, 12), + (PK_ROTATION, 12), +]; + +/// The fields the context asks for (`lcPktData`), all absolute: the status, the cursor, the +/// position and the tangential pressure. +const PACKET_DATA: u32 = PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The changes that make a packet (`lcMoveMask`): a move, or a turn of the wheel in place. +const MOVE_MASK: u32 = PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The bytes `WTPacket` writes into: more than a packet of every field. +const PACKET_BUFFER: usize = 256; + +/// `TPS_PROXIMITY` and `TPS_QUEUE_ERR` (`wintab.h`), in `pkStatus`: the cursor is out of the +/// context, and the queue overflowed. +const TPS_PROXIMITY: u32 = 0x0001; +const TPS_QUEUE_ERR: u32 = 0x0002; + +/// The `LOGCONTEXTW` (`wintab.h`) as 32-bit words: a 40-character name, then `lcOptions`, +/// `lcStatus`, `lcLocks`, `lcMsgBase`, `lcDevice`, `lcPktRate`, `lcPktData`, `lcPktMode`, +/// `lcMoveMask`, `lcBtnDnMask` and `lcBtnUpMask`, and 22 words of extents and sensitivities. +const LOGCONTEXT_WORDS: usize = 53; +const _: () = assert!(LOGCONTEXT_WORDS * 4 == 212, "sizeof(LOGCONTEXTW)"); +const LC_OPTIONS: usize = 20; +const LC_MSG_BASE: usize = 23; +const LC_PKT_DATA: usize = 26; +const LC_PKT_MODE: usize = 27; +const LC_MOVE_MASK: usize = 28; +const LC_BTN_DN_MASK: usize = 29; +const LC_BTN_UP_MASK: usize = 30; + +/// `WTInfoW` categories and indexes (`wintab.h`): the interface's device count, the default +/// context, a device's first cursor, cursor count and tangential-pressure range, and a cursor's +/// packet fields and type. +const WTI_INTERFACE: u32 = 1; +const IFC_NDEVICES: u32 = 4; +const WTI_DEFCONTEXT: u32 = 3; +const WTI_DEVICES: u32 = 100; +const DVC_NCSRTYPES: u32 = 3; +const DVC_FIRSTCSR: u32 = 4; +const DVC_TPRESSURE: u32 = 16; +const WTI_CURSORS: u32 = 200; +const CSR_PKTDATA: u32 = 3; +const CSR_TYPE: u32 = 20; +/// Cursor and device numbers stay below the next category's base. +const MAX_INDEX: u32 = 100; +/// At most this many devices are looked through for a cursor's device. +const MAX_DEVICES: u32 = 16; + +/// A packet and a pointer message at most this far apart, in the message clock's milliseconds, +/// belong together. +const MAX_SKEW_MS: u32 = 200; +/// At most this many cursors' readings are kept. +const MAX_READINGS: usize = 4; + +/// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, +/// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on +/// a move or a turn of the wheel, and no button events. +fn configure(words: &mut [u32; LOGCONTEXT_WORDS]) { + words[LC_OPTIONS] = (words[LC_OPTIONS] | CXO_MESSAGES | CXO_CSRMESSAGES) & !(CXO_SYSTEM | CXO_PEN); + words[LC_MSG_BASE] = WT_DEFBASE; + words[LC_PKT_DATA] = PACKET_DATA; + words[LC_PKT_MODE] = 0; + words[LC_MOVE_MASK] = MOVE_MASK; + words[LC_BTN_DN_MASK] = 0; + words[LC_BTN_UP_MASK] = 0; +} + +/// The size in bytes of a packet holding the fields of `mask`. +fn packet_size(mask: u32) -> usize { + FIELDS.iter().filter(|(f, _)| mask & f != 0).map(|(_, n)| n).sum() +} + +/// The 32-bit field `field` of a packet holding the fields of `mask`, or `None` when the mask +/// leaves it out, it is not a 32-bit field, or `bytes` is too short. +fn field(bytes: &[u8], mask: u32, field: u32) -> Option { + if mask & field == 0 || bytes.len() < packet_size(mask) { + return None; + } + let mut at = 0; + for &(f, n) in &FIELDS { + if f == field { + let word = bytes.get(at..at + 4).filter(|_| n == 4)?; + return Some(u32::from_ne_bytes(word.try_into().ok()?)); + } + if mask & f != 0 { + at += n; + } + } + None +} + +/// What a packet says about the wheel. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Packet { + status: u32, + cursor: u32, + tangent: u32, +} + +/// The status, cursor and tangential pressure of a packet holding the fields of `mask`. +fn decode(bytes: &[u8], mask: u32) -> Option { + Some(Packet { status: field(bytes, mask, PK_STATUS)?, cursor: field(bytes, mask, PK_CURSOR)?, tangent: field(bytes, mask, PK_TANGENT_PRESSURE)? }) +} + +/// A device's tangential-pressure range (`AXIS`'s `axMin` and `axMax`). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Axis { + min: i32, + max: i32, +} + +impl Axis { + /// The wheel, 0..1, for the absolute value `raw`: 0 at `axMin`, 1 at `axMax`. `pktdef.h` gives + /// an absolute tangential pressure as unsigned; with a range below 0 it is read as signed. A + /// value outside the range reads as none. + fn wheel(self, raw: u32) -> Option { + let (min, max) = (i64::from(self.min), i64::from(self.max)); + if min >= max { + return None; + } + let v = if min < 0 { i64::from(raw as i32) } else { i64::from(raw) }; + (min..=max).contains(&v).then(|| ((v - min) as f64 / (max - min) as f64) as f32) + } +} + +/// Whether a cursor of this `CSR_TYPE` is an airbrush. +fn is_airbrush(csr_type: u32) -> bool { + csr_type & 0x0F06 == 0x0902 +} + +/// The wheel range of a cursor of `csr_type` whose packets carry the fields of `csr_pktdata`, on a +/// device whose `DVC_TPRESSURE` reads as `axis` (`axMin`, `axMax`, `axUnits`, `axResolution`): +/// `None` unless it is an airbrush with a tangential pressure and the range is not empty. +fn wheel_axis(csr_type: u32, csr_pktdata: u32, axis: Option<[u32; 4]>) -> Option { + let [min, max, ..] = axis?; + let axis = Axis { min: min as i32, max: max as i32 }; + (is_airbrush(csr_type) && csr_pktdata & PK_TANGENT_PRESSURE != 0 && axis.min < axis.max).then_some(axis) +} + +/// The device of `cursor`, from each device's first cursor and cursor count (`DVC_FIRSTCSR`, +/// `DVC_NCSRTYPES`), or `None` when no device or more than one has it. +fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { + let mut found = devices.iter().enumerate().filter(|(_, (first, n))| first.checked_add(*n).is_some_and(|end| (*first..end).contains(&cursor))); + let (d, _) = found.next()?; + found.next().is_none().then_some(d) +} + +/// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. +fn near(a: u32, b: u32) -> bool { + (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS +} + +/// The latest packet of a cursor near the context. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Reading { + cursor: u32, + /// The cursor's wheel range, `None` for a cursor without a wheel. + axis: Option, + raw: u32, + /// The message time of the packet. + time: u32, + /// The cursor has reported a value other than 0 since the readings started afresh. + moved: bool, +} + +/// The latest packet of each cursor near the context, until the readings start afresh. +#[derive(Clone, Debug, Default)] +struct Readings { + list: Vec, + /// The end of the pen the last pointer message read, `Some(true)` for the eraser end. + eraser: Option, +} + +impl Readings { + /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of + /// a cursor out of the context, or after the queue overflowed, drops that cursor's reading. + fn packet(&mut self, p: Packet, axis: Option, time: u32) { + let at = self.list.iter().position(|r| r.cursor == p.cursor); + if p.status & (TPS_PROXIMITY | TPS_QUEUE_ERR) != 0 { + if let Some(i) = at { + self.list.remove(i); + } + return; + } + let moved = at.is_some_and(|i| self.list[i].moved && self.list[i].axis == axis) || p.tangent != 0; + let reading = Reading { cursor: p.cursor, axis, raw: p.tangent, time, moved }; + match at { + Some(i) => self.list[i] = reading, + None => { + if self.list.len() >= MAX_READINGS { + self.list.remove(0); + } + self.list.push(reading); + } + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, or the + /// context closed. + fn forget(&mut self) { + self.list.clear(); + self.eraser = None; + } + + /// The wheel for a pointer message of a pen at the message time `time` with its `eraser` end, + /// if the cursor it comes from is an airbrush: the one cursor read since the readings started + /// afresh, however long ago its last packet came (a pen held still sends none), or, when + /// several were, the one whose latest packet is within [`MAX_SKEW_MS`] of the message. `None` + /// when no cursor, or more than one, is that recent, or the cursor has read only 0 since the + /// readings started afresh. A turn to the other end starts them afresh first. + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + if self.eraser.is_some_and(|e| e != eraser) { + self.forget(); + } + self.eraser = Some(eraser); + let r = match self.list.as_slice() { + [one] => one, + list => { + let mut near_time = list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; + } + r + } + }; + if !r.moved { + return None; + } + r.axis?.wheel(r.raw) + } +} + +/// What a pen message does to the open context before it is opened for the pen's window. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Current { + /// Nothing is open, or the context is the pen window's. + Keep, + /// The context's window is gone: drop the handle without a call on it. + Drop, + /// The context is another window's: close it with `WTClose`. + Close, +} + +/// The context step for a pen message to a window owned by `owner`: what happens to the open +/// context, whose window is `current` with whether that window still exists, and whether a context +/// is opened for `owner`. The context follows the window the pen draws in. An open is tried once +/// for a window until another window is tried or the driver closes or changes the context +/// (`tried`). +fn next_context(current: Option<(usize, bool)>, tried: Option, owner: usize) -> (Current, bool) { + let step = match current { + Some((_, false)) => Current::Drop, + Some((w, true)) if w == owner => return (Current::Keep, false), + Some(_) => Current::Close, + None => Current::Keep, + }; + (step, tried != Some(owner) || step != Current::Keep) +} + +/// What a message does to the readings and the context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Message { + /// A packet with this serial number is waiting for the context `lparam` names. + Packet { + serial: u32, + ctx: usize, + }, + /// The readings start afresh for the context it names. + Forget { + ctx: usize, + }, + /// The context it names has closed. + Closed { + ctx: usize, + }, + /// The driver's information changed: the context closes and opens again. + InfoChange, + Other, +} + +/// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` +/// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. +fn message(message: u32, wparam: usize, lparam: isize) -> Message { + match message { + WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, + WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, + WT_PROXIMITY => Message::Forget { ctx: wparam }, + WT_CTXCLOSE => Message::Closed { ctx: wparam }, + WT_INFOCHANGE => Message::InfoChange, + _ => Message::Other, + } +} + +#[cfg(windows)] +pub use win::{forget, msg_hook, pen_wheel}; + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win { + use std::cell::RefCell; + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows::Win32::Foundation::HWND; + use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::UI::WindowsAndMessaging::{GA_ROOTOWNER, GetAncestor, IsWindow, MSG}; + use windows::core::{s, w}; + + use super::{ + Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, + MAX_READINGS, Message, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, configure, decode, + device_of, message, next_context, wheel_axis, + }; + + /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). + type WtInfo = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32; + type WtOpen = unsafe extern "system" fn(*mut c_void, *mut c_void, i32) -> *mut c_void; + type WtClose = unsafe extern "system" fn(*mut c_void) -> i32; + type WtPacket = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + + #[derive(Clone, Copy)] + struct Api { + info: WtInfo, + open: WtOpen, + close: WtClose, + packet: WtPacket, + } + + /// The bytes a packet is read into. + #[repr(C, align(8))] + struct PacketBuffer([u8; PACKET_BUFFER]); + + /// An open context and the window that owns it. + struct Context { + handle: *mut c_void, + hwnd: *mut c_void, + } + + #[derive(Default)] + struct State { + context: Option, + /// The window an open was last tried for ([`next_context`]). + tried: Option<*mut c_void>, + /// Each cursor's wheel range, as the driver reported it. + cursors: Vec<(u32, Option)>, + readings: Readings, + } + + thread_local! { + static STATE: RefCell = RefCell::new(State::default()); + } + + /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. + fn api() -> Option { + static API: OnceLock> = OnceLock::new(); + *API.get_or_init(|| { + // SAFETY: Wintab32.dll is loaded from the system directory only, and stays loaded for + // the process, so the function pointers below stay valid. + let module = unsafe { LoadLibraryExW(w!("Wintab32.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?; + // SAFETY: the names are NUL-terminated, and the module is loaded. + let (info, open, close, packet) = unsafe { + ( + GetProcAddress(module, s!("WTInfoW"))?, + GetProcAddress(module, s!("WTOpenW"))?, + GetProcAddress(module, s!("WTClose"))?, + GetProcAddress(module, s!("WTPacket"))?, + ) + }; + type Proc = unsafe extern "system" fn() -> isize; + // SAFETY: the exports have these signatures (`wintab.h`). + unsafe { + Some(Api { + info: std::mem::transmute::(info), + open: std::mem::transmute::(open), + close: std::mem::transmute::(close), + packet: std::mem::transmute::(packet), + }) + } + }) + } + + /// `WTInfoW`'s answer for `category` and `index`, when it is exactly `N` 32-bit words. + fn info(api: Api, category: u32, index: u32) -> Option<[u32; N]> { + // SAFETY: a null buffer asks for the size only. + let size = unsafe { (api.info)(category, index, std::ptr::null_mut()) } as usize; + if N > 128 || size != N * 4 { + return None; + } + // Room for more than asked, should the driver write more than it said. + let mut buf = [0u32; 128]; + // SAFETY: `buf` holds 512 bytes, more than the size the driver gave. + let wrote = unsafe { (api.info)(category, index, buf.as_mut_ptr().cast()) } as usize; + let mut out = [0u32; N]; + out.copy_from_slice(buf.get(..N)?); + (wrote == N * 4).then_some(out) + } + + /// The wheel range of `cursor`, `None` for a cursor without one or one the driver does not + /// describe. + fn cursor_axis(api: Api, cursor: u32) -> Option { + if cursor >= MAX_INDEX { + return None; + } + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE)?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA)?; + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES)?; + let mut devices = vec![]; + for d in 0..count.min(MAX_DEVICES) { + devices.push((info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR)?[0], info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES)?[0])); + } + let device = u32::try_from(device_of(cursor, &devices)?).ok()?; + wheel_axis(csr_type, csr_pktdata, info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE)) + } + + fn is_window(hwnd: *mut c_void) -> bool { + // SAFETY: `IsWindow` takes any handle value and reads no caller memory. + unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() + } + + impl State { + fn close(&mut self, api: Api) { + if let Some(c) = self.context.take() { + // SAFETY: the handle came from `WTOpenW` and has not been closed. + unsafe { (api.close)(c.handle) }; + } + self.readings.forget(); + } + + /// Moves the context to the window that owns `hwnd` ([`next_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void) { + // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. + let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; + let owner = if owner.is_null() { hwnd } else { owner }; + let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); + let (step, open) = next_context(current, self.tried.map(|w| w as usize), owner as usize); + match step { + Current::Keep => {} + Current::Drop => { + self.context = None; + self.readings.forget(); + } + Current::Close => self.close(api), + } + if !open { + return; + } + self.tried = Some(owner); + let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; + configure(&mut words); + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + if !handle.is_null() { + self.context = Some(Context { handle, hwnd: owner }); + } + } + + fn ours(&self, hwnd: *mut c_void, ctx: usize) -> Option<*mut c_void> { + self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) + } + + fn axis(&mut self, api: Api, cursor: u32) -> Option { + if let Some(&(_, axis)) = self.cursors.iter().find(|(c, _)| *c == cursor) { + return axis; + } + let axis = cursor_axis(api, cursor); + if self.cursors.len() >= MAX_READINGS * 4 { + self.cursors.remove(0); + } + self.cursors.push((cursor, axis)); + axis + } + } + + /// winit's message hook for the Wintab messages: reads each packet of the context and starts + /// the readings afresh on a cursor's change or proximity. It never consumes the message. + pub fn msg_hook(msg: &MSG) { + let what = message(msg.message, msg.wParam.0, msg.lParam.0); + if what == Message::Other { + return; + } + let Some(api) = api() else { return }; + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + match what { + Message::Packet { serial, ctx } => { + let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; + let mut buf = PacketBuffer([0; PACKET_BUFFER]); + // SAFETY: the handle is the open context's, and `buf` holds more bytes than a + // packet of every field. + if unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } == 0 { + return; + } + let Some(p) = decode(&buf.0, PACKET_DATA) else { return }; + let axis = s.axis(api, p.cursor); + s.readings.packet(p, axis, msg.time); + } + Message::Forget { ctx } => { + if s.ours(msg.hwnd.0, ctx).is_some() { + s.readings.forget(); + } + } + Message::Closed { ctx } => { + if s.context.as_ref().is_some_and(|c| c.handle as usize == ctx) { + s.context = None; + s.tried = None; + s.readings.forget(); + } + } + Message::InfoChange => { + s.close(api); + s.tried = None; + s.cursors.clear(); + } + Message::Other => {} + } + }); + } + + /// The wheel for a pointer message of a pen to `hwnd` at the message time `time`, with its + /// `eraser` end ([`Readings::wheel_at`]), opening the context first when none is open. + pub fn pen_wheel(hwnd: HWND, time: u32, eraser: bool) -> Option { + let api = api()?; + STATE.with(|s| { + let mut s = s.try_borrow_mut().ok()?; + s.open_for(api, hwnd.0); + s.readings.wheel_at(time, eraser) + }) + } + + /// Start the readings afresh: the pen left the window or detection range, or a press was + /// canceled. + pub fn forget() { + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.readings.forget(); + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler + /// when it has none, and the wider fields hold filler bytes. + fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { + let mut out = vec![]; + for &(f, n) in &FIELDS { + if mask & f == 0 { + continue; + } + let v = values.iter().find(|(k, _)| *k == f).map_or(0xAAAA_AAAA, |&(_, v)| v); + if n == 4 { + out.extend(v.to_ne_bytes()); + } else { + out.extend(std::iter::repeat_n(0xEE, n)); + } + } + out + } + + #[test] + fn the_context_asks_for_the_wheel_without_the_system_cursor() { + let mut words = [0u32; LOGCONTEXT_WORDS]; + words[LC_OPTIONS] = CXO_SYSTEM | CXO_PEN | 0x8000; + words[LC_MSG_BASE] = 0x1234; + words[LC_BTN_DN_MASK] = !0; + words[LC_BTN_UP_MASK] = !0; + words[LC_PKT_MODE] = PK_TANGENT_PRESSURE; + words[31] = 77; + configure(&mut words); + assert_eq!(words[LC_OPTIONS], CXO_MESSAGES | CXO_CSRMESSAGES | 0x8000, "the driver's other options stay"); + assert_eq!(words[LC_MSG_BASE], WT_DEFBASE); + assert_eq!(words[LC_PKT_DATA], PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE); + assert_eq!(words[LC_PKT_MODE], 0, "absolute"); + assert_eq!(words[LC_MOVE_MASK] & PK_TANGENT_PRESSURE, PK_TANGENT_PRESSURE, "a turn in place makes a packet"); + assert_eq!((words[LC_BTN_DN_MASK], words[LC_BTN_UP_MASK]), (0, 0)); + assert_eq!(words[31], 77, "the extents stay the driver's"); + } + + #[test] + fn packets_are_read_in_the_order_of_their_fields() { + let want = Packet { status: 0, cursor: 3, tangent: 600 }; + let p = bytes(PACKET_DATA, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), 20); + assert_eq!(decode(&p, PACKET_DATA), Some(want)); + // Every field before the tangential pressure, the context handle and the orientation + // after it. + let all = FIELDS.iter().fold(0, |m, (f, _)| m | f); + let p = bytes(all, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), packet_size(all)); + assert_eq!(packet_size(all), std::mem::size_of::() + 4 * 11 + 24); + assert_eq!(decode(&p, all), Some(want)); + assert_eq!(decode(&p[..p.len() - 1], all), None, "a short packet"); + assert_eq!(decode(&p, PK_STATUS | PK_CURSOR), None, "no tangential pressure"); + assert_eq!(field(&p, all, PK_ORIENTATION), None, "not a 32-bit field"); + assert!(packet_size(all) <= PACKET_BUFFER); + } + + #[test] + fn only_an_airbrush_with_a_range_reads_a_wheel() { + let range = |min: i32, max: i32| Some([min as u32, max as u32, 0, 0]); + let airbrush = 0x0902; + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 1023)), Some(Axis { min: 0, max: 1023 })); + assert_eq!(wheel_axis(0x090A, PK_TANGENT_PRESSURE, range(-1023, 1023)), Some(Axis { min: -1023, max: 1023 }), "its other end"); + assert_eq!(wheel_axis(0x0802, PACKET_DATA, range(0, 1023)), None, "a general stylus"); + assert_eq!(wheel_axis(0x0804, PACKET_DATA, range(0, 1023)), None, "an Art Pen"); + assert_eq!(wheel_axis(airbrush, PK_X | PK_Y, range(0, 1023)), None, "no tangential pressure"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, None), None, "no range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 0)), None, "an empty range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(1023, 0)), None, "a falling range"); + } + + #[test] + fn the_wheel_is_its_place_in_the_range() { + let axis = Axis { min: 0, max: 1000 }; + assert_eq!(axis.wheel(0), Some(0.0)); + assert_eq!(axis.wheel(250), Some(0.25)); + assert_eq!(axis.wheel(1000), Some(1.0)); + assert_eq!(axis.wheel(1001), None, "past the end"); + assert_eq!(axis.wheel(u32::MAX), None); + let signed = Axis { min: -1000, max: 1000 }; + assert_eq!(signed.wheel(-1000i32 as u32), Some(0.0)); + assert_eq!(signed.wheel(0), Some(0.5)); + assert_eq!(signed.wheel(500), Some(0.75)); + assert_eq!(signed.wheel(i32::MIN as u32), None); + let wide = Axis { min: i32::MIN, max: i32::MAX }; + assert_eq!(wide.wheel(i32::MAX as u32), Some(1.0), "no overflow"); + assert_eq!(Axis { min: 5, max: 5 }.wheel(5), None); + } + + #[test] + fn a_cursor_belongs_to_one_device() { + let devices = [(0, 3), (3, 3)]; + assert_eq!(device_of(1, &devices), Some(0)); + assert_eq!(device_of(4, &devices), Some(1)); + assert_eq!(device_of(6, &devices), None); + assert_eq!(device_of(1, &[(0, 3), (1, 1)]), None, "two devices claim it"); + assert_eq!(device_of(u32::MAX, &[(u32::MAX - 1, 5)]), None, "a range past the end"); + assert_eq!(device_of(0, &[]), None); + } + + const AXIS: Option = Some(Axis { min: 0, max: 1000 }); + + fn packet(cursor: u32, tangent: u32) -> Packet { + Packet { status: 0, cursor, tangent } + } + + #[test] + fn a_pen_message_takes_the_wheel_of_the_recent_airbrush() { + let mut r = Readings::default(); + assert_eq!(r.wheel_at(1000, false), None, "no packet"); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1010, false), Some(0.25)); + assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); + assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.packet(packet(1, 1000), AXIS, u32::MAX - 5); + r.packet(packet(2, 500), None, u32::MAX); + assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + r.packet(packet(1, 1000), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); + r.forget(); + r.packet(packet(2, 500), None, 100); + assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); + r.packet(packet(1, 2000), AXIS, 300); + assert_eq!(r.wheel_at(500, false), None, "a value past the range"); + } + + #[test] + fn zero_is_no_wheel_until_the_pen_reports_another_value() { + let mut r = Readings::default(); + r.packet(packet(1, 0), AXIS, 100); + assert_eq!(r.wheel_at(100, false), None); + r.packet(packet(1, 300), AXIS, 110); + r.packet(packet(1, 0), AXIS, 120); + assert_eq!(r.wheel_at(120, false), Some(0.0), "a real 0 after another value"); + r.forget(); + r.packet(packet(1, 0), AXIS, 130); + assert_eq!(r.wheel_at(130, false), None, "afresh after the pen came near"); + } + + #[test] + fn the_readings_start_afresh_for_the_other_end_and_out_of_the_context() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_at(100, false), Some(0.3)); + assert_eq!(r.wheel_at(100, true), None, "the other end"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, true), Some(0.3)); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 300) }, AXIS, 120); + assert_eq!(r.wheel_at(120, true), None, "out of the context"); + r.packet(packet(1, 300), AXIS, 130); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(1, 300) }, AXIS, 140); + assert_eq!(r.wheel_at(140, true), None, "the queue overflowed"); + // The eraser end leaves; the tip's first message after it keeps the tip's packet. + r.forget(); + r.packet(packet(1, 300), AXIS, 150); + assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + for c in 0..10 { + r.packet(packet(c, 300), AXIS, 1000 * c); + } + assert_eq!(r.list.len(), MAX_READINGS, "bounded"); + assert_eq!(r.wheel_at(9000, false), Some(0.3)); + } + + #[test] + fn the_context_follows_the_window_the_pen_draws_in() { + let (main, doc) = (0x10, 0x20); + assert_eq!(next_context(None, None, main), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(next_context(Some((main, true)), Some(main), main), (Current::Keep, false), "the same window keeps it"); + assert_eq!(next_context(Some((main, true)), Some(main), doc), (Current::Close, true), "another document window"); + assert_eq!(next_context(Some((doc, true)), Some(doc), main), (Current::Close, true), "and back"); + assert_eq!(next_context(Some((main, false)), Some(main), doc), (Current::Drop, true), "a window that is gone"); + assert_eq!(next_context(Some((main, false)), Some(main), main), (Current::Drop, true), "its handle reused"); + assert_eq!(next_context(None, Some(main), main), (Current::Keep, false), "an open that failed is not tried again"); + assert_eq!(next_context(None, Some(main), doc), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn wintab_messages_name_their_context() { + assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); + assert_eq!(message(WT_CSRCHANGE, 42, 0x5000), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_PROXIMITY, 0x5000, 1), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_CTXCLOSE, 0x5000, 0), Message::Closed { ctx: 0x5000 }); + assert_eq!(message(WT_INFOCHANGE, 0, 0), Message::InfoChange); + // WM_POINTERUPDATE and the context-open message. + assert_eq!(message(0x0245, 0, 0), Message::Other); + assert_eq!(message(WT_DEFBASE + 1, 0, 0), Message::Other); + } +} diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 0b27d24127..0b3eb92416 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -12,8 +12,9 @@ //! each pointer message of a pen before winit handles it. The canvas uses the pressure when a //! frame's events carry no touch force, and the tilt and rotation for each press, drag and release. //! An airbrush pen's finger wheel comes with the tilt and rotation ([`PenPose::wheel`]) where the -//! host reads it: from XInput2 on X11 and from AppKit on macOS. The app does not read it on -//! Windows, whose pointer messages have no field for it, or in the web build. +//! host reads it: from XInput2 on X11, from AppKit on macOS, and on Windows, whose pointer messages +//! have no field for it, from the tablet driver's Wintab interface when the driver has one. The app +//! does not read it in the web build. //! //! The feed also says which end of the pen moved. Turning the pen to its eraser end selects the //! Eraser tool, and turning it back to the tip selects the tool used before diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..2515a3bc92 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4170,9 +4170,10 @@ already walks Image Trace. Short agent entry points: value goes from the value less the variation (a Scatter brush's first value, an Art brush's `width`) at 0 to the value plus the variation (the second value, `width_max`) at 1, and a stroke without a wheel draws the value half way. Brush Options offers Stylus Wheel for a Calligraphic or Scatter brush's Size and an Art brush's Width. The - desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11 and from AppKit (`tangentialPressure`) on macOS; - it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation - code 3. + desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and + on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` + is installed; without it a Windows pen reads no wheel. The web build does not read it. `.ai` brush definitions read + and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..6e53dbc469 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2057,7 +2057,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2065,7 +2065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_pose` and `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` (vectorcraft). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From 29fa62b46ce32c1a360c1075cd9dce95dcbac872 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:12:24 -0800 Subject: [PATCH 08/63] Windows: the Wintab wheel follows the driver's context notices The tablet driver sends WT_CTXCLOSE and WT_INFOCHANGE to the window procedure, and a sent message does not pass winit's message hook, so a context the driver closed kept its handle and the wheel stopped reading. The context's window now gets a window procedure in front of its own that notes both notices. The next Wintab or pen message drops a closed context or closes and reopens it after an information change, forgetting the cached cursor ranges. A notice the reader causes by closing its own context does not drop a later context with the same handle value. A packet that WTPacket cannot read now starts the readings afresh, so a pen message no longer takes a wheel value that may be stale. Only the pen whose message last read the wheel clears the readings when it leaves the window or detection range or its press is canceled; a touch or another pen leaving keeps them. --- apps/vectorcraft/src/windows_stylus.rs | 41 +++- apps/vectorcraft/src/windows_wintab.rs | 267 ++++++++++++++++++++++--- 2 files changed, 267 insertions(+), 41 deletions(-) diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 15fcd4b9e2..1a75122ac9 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -70,6 +70,8 @@ const WM_POINTERLEAVE: u32 = 0x024A; thread_local! { static STROKES: RefCell = RefCell::new(BarrelStrokes::default()); + /// The pointer id of the pen whose message last read the Wintab wheel. + static WHEEL_PEN: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// The pen feed [`msg_hook`] writes, once [`start`] has made it. @@ -106,14 +108,16 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { return false; }; crate::windows_wintab::msg_hook(msg); - if forgets_wheel(msg.message, msg.wParam.0) { + if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) { crate::windows_wintab::forget(); } let read_pen = || { let mut info = POINTER_PEN_INFO::default(); + let id = (msg.wParam.0 & 0xffff) as u32; // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. - unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?; + unsafe { GetPointerPenInfo(id, &mut info) }.ok()?; + WHEEL_PEN.set(Some(id)); let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, eraser); @@ -155,8 +159,12 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32, wheel: Optio /// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message /// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the -/// window. -fn forgets_wheel(message: u32, wparam: usize) -> bool { +/// window, when the pointer is `pen`, the pen whose message last read the wheel. A touch or another +/// pen leaving keeps the readings. +fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + if pen != Some((wparam & 0xffff) as u32) { + return false; + } let flags = wparam >> 16; match message { WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => { @@ -477,15 +485,28 @@ mod tests { fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() { let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7; + let pen = Some(7); for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { - assert!(!forgets_wheel(m, in_range), "{m:#x}"); - assert!(forgets_wheel(m, 7), "out of range: {m:#x}"); - assert!(forgets_wheel(m, canceled), "canceled: {m:#x}"); + assert!(!forgets_wheel(m, in_range, pen), "{m:#x}"); + assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}"); + assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}"); } - assert!(forgets_wheel(WM_POINTERLEAVE, in_range)); + assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen)); // WM_MOUSEMOVE and WT_PACKET. - assert!(!forgets_wheel(0x0200, 0)); - assert!(!forgets_wheel(0x7FF0, 7)); + assert!(!forgets_wheel(0x0200, 0, Some(0))); + assert!(!forgets_wheel(0x7FF0, 7, pen)); + } + + #[test] + fn another_pointer_leaving_keeps_the_wheel() { + // A touch, pointer 9, leaves the window and detection range while pen 7 hovers. + let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9; + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7))); + assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range"); + let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9; + assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled"); + assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel"); + assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself"); } #[test] diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 2c4166821a..9075c5bd19 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -30,11 +30,15 @@ //! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the //! readings start afresh when a cursor //! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns -//! to its other end, a press is canceled, the pen leaves the window or detection range, or the -//! context closes. These rules are VectorCraft's own. +//! to its other end, a press of the pen is canceled, the pen leaves the window or detection +//! range, or the context closes. These rules are VectorCraft's own. //! -//! The context closes when the driver closes it or its information changes (`WT_INFOCHANGE`), and -//! is dropped when its window no longer exists; a later pen message opens it again. +//! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's +//! information changes (`WT_INFOCHANGE`), and dropped when its window no longer exists; a later pen +//! message opens it again. The driver sends those two notices to the window procedure, where a +//! sent message does not pass winit's message hook, so the context's window gets a window procedure +//! in front of its own that notes them ([`Notices`]). A packet that `WTPacket` cannot read also +//! starts the readings afresh ([`Readings::read`]). #![cfg_attr(not(windows), allow(dead_code))] /// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. @@ -279,8 +283,18 @@ impl Readings { } } - /// Start afresh: the pen came near or left, another cursor came, a press was canceled, or the - /// context closed. + /// A `WT_PACKET` read at the message time `time`: the packet with its cursor's wheel range, or + /// `None` when `WTPacket` failed or the packet could not be decoded. Then no reading is known to + /// be current, and the readings start afresh until the next packet. + fn read(&mut self, read: Option<(Packet, Option)>, time: u32) { + match read { + Some((p, axis)) => self.packet(p, axis, time), + None => self.forget(), + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet + /// could not be read, or the context closed. fn forget(&mut self) { self.list.clear(); self.eraser = None; @@ -341,6 +355,67 @@ fn next_context(current: Option<(usize, bool)>, tried: Option, owner: usi (step, tried != Some(owner) || step != Current::Keep) } +/// At most this many contexts' closing notices wait for [`Notices::take`]. +const MAX_NOTICES: usize = 8; + +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`) since they were last +/// taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// call of its own, so they are noted here and acted on at the next Wintab or pen message. +#[derive(Clone, Debug, Default, PartialEq)] +struct Notices { + /// The contexts the driver closed or is about to close. + closed: Vec, + /// The driver's information changed. + info_changed: bool, +} + +/// What the driver's notices do to the open context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Notice { + /// Nothing changed for it. + Keep, + /// The driver closed it: drop the handle without `WTClose`, and open a context again at the + /// next pen message. + Closed, + /// The driver's information changed: close it, forget each cursor's wheel range, and open a + /// context again at the next pen message. + Reopen, +} + +impl Notices { + /// Notes `message` if it is a closing or information-change notice. + fn note(&mut self, message: Message) { + match message { + Message::Closed { ctx } if !self.closed.contains(&ctx) => { + if self.closed.len() >= MAX_NOTICES { + self.closed.remove(0); + } + self.closed.push(ctx); + } + Message::InfoChange => self.info_changed = true, + _ => {} + } + } + + /// The reader closed `ctx` itself: its closing notice is not the driver's, and a context opened + /// later with the same handle value stays open. + fn closed_by_reader(&mut self, ctx: usize) { + self.closed.retain(|&c| c != ctx); + } + + /// Takes the notices: what they do to the open context `current`. + fn take(&mut self, current: Option) -> Notice { + let notices = std::mem::take(self); + if notices.info_changed { + Notice::Reopen + } else if current.is_some_and(|c| notices.closed.contains(&c)) { + Notice::Closed + } else { + Notice::Keep + } + } +} + /// What a message does to the readings and the context. #[derive(Clone, Copy, Debug, PartialEq)] enum Message { @@ -385,15 +460,18 @@ mod win { use std::ffi::c_void; use std::sync::OnceLock; - use windows::Win32::Foundation::HWND; + use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; - use windows::Win32::UI::WindowsAndMessaging::{GA_ROOTOWNER, GetAncestor, IsWindow, MSG}; - use windows::core::{s, w}; + use windows::Win32::UI::WindowsAndMessaging::{ + CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetPropW, GetWindowLongPtrW, IsWindow, MSG, RemovePropW, SetPropW, + SetWindowLongPtrW, WM_NCDESTROY, WNDPROC, + }; + use windows::core::{PCWSTR, s, w}; use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, - MAX_READINGS, Message, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, configure, decode, - device_of, message, next_context, wheel_axis, + MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, + configure, decode, device_of, message, next_context, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -432,6 +510,73 @@ mod win { thread_local! { static STATE: RefCell = RefCell::new(State::default()); + /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends + /// while [`STATE`] is borrowed for a driver call. + static NOTICES: RefCell = RefCell::new(Notices::default()); + } + + /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. + const PREV_PROC: PCWSTR = w!("VectorCraft.Wintab.PrevProc"); + + /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. + fn note(what: Message) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange) { + return; + } + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.note(what); + } + }); + } + + /// The window procedure put in front of the context window's own: the driver sends + /// `WT_CTXCLOSE` and `WT_INFOCHANGE` (), + /// and a sent message reaches the window procedure without passing winit's message hook. It + /// notes them and passes every message on. + unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + note(message(msg, wparam.0, lparam.0)); + // SAFETY: `GetPropW` takes any handle value and a NUL-terminated name. + let prev = unsafe { GetPropW(hwnd, PREV_PROC) }.0; + if msg == WM_NCDESTROY { + // SAFETY: as above; the window is being destroyed. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } + if prev.is_null() { + // SAFETY: the default procedure takes any message of a window of this thread. + return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }; + } + // SAFETY: the property holds the window procedure `subclass` replaced, which stays valid + // while the window exists. + let prev = unsafe { std::mem::transmute::<*mut c_void, WNDPROC>(prev) }; + // SAFETY: `prev` is the window's own procedure, called with the message it was sent. + unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } + } + + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window. The window's + /// property holds the procedure it replaced, and goes with the window. + fn subclass(hwnd: *mut c_void) { + let hwnd = HWND(hwnd); + // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. + if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { + return; + } + // SAFETY: as above. + let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; + if prev == 0 { + return; + } + // SAFETY: the window is this thread's (winit's), and the property's value is a procedure + // address, not memory the system frees. + if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { + return; + } + type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; + // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. + if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { + // SAFETY: as for `SetPropW`. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } } /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. @@ -506,10 +651,34 @@ mod win { if let Some(c) = self.context.take() { // SAFETY: the handle came from `WTOpenW` and has not been closed. unsafe { (api.close)(c.handle) }; + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.closed_by_reader(c.handle as usize); + } + }); } self.readings.forget(); } + /// Acts on the driver's notices since the last look ([`Notices::take`]). + fn take_notices(&mut self, api: Api) { + let current = self.context.as_ref().map(|c| c.handle as usize); + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::Keep, |mut n| n.take(current))); + match notice { + Notice::Keep => {} + Notice::Closed => { + self.context = None; + self.tried = None; + self.readings.forget(); + } + Notice::Reopen => { + self.close(api); + self.tried = None; + self.cursors.clear(); + } + } + } + /// Moves the context to the window that owns `hwnd` ([`next_context`]). fn open_for(&mut self, api: Api, hwnd: *mut c_void) { // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. @@ -535,6 +704,7 @@ mod win { let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; if !handle.is_null() { self.context = Some(Context { handle, hwnd: owner }); + subclass(owner); } } @@ -556,46 +726,35 @@ mod win { } /// winit's message hook for the Wintab messages: reads each packet of the context and starts - /// the readings afresh on a cursor's change or proximity. It never consumes the message. + /// the readings afresh on a cursor's change or proximity. A closing or information-change + /// notice that comes through the queue is noted as [`wnd_proc`] notes a sent one. It never + /// consumes the message. pub fn msg_hook(msg: &MSG) { let what = message(msg.message, msg.wParam.0, msg.lParam.0); if what == Message::Other { return; } let Some(api) = api() else { return }; + note(what); STATE.with(|s| { let Ok(mut s) = s.try_borrow_mut() else { return }; + s.take_notices(api); match what { Message::Packet { serial, ctx } => { let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; let mut buf = PacketBuffer([0; PACKET_BUFFER]); // SAFETY: the handle is the open context's, and `buf` holds more bytes than a // packet of every field. - if unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } == 0 { - return; - } - let Some(p) = decode(&buf.0, PACKET_DATA) else { return }; - let axis = s.axis(api, p.cursor); - s.readings.packet(p, axis, msg.time); + let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor))); + s.readings.read(read, msg.time); } Message::Forget { ctx } => { if s.ours(msg.hwnd.0, ctx).is_some() { s.readings.forget(); } } - Message::Closed { ctx } => { - if s.context.as_ref().is_some_and(|c| c.handle as usize == ctx) { - s.context = None; - s.tried = None; - s.readings.forget(); - } - } - Message::InfoChange => { - s.close(api); - s.tried = None; - s.cursors.clear(); - } - Message::Other => {} + Message::Closed { .. } | Message::InfoChange | Message::Other => {} } }); } @@ -606,6 +765,7 @@ mod win { let api = api()?; STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; + s.take_notices(api); s.open_for(api, hwnd.0); s.readings.wheel_at(time, eraser) }) @@ -802,6 +962,51 @@ mod tests { assert_eq!(next_context(None, Some(main), doc), (Current::Keep, true), "but is for another window"); } + #[test] + fn a_packet_that_cannot_be_read_starts_the_readings_afresh() { + let mut r = Readings::default(); + r.read(Some((packet(1, 750), AXIS)), 100); + assert_eq!(r.wheel_at(100, false), Some(0.75)); + r.read(None, 110); + assert_eq!(r.wheel_at(110, false), None, "the last reading is not kept after a failed read"); + r.read(Some((packet(1, 500), AXIS)), 120); + assert_eq!(r.wheel_at(120, false), Some(0.5), "the next packet reads again"); + } + + #[test] + fn the_drivers_notices_drop_or_reopen_the_context() { + let (ours, other) = (0x5000, 0x6000); + let mut n = Notices::default(); + assert_eq!(n.take(Some(ours)), Notice::Keep, "no notice"); + n.note(Message::Closed { ctx: other }); + assert_eq!(n.take(Some(ours)), Notice::Keep, "another context closed"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice::Closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), Notice::Keep, "taken once"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(None), Notice::Keep, "nothing open"); + assert_eq!(n, Notices::default(), "and the notice is gone"); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice::Reopen); + n.note(Message::InfoChange); + assert_eq!(n.take(None), Notice::Reopen, "cursor ranges are read again even with nothing open"); + // The reader closes its context, and the driver's notice of that arrives during the call; + // a context opened next under the same handle value stays open. + n.note(Message::Closed { ctx: ours }); + n.closed_by_reader(ours); + assert_eq!(n.take(Some(ours)), Notice::Keep); + for ctx in 0..20 { + n.note(Message::Closed { ctx }); + n.note(Message::Closed { ctx }); + } + assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); + assert_eq!(n.take(Some(19)), Notice::Closed, "the latest kept"); + n.note(Message::Packet { serial: 1, ctx: ours }); + n.note(Message::Forget { ctx: ours }); + n.note(Message::Other); + assert_eq!(n, Notices::default(), "other messages are not notices"); + } + #[test] fn wintab_messages_name_their_context() { assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); From 7bf46c2101599b6ba5e4b93e3b7ca1e63dff60a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:54:18 -0800 Subject: [PATCH 09/63] Windows: the Wintab wheel drops a context the driver closed and clears readings on a queue overflow - A close notice and an information change in one batch now both count: the handle the driver closed is dropped without WTClose, and each cursor's wheel range is read again. - The window procedure that notes the driver's notices is put in front of the window's own before a context is opened. When it cannot be, no context is opened for that window. - A packet that reports the context's queue overflowed (TPS_QUEUE_ERR) starts every reading afresh, not only its own cursor's. - The first pen whose pointer message comes within 200 ms of an airbrush packet takes the readings. Another pen's messages read no wheel until they start afresh, and the taking pen's leaving starts them afresh. --- apps/vectorcraft/src/windows_stylus.rs | 10 +- apps/vectorcraft/src/windows_wintab.rs | 277 ++++++++++++++++++------- 2 files changed, 208 insertions(+), 79 deletions(-) diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 1a75122ac9..a5d9b86271 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -70,7 +70,9 @@ const WM_POINTERLEAVE: u32 = 0x024A; thread_local! { static STROKES: RefCell = RefCell::new(BarrelStrokes::default()); - /// The pointer id of the pen whose message last read the Wintab wheel. + /// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that + /// took them, or the pen whose message last asked for the wheel when none has + /// ([`crate::windows_wintab::wheel_pen`]). static WHEEL_PEN: std::cell::Cell> = const { std::cell::Cell::new(None) }; } @@ -117,10 +119,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { // SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a // pointer that is not a pen. unsafe { GetPointerPenInfo(id, &mut info) }.ok()?; - WHEEL_PEN.set(Some(id)); let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0; let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0; - let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, eraser); + let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser); + WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id))); let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation, wheel); Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose)) }; @@ -159,7 +161,7 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32, wheel: Optio /// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message /// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the -/// window, when the pointer is `pen`, the pen whose message last read the wheel. A touch or another +/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another /// pen leaving keeps the readings. fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { if pen != Some((wparam & 0xffff) as u32) { diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 9075c5bd19..ba4c784049 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -23,10 +23,12 @@ //! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, //! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 //! ([`Axis::wheel`]); a value outside it reads as none. -//! - A pointer message of a pen takes the wheel of the airbrush read since the readings started -//! afresh, however long ago its last packet came, since a pen held still sends none. When -//! several cursors were read, it takes the one whose latest packet came within [`MAX_SKEW_MS`] of -//! the message, and none when two are that recent or none is ([`Readings::wheel_at`]). As on +//! - A pointer message of a pen takes the wheel of the airbrush whose latest packet came within +//! [`MAX_SKEW_MS`] of the message, and none when two are that recent or none is +//! ([`Readings::wheel_for`]). The first pen to read a wheel that way after the readings start +//! afresh takes the readings: other pens read none until they start afresh, and that pen keeps +//! reading the one airbrush read, however long ago its last packet came, since a pen held still +//! sends none. As on //! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the //! readings start afresh when a cursor //! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns @@ -34,11 +36,14 @@ //! range, or the context closes. These rules are VectorCraft's own. //! //! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's -//! information changes (`WT_INFOCHANGE`), and dropped when its window no longer exists; a later pen -//! message opens it again. The driver sends those two notices to the window procedure, where a -//! sent message does not pass winit's message hook, so the context's window gets a window procedure -//! in front of its own that notes them ([`Notices`]). A packet that `WTPacket` cannot read also -//! starts the readings afresh ([`Readings::read`]). +//! information changes (`WT_INFOCHANGE`) unless the driver closed it too, and dropped when its +//! window no longer exists; a later pen message opens it again. The driver sends those two notices +//! to the window procedure, where a sent message does not pass winit's message hook, so the +//! context's window gets a window procedure in front of its own that notes them ([`Notices`]). +//! When that procedure cannot be put in front, no context is opened for the window +//! ([`hooked_open`]). A packet that `WTPacket` cannot read starts the readings afresh +//! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed +//! (`TPS_QUEUE_ERR`, [`Readings::packet`]). #![cfg_attr(not(windows), allow(dead_code))] /// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. @@ -257,14 +262,22 @@ struct Readings { list: Vec, /// The end of the pen the last pointer message read, `Some(true)` for the eraser end. eraser: Option, + /// The pointer id of the pen whose message first read the wheel since the readings started + /// afresh; another pen's messages read none. + pen: Option, } impl Readings { /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of - /// a cursor out of the context, or after the queue overflowed, drops that cursor's reading. + /// a cursor out of the context drops that cursor's reading. A packet sent after the context's + /// queue overflowed starts every reading afresh, until the next packet. fn packet(&mut self, p: Packet, axis: Option, time: u32) { + if p.status & TPS_QUEUE_ERR != 0 { + self.forget(); + return; + } let at = self.list.iter().position(|r| r.cursor == p.cursor); - if p.status & (TPS_PROXIMITY | TPS_QUEUE_ERR) != 0 { + if p.status & TPS_PROXIMITY != 0 { if let Some(i) = at { self.list.remove(i); } @@ -294,25 +307,36 @@ impl Readings { } /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet - /// could not be read, or the context closed. + /// could not be read, the context's queue overflowed, or the context closed. fn forget(&mut self) { self.list.clear(); self.eraser = None; + self.pen = None; } - /// The wheel for a pointer message of a pen at the message time `time` with its `eraser` end, - /// if the cursor it comes from is an airbrush: the one cursor read since the readings started - /// afresh, however long ago its last packet came (a pen held still sends none), or, when - /// several were, the one whose latest packet is within [`MAX_SKEW_MS`] of the message. `None` - /// when no cursor, or more than one, is that recent, or the cursor has read only 0 since the - /// readings started afresh. A turn to the other end starts them afresh first. - fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took + /// the readings, or `pen` when none has. + fn owner_or(&self, pen: u32) -> u32 { + self.pen.unwrap_or(pen) + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time + /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose + /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the + /// readings, the one cursor read since they started afresh, however long ago its last packet + /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, + /// or the cursor has read only 0 since the readings started afresh, or another pen's message + /// read a wheel first since then. A turn to the other end starts them afresh first. + fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { + if self.pen.is_some_and(|p| p != pen) { + return None; + } if self.eraser.is_some_and(|e| e != eraser) { self.forget(); } self.eraser = Some(eraser); let r = match self.list.as_slice() { - [one] => one, + [one] if self.pen == Some(pen) => one, list => { let mut near_time = list.iter().filter(|r| near(time, r.time)); let r = near_time.next()?; @@ -325,7 +349,9 @@ impl Readings { if !r.moved { return None; } - r.axis?.wheel(r.raw) + let wheel = r.axis?.wheel(r.raw)?; + self.pen = Some(pen); + Some(wheel) } } @@ -369,17 +395,15 @@ struct Notices { info_changed: bool, } -/// What the driver's notices do to the open context. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Notice { - /// Nothing changed for it. - Keep, +/// What the driver's notices do to the open context. Both can come in one batch. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Notice { /// The driver closed it: drop the handle without `WTClose`, and open a context again at the /// next pen message. - Closed, - /// The driver's information changed: close it, forget each cursor's wheel range, and open a - /// context again at the next pen message. - Reopen, + closed: bool, + /// The driver's information changed: close it if it is still open, forget each cursor's wheel + /// range, and open a context again at the next pen message. + info_changed: bool, } impl Notices { @@ -406,16 +430,17 @@ impl Notices { /// Takes the notices: what they do to the open context `current`. fn take(&mut self, current: Option) -> Notice { let notices = std::mem::take(self); - if notices.info_changed { - Notice::Reopen - } else if current.is_some_and(|c| notices.closed.contains(&c)) { - Notice::Closed - } else { - Notice::Keep - } + Notice { closed: current.is_some_and(|c| notices.closed.contains(&c)), info_changed: notices.info_changed } } } +/// Opens a context with `open` only when `hook` put the window procedure that notes the driver's +/// notices in front of the window's own; otherwise opens none, and the window is not tried again +/// until another window is ([`next_context`]). +fn hooked_open(hook: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() { open() } else { None } +} + /// What a message does to the readings and the context. #[derive(Clone, Copy, Debug, PartialEq)] enum Message { @@ -451,7 +476,7 @@ fn message(message: u32, wparam: usize, lparam: isize) -> Message { } #[cfg(windows)] -pub use win::{forget, msg_hook, pen_wheel}; +pub use win::{forget, msg_hook, pen_wheel, wheel_pen}; #[cfg(windows)] #[allow(unsafe_code)] @@ -471,7 +496,7 @@ mod win { use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, - configure, decode, device_of, message, next_context, wheel_axis, + configure, decode, device_of, hooked_open, message, next_context, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -553,30 +578,33 @@ mod win { unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } } - /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window. The window's - /// property holds the procedure it replaced, and goes with the window. - fn subclass(hwnd: *mut c_void) { + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns + /// whether it is there. The window's property holds the procedure it replaced, and goes with the + /// window. + fn subclass(hwnd: *mut c_void) -> bool { let hwnd = HWND(hwnd); // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { - return; + return true; } // SAFETY: as above. let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; if prev == 0 { - return; + return false; } // SAFETY: the window is this thread's (winit's), and the property's value is a procedure // address, not memory the system frees. if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { - return; + return false; } type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { // SAFETY: as for `SetPropW`. let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + return false; } + true } /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. @@ -663,19 +691,16 @@ mod win { /// Acts on the driver's notices since the last look ([`Notices::take`]). fn take_notices(&mut self, api: Api) { let current = self.context.as_ref().map(|c| c.handle as usize); - let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::Keep, |mut n| n.take(current))); - match notice { - Notice::Keep => {} - Notice::Closed => { - self.context = None; - self.tried = None; - self.readings.forget(); - } - Notice::Reopen => { - self.close(api); - self.tried = None; - self.cursors.clear(); - } + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::default(), |mut n| n.take(current))); + if notice.closed { + self.context = None; + self.tried = None; + self.readings.forget(); + } + if notice.info_changed { + self.close(api); + self.tried = None; + self.cursors.clear(); } } @@ -700,11 +725,17 @@ mod win { self.tried = Some(owner); let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; configure(&mut words); - // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for the call. - let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; - if !handle.is_null() { + let handle = hooked_open( + || subclass(owner), + || { + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for + // the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + (!handle.is_null()).then_some(handle) + }, + ); + if let Some(handle) = handle { self.context = Some(Context { handle, hwnd: owner }); - subclass(owner); } } @@ -759,18 +790,25 @@ mod win { }); } - /// The wheel for a pointer message of a pen to `hwnd` at the message time `time`, with its - /// `eraser` end ([`Readings::wheel_at`]), opening the context first when none is open. - pub fn pen_wheel(hwnd: HWND, time: u32, eraser: bool) -> Option { + /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message + /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when + /// none is open. + pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { let api = api()?; STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; s.take_notices(api); s.open_for(api, hwnd.0); - s.readings.wheel_at(time, eraser) + s.readings.wheel_for(time, pen, eraser) }) } + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer + /// id `pen` ([`Readings::owner_or`]). + pub fn wheel_pen(pen: u32) -> u32 { + STATE.with(|s| s.try_borrow().map_or(pen, |s| s.readings.owner_or(pen))) + } + /// Start the readings afresh: the pen left the window or detection range, or a press was /// canceled. pub fn forget() { @@ -786,6 +824,15 @@ mod win { mod tests { use super::*; + /// The pointer id of the pen in the tests that use one pen. + const PEN: u32 = 1; + + impl Readings { + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + self.wheel_for(time, PEN, eraser) + } + } + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler /// when it has none, and the wider fields hold filler bytes. fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { @@ -976,37 +1023,117 @@ mod tests { #[test] fn the_drivers_notices_drop_or_reopen_the_context() { let (ours, other) = (0x5000, 0x6000); + let keep = Notice::default(); + let closed = Notice { closed: true, info_changed: false }; + let reopen = Notice { closed: false, info_changed: true }; let mut n = Notices::default(); - assert_eq!(n.take(Some(ours)), Notice::Keep, "no notice"); + assert_eq!(n.take(Some(ours)), keep, "no notice"); n.note(Message::Closed { ctx: other }); - assert_eq!(n.take(Some(ours)), Notice::Keep, "another context closed"); + assert_eq!(n.take(Some(ours)), keep, "another context closed"); n.note(Message::Closed { ctx: ours }); - assert_eq!(n.take(Some(ours)), Notice::Closed, "the driver closed it"); - assert_eq!(n.take(Some(ours)), Notice::Keep, "taken once"); + assert_eq!(n.take(Some(ours)), closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), keep, "taken once"); n.note(Message::Closed { ctx: ours }); - assert_eq!(n.take(None), Notice::Keep, "nothing open"); + assert_eq!(n.take(None), keep, "nothing open"); assert_eq!(n, Notices::default(), "and the notice is gone"); n.note(Message::InfoChange); - assert_eq!(n.take(Some(ours)), Notice::Reopen); + assert_eq!(n.take(Some(ours)), reopen); n.note(Message::InfoChange); - assert_eq!(n.take(None), Notice::Reopen, "cursor ranges are read again even with nothing open"); + assert_eq!(n.take(None), reopen, "cursor ranges are read again even with nothing open"); // The reader closes its context, and the driver's notice of that arrives during the call; // a context opened next under the same handle value stays open. n.note(Message::Closed { ctx: ours }); n.closed_by_reader(ours); - assert_eq!(n.take(Some(ours)), Notice::Keep); + assert_eq!(n.take(Some(ours)), keep); for ctx in 0..20 { n.note(Message::Closed { ctx }); n.note(Message::Closed { ctx }); } assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); - assert_eq!(n.take(Some(19)), Notice::Closed, "the latest kept"); + assert_eq!(n.take(Some(19)), closed, "the latest kept"); n.note(Message::Packet { serial: 1, ctx: ours }); n.note(Message::Forget { ctx: ours }); n.note(Message::Other); assert_eq!(n, Notices::default(), "other messages are not notices"); } + #[test] + fn a_close_and_an_information_change_in_one_batch_both_count() { + let ours = 0x5000; + let both = Notice { closed: true, info_changed: true }; + let mut n = Notices::default(); + n.note(Message::Closed { ctx: ours }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), both, "the closed handle is dropped, not closed again"); + n.note(Message::InfoChange); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), both, "in either order"); + n.note(Message::Closed { ctx: 0x6000 }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice { closed: false, info_changed: true }, "another context's close"); + } + + #[test] + fn a_context_opens_only_behind_the_window_procedure() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, open), Some(7)); + assert_eq!(opens.get(), 1); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| false, open), None, "no context without the procedure"); + assert_eq!(opens.get(), 1, "and the driver is not asked for one"); + assert_eq!(hooked_open(|| true, || None::), None, "an open that fails"); + } + + #[test] + fn the_readings_belong_to_the_pen_that_took_them_first() { + let other = 2; + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_for(5000, other, false), None, "a pen message long after the packet does not take them"); + assert_eq!(r.wheel_for(150, other, false), Some(0.3), "one near the packet does"); + assert_eq!(r.wheel_at(5010, false), None, "another pen with no packets of its own"); + assert_eq!(r.wheel_for(5020, other, false), Some(0.3), "and the pen that took them still reads them"); + r.forget(); + assert_eq!(r.wheel_at(5030, false), None, "no packet since the readings started afresh"); + r.packet(packet(1, 400), AXIS, 5040); + assert_eq!(r.wheel_at(5040, false), Some(0.4), "then another pen takes them"); + } + + #[test] + fn a_pen_takes_the_readings_only_when_it_reads_a_wheel() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, false), None, "no packet yet"); + assert_eq!(r.owner_or(PEN), PEN, "and no pen took the readings"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, false), Some(0.3), "the pen with the reading"); + assert_eq!(r.owner_or(other), PEN, "the pen whose leaving starts the readings afresh"); + r.forget(); + assert_eq!(r.owner_or(other), other); + } + + #[test] + fn a_queue_overflow_starts_every_reading_afresh() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + r.packet(packet(2, 500), None, 110); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(2, 500) }, None, 120); + assert!(r.list.is_empty(), "the queue is the context's, not the cursor's"); + assert_eq!(r.wheel_at(5000, false), None, "the airbrush's old wheel is not taken"); + r.packet(packet(1, 400), AXIS, 5000); + assert_eq!(r.wheel_at(5000, false), Some(0.4), "the next packet reads again"); + r.packet(packet(2, 500), None, 5010); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(2, 500) }, None, 5020); + assert_eq!(r.list.len(), 1, "a cursor that leaves drops only its own reading"); + } + #[test] fn wintab_messages_name_their_context() { assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); From 1157d8ab51e7b2be2d0c262f2dcd948b3ba902cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:36:33 -0800 Subject: [PATCH 10/63] Accessibility: the isolation bar's back arrow, crumbs and pattern buttons have screen-reader names The isolation bar drew its back arrow, the crumbs of the levels above and the pattern editing buttons as bare Tab stops with no name or role. Each is now a button. The back arrow is named for what it does: Back One Level, Exit Isolation Mode, Exit Symbol Editing Mode, or Done while a pattern is edited. A crumb is named with the name it shows, and Save a Copy, Done and Cancel with their labels, all in the UI's language. The strings already have rows in every catalog. --- crates/ui-egui/src/chrome/tabs.rs | 28 +++++++++-- crates/ui-egui/src/chrome/tests.rs | 81 ++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 107 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index b92d1e5d04..0410c2f71d 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -432,8 +432,30 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { // the levels above and the pattern buttons leaves isolation mode. let background = ui.interact(bar, ui.scope_id().with("iso-bar"), Sense::CLICK | Sense::DRAG); ui.painter().rect_filled(bar, 0.0, t.panel); + // The back arrow goes up one level: the isolated object's parent group, or `object.exitIsolation`, + // which goes from an isolated sublayer to its parent layer, from a group in a symbol's art to + // the symbol's layer, and otherwise leaves isolation mode. While a pattern is edited it is Done. + // Screen readers call it by what it does. + let parent_group = ancestry.iter().rev().nth(1).copied().filter(|p| st.doc.node(*p).is_some_and(|n| !n.is_layer())); + let symbol_layer = st.doc.symbol_edit.as_ref().map(|e| e.layer); + let up_one = parent_group.is_some() + || symbol_layer.is_some_and(|l| l != iso && ancestry.contains(&l)) + || (st.doc.mask_edit.is_none() + && symbol_layer.is_none() + && st.doc.node(iso).is_some_and(|n| n.is_layer()) + && st.doc.parent_of(iso).is_some_and(|p| st.doc.is_editable(p))); + let back_name = if pattern_edit.is_some() { + tl!("Done") + } else if up_one { + tl!("Back One Level") + } else if symbol_layer == Some(iso) { + tl!("Exit Symbol Editing Mode") + } else { + tl!("Exit Isolation Mode") + }; let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0)); let bresp = ui.interact(back, ui.scope_id().with("iso-back"), Sense::click()); + bresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), back_name)); icons::paint(ui, "chevron-left", back, if bresp.hovered() { t.text } else { t.icon }); let mut x = bar.left() + 30.0; @@ -449,6 +471,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if !is_leaf { let crumb_rect = egui::Rect::from_min_max(egui::pos2(x - 3.0, bar.top() + 3.0), egui::pos2(x + w + 3.0, bar.bottom() - 3.0)); let resp = ui.interact(crumb_rect, ui.scope_id().with(("iso-crumb", i)), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &crumb.name)); if resp.hovered() { ui.painter().rect_filled(crumb_rect, 3.0, t.hover); } @@ -480,6 +503,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { let w = 12.0 + 7.0 * label.len() as f32; let r = egui::Rect::from_min_max(egui::pos2(x - w, bar.top() + 3.0), egui::pos2(x, bar.bottom() - 3.0)); let resp = ui.interact(r, ui.scope_id().with(("pat-bar", cmd)), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); ui.painter().rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.panel }); ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.button_border), egui::StrokeKind::Inside); ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), t.text); @@ -492,9 +516,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if bresp.clicked() { pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done")); if pattern_cmd.is_none() { - // Up one level: the isolated object's parent group, or `object.exitIsolation`, which - // goes from an isolated sublayer to its parent layer and otherwise leaves isolation mode. - nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { + nav_cmd = Some(match parent_group { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), }); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..00aabb241a 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2264,6 +2264,87 @@ fn tab_skips_the_isolation_bars_background() { assert!(!stops.contains(&bar), "{stops:?}"); } +/// Screen readers call the isolation bar's back arrow by what it does, each crumb of the levels +/// above by the name it shows, and the pattern buttons by their labels, in the UI's language. The +/// current object's name is not a button. +#[test] +fn the_isolation_bars_controls_have_screen_reader_names() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let buttons = |app: &mut crate::VectorcraftApp| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::isolation_bar(app, ui, screen)); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let mut names: Vec = + nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + names.sort(); + names + }; + let name = |app: &crate::VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().display_name(); + let st = app.session.active().unwrap(); + let (layer, group) = (st.doc.layer_of(NodeId(a)).unwrap(), st.doc.parent_of(NodeId(a)).unwrap()); + let (layer_name, group_name) = (name(&app, layer), name(&app, group)); + + // A path in a group: back goes to the group. + app.run("object.isolate", json!({"id": a})).unwrap(); + let mut want = vec!["Back One Level".to_string(), layer_name.clone(), group_name.clone()]; + want.sort(); + assert_eq!(buttons(&mut app), want, "the current object's name is not a button"); + + // The group itself: back leaves isolation mode. + app.run("object.isolate", json!({"id": group.0})).unwrap(); + let mut want = vec!["Exit Isolation Mode".to_string(), layer_name.clone()]; + want.sort(); + assert_eq!(buttons(&mut app), want); + + // An isolated sublayer: back goes to its parent layer, and from the top-level layer it leaves. + let sub = app.run("layer.newSublayer", json!({"parent": layer.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap(); + app.run("object.isolate", json!({"id": sub})).unwrap(); + let mut want = vec!["Back One Level".to_string(), layer_name.clone()]; + want.sort(); + assert_eq!(buttons(&mut app), want); + app.run("object.isolate", json!({"id": layer.0})).unwrap(); + assert_eq!(buttons(&mut app), vec!["Exit Isolation Mode".to_string()]); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + + // In German. + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = buttons(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(german.contains(&"Isolationsmodus beenden".to_string()), "{german:?}"); + app.run("object.exitIsolation", json!({"all": true})).unwrap(); + + // Pattern editing: back is Done, beside Save a Copy, Done and Cancel. + let c = rect(&mut app, 200.0); + app.run("select.set", json!({"ids": [c]})).unwrap(); + app.run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap(); + let names = buttons(&mut app); + for label in ["Save a Copy", "Cancel"] { + assert!(names.contains(&label.to_string()), "{label} in {names:?}"); + } + assert_eq!(names.iter().filter(|n| *n == "Done").count(), 2, "{names:?}"); + app.run("object.pattern.cancel", json!({})).unwrap(); + + // Symbol editing mode: back leaves it. + let d = rect(&mut app, 300.0); + app.run("select.set", json!({"ids": [d]})).unwrap(); + app.run("symbol.new", json!({"name": "Box"})).unwrap(); + app.run("symbol.edit", json!({"name": "Box"})).unwrap(); + let names = buttons(&mut app); + assert!(names.contains(&"Exit Symbol Editing Mode".to_string()), "{names:?}"); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..1ca8a95373 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1321,6 +1321,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`). + - Screen readers read the isolation bar's back arrow as a button named for what it does (Back One Level, Exit Isolation Mode, Exit Symbol Editing Mode, or Done while a pattern is edited), each crumb of the levels above as a button with the name it shows, and Save a Copy, Done and Cancel by their labels, in the UI's language (`the_isolation_bars_controls_have_screen_reader_names`). - In isolation mode the Layers panel lists only the art of the isolated layer, sublayer or group, and lists the other layers and groups again when isolation mode ends ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=212)). As VectorCraft's own rules, the isolated layer, sublayer, group or object is the top row and opens on entering, the panel scrolls back to its row on leaving, search and filter look only inside it, nothing is dropped beside its row or into the empty space under the rows, Rename and Locate Object open no rows outside it, and rows highlighted outside it are no longer highlighted. With no row highlighted, Delete Selection and the trash do not delete a current layer outside it. New Layer, New Sublayer and Duplicate (in the panel menu and a row's context menu) are off, and OK in New Layer Options is an error, while the layer or copy they make would be outside it (`isolation_lists_only_the_isolated_art_and_exit_lists_every_layer_again`, `isolation_opens_the_isolated_row_and_keeps_drops_inside_it`, `isolation_drops_highlights_outside_the_isolated_art`, `isolation_keeps_rename_and_locate_to_the_rows_listed`, `isolation_keeps_delete_to_the_rows_listed`, `isolation_keeps_new_layers_to_the_rows_listed`, `new_layer_options_ok_checks_isolation_again`). - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). From 0c20ddaa02410484feb809633c5c80329d58b98c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:55:53 -0800 Subject: [PATCH 11/63] Windows: the Wintab wheel retries a failed open, sees the pen leave and closes while another app is active - An open that leaves no context (a failed `WTInfoW` or `WTOpenW`, or a window procedure that could not be put in front) is tried again for the same window by a pen message 2 s or more later (`RETRY_MS`), instead of only after the pen moves to another window. An open context is kept as before. - Windows sends `WM_POINTERLEAVE` to the window procedure, so winit's message hook does not see it. A `WH_CALLWNDPROC` hook on the UI thread now hands a sent `WM_POINTERENTER` or `WM_POINTERLEAVE` to the stylus code, and the wheel pen's leaving starts the readings afresh. A leave that comes while the readings are in use takes effect at the next Wintab or pen message. Until the hook is installed no context opens. - The context closes when another app becomes the active one (`WM_ACTIVATEAPP`, seen through the same hook), and no pen message opens one while the foreground window belongs to another thread, so the context does not stay in front of another app's context in the driver's overlap order. --- apps/vectorcraft/src/windows_stylus.rs | 36 +++ apps/vectorcraft/src/windows_wintab.rs | 309 +++++++++++++++++++++---- 2 files changed, 299 insertions(+), 46 deletions(-) diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index a5d9b86271..bb05debce3 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -177,6 +177,25 @@ fn forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { } } +/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook +/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and +/// `WM_POINTERLEAVE` are sent +/// (); the posted pointer +/// messages are left to [`msg_hook`]. +fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { + matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen) +} + +/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on +/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as +/// [`msg_hook`] does for the messages it sees. +#[cfg(windows)] +pub fn sent_message(message: u32, wparam: usize) { + if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) { + crate::windows_wintab::forget(); + } +} + /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, /// not from a pen or a touch. fn is_mouse(extra_info: u32) -> bool { @@ -511,6 +530,23 @@ mod tests { assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself"); } + #[test] + fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() { + let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7; + let pen = Some(7); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window"); + assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves"); + assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel"); + assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window"); + // Posted messages, which the message hook already sees. + for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] { + assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}"); + } + // WT_CTXCLOSE. + assert!(!sent_forgets_wheel(0x7FF2, 7, pen)); + } + #[test] fn a_pens_pressure_is_the_one_winit_gives_its_touch() { assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5); diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index ba4c784049..81a3f8efb2 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -41,7 +41,12 @@ //! to the window procedure, where a sent message does not pass winit's message hook, so the //! context's window gets a window procedure in front of its own that notes them ([`Notices`]). //! When that procedure cannot be put in front, no context is opened for the window -//! ([`hooked_open`]). A packet that `WTPacket` cannot read starts the readings afresh +//! ([`hooked_open`]). An open that leaves no context is tried again for the same window by a pen +//! message [`RETRY_MS`] or more later ([`next_context`]). A hook on the messages Windows sends to +//! the thread's windows passes a pen's `WM_POINTERLEAVE` to [`crate::windows_stylus`], and closes +//! the context when another app becomes the active one (`WM_ACTIVATEAPP`). No pen message opens a +//! context while this app is not active, so the context does not sit in front of another app's in +//! the driver's overlap order. A packet that `WTPacket` cannot read starts the readings afresh //! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed //! (`TPS_QUEUE_ERR`, [`Readings::packet`]). #![cfg_attr(not(windows), allow(dead_code))] @@ -366,26 +371,43 @@ enum Current { Close, } -/// The context step for a pen message to a window owned by `owner`: what happens to the open -/// context, whose window is `current` with whether that window still exists, and whether a context -/// is opened for `owner`. The context follows the window the pen draws in. An open is tried once -/// for a window until another window is tried or the driver closes or changes the context -/// (`tried`). -fn next_context(current: Option<(usize, bool)>, tried: Option, owner: usize) -> (Current, bool) { +/// After an open that left no context, the same window is tried again by the first pen message at +/// least this many milliseconds of the message clock later. +const RETRY_MS: u32 = 2000; + +/// The context step for a pen message to a window owned by `owner` at the message time `time`: +/// what happens to the open context, whose window is `current` with whether that window still +/// exists, and whether a context is opened for `owner`. The context follows the window the pen +/// draws in. While no context is open, the window and time of the last open tried (`tried`) keep +/// pen messages to that window from trying again until [`RETRY_MS`] have passed; another window, +/// or the driver closing or changing the context, tries at once. +/// A pen message to a window of an app that is not the active one (`active` false) opens none, so +/// the context never sits in front of the active app's own in the driver's overlap order. +fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32, active: bool) -> (Current, bool) { let step = match current { Some((_, false)) => Current::Drop, Some((w, true)) if w == owner => return (Current::Keep, false), Some(_) => Current::Close, None => Current::Keep, }; - (step, tried != Some(owner) || step != Current::Keep) + let due = match tried { + Some((w, at)) if w == owner => retry_due(at, time), + _ => true, + }; + (step, active && (due || step != Current::Keep)) +} + +/// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or +/// more later, on the message clock, which wraps. +fn retry_due(at: u32, time: u32) -> bool { + time.wrapping_sub(at) >= RETRY_MS } /// At most this many contexts' closing notices wait for [`Notices::take`]. const MAX_NOTICES: usize = 8; -/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`) since they were last -/// taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`), and another app becoming +/// the active one (`WM_ACTIVATEAPP`), since they were last taken. The driver sends them to the window procedure, at times while the reader is in a driver /// call of its own, so they are noted here and acted on at the next Wintab or pen message. #[derive(Clone, Debug, Default, PartialEq)] struct Notices { @@ -393,6 +415,10 @@ struct Notices { closed: Vec, /// The driver's information changed. info_changed: bool, + /// The readings were to start afresh while they were in use ([`Notices::forget_later`]). + forget: bool, + /// Another app became the active one. + deactivated: bool, } /// What the driver's notices do to the open context. Both can come in one batch. @@ -404,10 +430,15 @@ struct Notice { /// The driver's information changed: close it if it is still open, forget each cursor's wheel /// range, and open a context again at the next pen message. info_changed: bool, + /// Start the readings afresh. + forget: bool, + /// Another app became the active one: close the context, and open one again at the next pen + /// message once this app is active again. + deactivated: bool, } impl Notices { - /// Notes `message` if it is a closing or information-change notice. + /// Notes `message` if it is a closing, information-change or deactivation notice. fn note(&mut self, message: Message) { match message { Message::Closed { ctx } if !self.closed.contains(&ctx) => { @@ -417,6 +448,7 @@ impl Notices { self.closed.push(ctx); } Message::InfoChange => self.info_changed = true, + Message::Deactivated => self.deactivated = true, _ => {} } } @@ -427,16 +459,27 @@ impl Notices { self.closed.retain(|&c| c != ctx); } + /// The readings are to start afresh, at a time they are in use, for example when the pen leaves + /// the window during a driver call: the next [`Notices::take`] says so. + fn forget_later(&mut self) { + self.forget = true; + } + /// Takes the notices: what they do to the open context `current`. fn take(&mut self, current: Option) -> Notice { let notices = std::mem::take(self); - Notice { closed: current.is_some_and(|c| notices.closed.contains(&c)), info_changed: notices.info_changed } + Notice { + closed: current.is_some_and(|c| notices.closed.contains(&c)), + info_changed: notices.info_changed, + forget: notices.forget, + deactivated: notices.deactivated, + } } } /// Opens a context with `open` only when `hook` put the window procedure that notes the driver's -/// notices in front of the window's own; otherwise opens none, and the window is not tried again -/// until another window is ([`next_context`]). +/// notices in front of the window's own; otherwise opens none, and the window is tried again as +/// [`next_context`] says. fn hooked_open(hook: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { if hook() { open() } else { None } } @@ -459,13 +502,21 @@ enum Message { }, /// The driver's information changed: the context closes and opens again. InfoChange, + /// Another app became the active one: the context closes. + Deactivated, Other, } +/// `WM_ACTIVATEAPP` (`winuser.h`): sent to the app's top-level windows when another app's window +/// is activated (`wParam` false) or one of the app's own is (true) +/// (). +const WM_ACTIVATEAPP: u32 = 0x001C; + /// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` /// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. fn message(message: u32, wparam: usize, lparam: isize) -> Message { match message { + WM_ACTIVATEAPP if wparam == 0 => Message::Deactivated, WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, WT_PROXIMITY => Message::Forget { ctx: wparam }, @@ -487,16 +538,18 @@ mod win { use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::System::Threading::GetCurrentThreadId; use windows::Win32::UI::WindowsAndMessaging::{ - CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetPropW, GetWindowLongPtrW, IsWindow, MSG, RemovePropW, SetPropW, - SetWindowLongPtrW, WM_NCDESTROY, WNDPROC, + CWPSTRUCT, CallNextHookEx, CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetForegroundWindow, GetPropW, + GetWindowLongPtrW, GetWindowThreadProcessId, IsWindow, MSG, RemovePropW, SetPropW, SetWindowLongPtrW, SetWindowsHookExW, WH_CALLWNDPROC, + WM_NCDESTROY, WNDPROC, }; use windows::core::{PCWSTR, s, w}; use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, - configure, decode, device_of, hooked_open, message, next_context, wheel_axis, + configure, decode, device_of, hooked_open, message, next_context, retry_due, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -526,8 +579,9 @@ mod win { #[derive(Default)] struct State { context: Option, - /// The window an open was last tried for ([`next_context`]). - tried: Option<*mut c_void>, + /// The window an open was last tried for, and the message time it was tried at + /// ([`next_context`]). + tried: Option<(*mut c_void, u32)>, /// Each cursor's wheel range, as the driver reported it. cursors: Vec<(u32, Option)>, readings: Readings, @@ -545,7 +599,7 @@ mod win { /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. fn note(what: Message) { - if !matches!(what, Message::Closed { .. } | Message::InfoChange) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange | Message::Deactivated) { return; } NOTICES.with(|n| { @@ -578,6 +632,79 @@ mod win { unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } } + /// Another app became the active one: closes the context now, unless the reader is in a call of + /// its own, when the noted [`Message::Deactivated`] closes it at the next Wintab or pen message. + /// No pen messages come while another app is active, so waiting for one would leave the context + /// in front of that app's own. + fn deactivate() { + let Some(api) = api() else { return }; + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.take_notices(api); + } + }); + } + + /// Whether this app is the active one: the foreground window belongs to this thread, which + /// runs every window of the app. + fn is_active() -> bool { + // SAFETY: `GetForegroundWindow` takes no arguments. + let foreground = unsafe { GetForegroundWindow() }; + // SAFETY: `GetWindowThreadProcessId` takes any handle value, and no process id is asked for. + !foreground.0.is_null() && unsafe { GetWindowThreadProcessId(foreground, None) } == unsafe { GetCurrentThreadId() } + } + + /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's + /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a + /// top-level window of the app, ) + /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` + /// () go to + /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows + /// they are sent to (). + unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code >= 0 { + // SAFETY: for `HC_ACTION` (0), `lParam` points to the message's `CWPSTRUCT`, which + // lives for the call; `as_ref` gives `None` for a null pointer. + if let Some(cwp) = unsafe { (lparam.0 as *const CWPSTRUCT).as_ref() } { + if message(cwp.message, cwp.wParam.0, cwp.lParam.0) == Message::Deactivated { + note(Message::Deactivated); + deactivate(); + } + crate::windows_stylus::sent_message(cwp.message, cwp.wParam.0); + } + } + // SAFETY: every hook procedure passes the call on, with what it was given. + unsafe { CallNextHookEx(None, code, wparam, lparam) } + } + + /// Installs [`call_wnd_proc`] for this thread, for a pen message at the message time `time`, + /// unless it is installed, and returns whether it is. It stays for the life of the thread. After + /// a failed install, a pen message tries again once [`retry_due`]. + fn hook_thread(time: u32) -> bool { + thread_local! { + /// Installed, or the message time of the last failed install. + static HOOK: std::cell::Cell>> = const { std::cell::Cell::new(Err(None)) }; + } + match HOOK.get() { + Ok(()) => return true, + Err(Some(at)) if !retry_due(at, time) => return false, + Err(_) => {} + } + // SAFETY: a hook of this thread, whose procedure is in this executable, so no module + // handle is passed. + let hooked = unsafe { SetWindowsHookExW(WH_CALLWNDPROC, Some(call_wnd_proc), None, GetCurrentThreadId()) }.is_ok(); + HOOK.set(if hooked { Ok(()) } else { Err(Some(time)) }); + hooked + } + + /// Closes the context for a deactivation noted while the reader was in a call of its own + /// ([`deactivate`]), once that call has ended. + fn settle() { + if NOTICES.with(|n| n.try_borrow().is_ok_and(|n| n.deactivated)) { + deactivate(); + } + } + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns /// whether it is there. The window's property holds the procedure it replaced, and goes with the /// window. @@ -702,15 +829,24 @@ mod win { self.tried = None; self.cursors.clear(); } + if notice.forget { + self.readings.forget(); + } + if notice.deactivated { + self.close(api); + self.tried = None; + } } - /// Moves the context to the window that owns `hwnd` ([`next_context`]). - fn open_for(&mut self, api: Api, hwnd: *mut c_void) { + /// Moves the context to the window that owns `hwnd`, for a pen message at the message time + /// `time` ([`next_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32) { // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; let owner = if owner.is_null() { hwnd } else { owner }; let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); - let (step, open) = next_context(current, self.tried.map(|w| w as usize), owner as usize); + let tried = self.tried.map(|(w, at)| (w as usize, at)); + let (step, open) = next_context(current, tried, owner as usize, time, is_active()); match step { Current::Keep => {} Current::Drop => { @@ -722,7 +858,7 @@ mod win { if !open { return; } - self.tried = Some(owner); + self.tried = Some((owner, time)); let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; configure(&mut words); let handle = hooked_open( @@ -785,22 +921,29 @@ mod win { s.readings.forget(); } } - Message::Closed { .. } | Message::InfoChange | Message::Other => {} + Message::Closed { .. } | Message::InfoChange | Message::Deactivated | Message::Other => {} } }); + settle(); } /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when - /// none is open. + /// none is open. The first call installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// installed, no context opens and the pens read no wheel. pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { let api = api()?; - STATE.with(|s| { + if !hook_thread(time) { + return None; + } + let wheel = STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; s.take_notices(api); - s.open_for(api, hwnd.0); + s.open_for(api, hwnd.0, time); s.readings.wheel_for(time, pen, eraser) - }) + }); + settle(); + wheel } /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer @@ -810,12 +953,16 @@ mod win { } /// Start the readings afresh: the pen left the window or detection range, or a press was - /// canceled. + /// canceled. While the readings are in use, as in a driver call, they start afresh at the next + /// Wintab or pen message ([`Notices::forget_later`]). pub fn forget() { - STATE.with(|s| { - if let Ok(mut s) = s.try_borrow_mut() { - s.readings.forget(); - } + STATE.with(|s| match s.try_borrow_mut() { + Ok(mut s) => s.readings.forget(), + Err(_) => NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.forget_later(); + } + }), }); } } @@ -996,17 +1143,73 @@ mod tests { assert_eq!(r.wheel_at(9000, false), Some(0.3)); } + /// [`next_context`] while this app is the active one. + fn step(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32) -> (Current, bool) { + next_context(current, tried, owner, time, true) + } + #[test] fn the_context_follows_the_window_the_pen_draws_in() { let (main, doc) = (0x10, 0x20); - assert_eq!(next_context(None, None, main), (Current::Keep, true), "the first pen message opens it"); - assert_eq!(next_context(Some((main, true)), Some(main), main), (Current::Keep, false), "the same window keeps it"); - assert_eq!(next_context(Some((main, true)), Some(main), doc), (Current::Close, true), "another document window"); - assert_eq!(next_context(Some((doc, true)), Some(doc), main), (Current::Close, true), "and back"); - assert_eq!(next_context(Some((main, false)), Some(main), doc), (Current::Drop, true), "a window that is gone"); - assert_eq!(next_context(Some((main, false)), Some(main), main), (Current::Drop, true), "its handle reused"); - assert_eq!(next_context(None, Some(main), main), (Current::Keep, false), "an open that failed is not tried again"); - assert_eq!(next_context(None, Some(main), doc), (Current::Keep, true), "but is for another window"); + let t = 1000; + assert_eq!(step(None, None, main, t), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t), (Current::Keep, false), "the same window keeps it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t + 60_000), (Current::Keep, false), "however long it is open"); + assert_eq!(step(Some((main, true)), Some((main, t)), doc, t), (Current::Close, true), "another document window"); + assert_eq!(step(Some((doc, true)), Some((doc, t)), main, t), (Current::Close, true), "and back"); + assert_eq!(step(Some((main, false)), Some((main, t)), doc, t), (Current::Drop, true), "a window that is gone"); + assert_eq!(step(Some((main, false)), Some((main, t)), main, t), (Current::Drop, true), "its handle reused"); + assert_eq!(step(None, Some((main, t)), main, t + 1), (Current::Keep, false), "an open that failed is not tried at once"); + assert_eq!(step(None, Some((main, t)), doc, t + 1), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn a_window_whose_open_failed_is_tried_again_later() { + let main = 0x10; + let t = 1000; + for dt in [0, 1, 500, RETRY_MS - 1] { + assert_eq!(step(None, Some((main, t)), main, t + dt), (Current::Keep, false), "{dt} ms later"); + } + assert_eq!(step(None, Some((main, t)), main, t + RETRY_MS), (Current::Keep, true), "after the retry interval"); + assert_eq!(step(None, Some((main, t)), main, t + 60_000), (Current::Keep, true), "or long after"); + // The message clock wraps after about 49.7 days. + let late = u32::MAX - 100; + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(50)), (Current::Keep, false), "across the wrap"); + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(RETRY_MS)), (Current::Keep, true), "and due across it"); + } + + #[test] + fn a_failed_step_is_retried_after_the_interval() { + assert!(!retry_due(1000, 1000), "at once"); + assert!(!retry_due(1000, 1000 + RETRY_MS - 1)); + assert!(retry_due(1000, 1000 + RETRY_MS), "after the interval"); + assert!(retry_due(u32::MAX - 10, (u32::MAX - 10).wrapping_add(RETRY_MS)), "across the clock's wrap"); + assert!(!retry_due(u32::MAX - 10, 5), "and not early across it"); + } + + #[test] + fn no_context_opens_while_another_app_is_active() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(next_context(None, None, main, t, false), (Current::Keep, false), "a pen hovering over an inactive window"); + assert_eq!(next_context(None, Some((main, t)), main, t + RETRY_MS, false), (Current::Keep, false), "not even when a retry is due"); + assert_eq!(next_context(Some((main, true)), None, doc, t, false), (Current::Close, false), "another window's context closes"); + assert_eq!(next_context(Some((main, false)), None, main, t, false), (Current::Drop, false), "a gone window's is dropped"); + assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); + } + + #[test] + fn another_app_becoming_active_closes_the_context() { + assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); + assert_eq!(message(WM_ACTIVATEAPP, 1, 0), Message::Other, "this app becoming active"); + let ours = 0x5000; + let mut n = Notices::default(); + n.note(Message::Deactivated); + assert_eq!(n.take(Some(ours)), Notice { deactivated: true, ..Notice::default() }); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.note(Message::Deactivated); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, deactivated: true, ..Notice::default() }, "beside the driver's close"); } #[test] @@ -1024,8 +1227,8 @@ mod tests { fn the_drivers_notices_drop_or_reopen_the_context() { let (ours, other) = (0x5000, 0x6000); let keep = Notice::default(); - let closed = Notice { closed: true, info_changed: false }; - let reopen = Notice { closed: false, info_changed: true }; + let closed = Notice { closed: true, ..Notice::default() }; + let reopen = Notice { info_changed: true, ..Notice::default() }; let mut n = Notices::default(); assert_eq!(n.take(Some(ours)), keep, "no notice"); n.note(Message::Closed { ctx: other }); @@ -1060,7 +1263,7 @@ mod tests { #[test] fn a_close_and_an_information_change_in_one_batch_both_count() { let ours = 0x5000; - let both = Notice { closed: true, info_changed: true }; + let both = Notice { closed: true, info_changed: true, ..Notice::default() }; let mut n = Notices::default(); n.note(Message::Closed { ctx: ours }); n.note(Message::InfoChange); @@ -1070,7 +1273,21 @@ mod tests { assert_eq!(n.take(Some(ours)), both, "in either order"); n.note(Message::Closed { ctx: 0x6000 }); n.note(Message::InfoChange); - assert_eq!(n.take(Some(ours)), Notice { closed: false, info_changed: true }, "another context's close"); + assert_eq!(n.take(Some(ours)), Notice { info_changed: true, ..Notice::default() }, "another context's close"); + } + + #[test] + fn a_leave_while_the_readings_are_in_use_starts_them_afresh_next() { + let ours = 0x5000; + let mut n = Notices::default(); + n.forget_later(); + assert_eq!(n.take(Some(ours)), Notice { forget: true, ..Notice::default() }, "the next look starts the readings afresh"); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.forget_later(); + assert_eq!(n.take(None), Notice { forget: true, ..Notice::default() }, "with nothing open too"); + n.forget_later(); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, forget: true, ..Notice::default() }, "beside a close"); } #[test] From 38595ca3fd0ded35aa816b06677ae61990db4f9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 08:52:26 -0800 Subject: [PATCH 12/63] Font menu: the Document filter test holds other tests' font changes back the_document_filter_lists_the_families_the_documents_type_uses lists every family, turns the Document filter on and off, and expects the same list again. A composite font that a test running alongside registers in the process-wide font database in between shows up at the top of the second list, and the test fails. The test now holds test_fonts::steady_fonts on the global database from before its first listing, so those changes wait until it ends. --- crates/ui-egui/src/font_menu/tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index e6dbdcca4e..930417a808 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1176,6 +1176,9 @@ fn the_document_filter_lists_the_families_the_documents_type_uses() { app.run("object.lock", serde_json::json!({})).unwrap(); app.run("text.create", serde_json::json!({"x": 20, "y": 150, "text": "Missing", "font": "Missing Family 7059"})).unwrap(); let db = vectorcraft_text::FontDb::global(); + // Tests running alongside register composite fonts and load fonts in the process-wide database; + // their changes wait until this test ends, so both listings of every family are the same. + let _steady = vectorcraft_text::test_fonts::steady_fonts(db); let used = super::document_families(db, &app.session.active().unwrap().doc); let mut names: Vec<_> = used.iter().cloned().collect(); names.sort(); From 86eed6b47dd963d2f83669c04f9db063d73e89e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:41:21 -0800 Subject: [PATCH 13/63] Selection: a selected linked image is crossed from corner to corner A selected linked image or placed document now shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. An image is outlined along its frame, so a turned or distorted image's outline follows its corners. The lines are selection marks: View > Hide Edges hides them, the hover highlight does not draw them, and output is unchanged. The overlay's point limit counts their ends where they are drawn. Fixes #9080 --- crates/ui-egui/src/canvas/outline.rs | 70 ++++++++++++++++--- crates/ui-egui/src/canvas/overlays.rs | 4 +- crates/ui-egui/src/canvas/panes.rs | 8 ++- crates/ui-egui/src/canvas/panes/tests.rs | 28 +++++++- crates/ui-egui/src/canvas/selection_marks.rs | 4 +- .../src/canvas/selection_marks/tests.rs | 68 ++++++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 26 +++++++ docs/target-app-parity.md | 1 + 8 files changed, 194 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index c2ab7945be..33e9553c2c 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -39,8 +39,8 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } -/// Outline of a node for highlighting (paths, compound children, area type frames, other -/// text/image bounds, symbol instances' bounds measured by their art from `symbols`; a clip +/// Outline of a node for highlighting (paths, compound children, area type frames, other text +/// bounds, images' frames, symbol instances' bounds measured by their art from `symbols`; a clip /// group's clipping path only, as [`walk_drawn`] visits it). pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { let mut bp = BezPath::new(); @@ -62,7 +62,13 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { + // An image shows its frame, turned or distorted with it. + NodeKind::Image(_) => { + if let Some(frame) = c.image_frame() { + bp.extend(frame); + } + } + NodeKind::SymbolInstance { .. } => { if let Some(b) = c.geometric_bounds_with(symbols) { bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); } @@ -87,6 +93,41 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Whether `n` is a linked image or a placed document, which the selection marks cross. +fn is_linked(n: &Node) -> bool { + match &n.kind { + NodeKind::Image(im) => im.link.is_some(), + NodeKind::PlacedDocument(_) => true, + _ => false, + } +} + +/// The corners (top left, top right, bottom right, bottom left) of a linked image's frame or of a +/// placed document's box. `None` for an embedded image and for anything else. +fn linked_corners(n: &Node) -> Option<[Point; 4]> { + match &n.kind { + NodeKind::Image(_) if is_linked(n) => n.image_corners(), + NodeKind::PlacedDocument(p) => Some(p.corners()), + _ => None, + } +} + +/// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, +/// from corner to corner of its frame or box (#9080). The selection marks draw them; the hover +/// highlight does not. +pub(super) fn linked_crosses(n: &Node) -> BezPath { + let mut bp = BezPath::new(); + walk_drawn(n, &mut |c| { + if let Some([tl, tr, br, bl]) = linked_corners(c) { + bp.move_to(tl); + bp.line_to(br); + bp.move_to(tr); + bp.line_to(bl); + } + }); + bp +} + /// The width of the key object's outline (Align to Key Object), thicker than the selection's. pub(super) const KEY_OUTLINE: f32 = 2.5; @@ -100,19 +141,32 @@ pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; /// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; /// counting stops there). pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - fn over(n: &Node, left: &mut usize) -> bool { - match left.checked_sub(overlay_points(n)) { + over_limit(nodes, false) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator) -> bool { + over_limit(nodes, true) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the +/// ends of the crossing lines when `crosses`); counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool) -> bool { + let ends = if crosses && is_linked(n) { 4 } else { 0 }; + match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, None => return true, } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left)) + !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left, crosses)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left)) + nodes.into_iter().any(|n| over(n, &mut left, crosses)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..9d5808e249 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -6,7 +6,7 @@ use egui::epaint::{TessellationOptions, Tessellator}; use super::artboards::names_an_artboard; use super::input::marquee_through; -use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_path, to_screen_path, too_many_anchors}; +use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_path, to_screen_path, too_many_anchors, too_many_marks}; use super::selection_marks::{MarkOptions, SelectionMarks}; use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; @@ -161,7 +161,7 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: }; let st = app.session.active(); let show_marks = !crate::dialogs::halftone::previewing(app); - let big = show_marks && st.is_some_and(|st| too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)))); + let big = show_marks && st.is_some_and(|st| too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)))); let big_bounds = if big { app.selection_bounds() } else { None }; let app = &*app; let Some(st) = app.session.active() else { return }; diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 63d89f2be2..69c6940c25 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -10,7 +10,7 @@ use std::collections::HashMap; use std::sync::Arc; use super::grid::LineLook; -use super::outline::{c32, node_outline, to_screen_path, too_many_anchors}; +use super::outline::{c32, linked_crosses, node_outline, to_screen_path, too_many_marks}; use super::view::fit_zoom; use super::{ Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, @@ -639,7 +639,7 @@ fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec Vec Vec Vec [bool; 4] { + let picture = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), app, p, &view, false)); + let drawn = |q: Point| { + let s = view.to_screen(q); + (-1..=1).any(|dy| { + (-1..=1).any(|dx| { + let (x, y) = ((s.x.round() as i64 + dx) as usize, (s.y.round() as i64 + dy) as usize); + picture.pixels[y * picture.size.0 + x][3] > 0.0 + }) + }) + }; + let [tl, tr, br, bl] = corners; + assert!([(tl, tr), (tr, br), (br, bl), (bl, tl)].into_iter().all(|(a, b)| drawn(a.midpoint(b))), "the outline runs along the frame"); + [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].map(drawn) + }; + let corners = |app: &VectorcraftApp, id: NodeId| { + let n = app.session.active().unwrap().doc.node(id).unwrap(); + match &n.kind { + NodeKind::PlacedDocument(p) => p.corners(), + _ => n.image_corners().unwrap(), + } + }; + app.run("select.all", json!({})).unwrap(); + assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a linked image"); + assert_eq!(crossed(&app, corners(&app, document)), [true; 4], "a placed document"); + assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "an embedded image"); + assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "linked and embedded images"); + app.run("select.set", json!({"ids": [linked.0]})).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a turned linked image, along its frame"); + let doc = &app.session.active().unwrap().doc; + let [tl, tr, br, bl] = corners(&app, linked); + let bounds = doc.node(linked).unwrap().geometric_bounds().unwrap(); + let out = vectorcraft_testkit::raster::render_region(doc, bounds, 1.0); + let pixel = |q: Point| out.pixel((q.x - bounds.x0).round() as u32, (q.y - bounds.y0).round() as u32); + // Halfway between the middle of the left side and the centre: clear of both diagonals. + let clear = pixel(tl.midpoint(bl).midpoint(tl.midpoint(br))); + assert!(clear[0] > 150 && clear[1] < 100 && clear[3] == 255, "the render shows the image: {clear:?}"); + let on_lines = [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)]; + assert!(on_lines.iter().all(|q| pixel(*q) == clear), "output of a selected linked image is not crossed"); +} + /// A frame of the whole canvas keeps entries for the selected objects only. #[test] fn the_canvas_drops_entries_it_does_not_draw() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..d5238029d7 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -776,6 +776,32 @@ fn a_clip_group_over_a_huge_path_shows_its_clipping_path() { assert_eq!((anchors, hovered), (4, true), "the square's four anchors, and the hover highlight"); } +/// The selection marks count the ends of the lines that cross linked images toward the overlay's +/// limit; the hover highlight and the key object's outline, which draw no such lines, do not +/// (#9080). +#[test] +fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { + use super::outline::{too_many_anchors, too_many_marks}; + let image = |link: Option| { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + vectorcraft_doc::Node::new(vectorcraft_doc::NodeId(1), NodeKind::Image(Box::new(im))) + }; + // Four corners each fit; with the four ends of the crossing lines they do not. + let count = OVERLAY_MAX_ANCHORS / 6; + let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; + let embedded = vec![image(None); count]; + assert!(!too_many_anchors(&linked) && too_many_marks(&linked), "linked images"); + assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); +} + /// #2422: the art inside a clip group still shows its whole outline when it is picked on its /// own: by Edit Contents, by a Direct Selection or Group Selection click, and in isolation mode; /// so does its Group Selection hover highlight. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..dd61b03ce9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,6 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a turned one, a placed document, an embedded image and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane. Scores and hours 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. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From d4ca49b7c6bac597597a6f3b3b26dd25e5e89ace Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:13:41 -0800 Subject: [PATCH 14/63] Tests: linked image crosses on distorted images, key, hover, Hide Edges The selection marks test now also checks a distorted linked image and a turned or distorted embedded image, the key object's outline alone and the hover highlight, each along the image's frame and without lines across it. A new test checks that the first canvas frame after View > Hide Edges draws nothing in the layer's color for a selected linked image. The render check comment uses American spelling. --- .../src/canvas/selection_marks/tests.rs | 70 +++++++++++++++---- crates/ui-egui/src/canvas/tests.rs | 41 +++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 97 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index a0ea0f7328..b0fcbc5658 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -586,8 +586,8 @@ fn an_edit_of_a_symbol_outlines_its_instance_again() { } /// A selected linked image and a selected placed document are crossed from corner to corner, on a -/// turned image along its frame; a selected embedded image shows its outline alone, and output of -/// the linked image shows no cross (#9080). +/// turned or distorted image along its frame; a selected embedded image shows its outline alone, +/// along its frame when turned or distorted. A render of the document is not crossed (#9080). #[test] fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; @@ -608,10 +608,9 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { let document = place(&mut app, &placed, true, [200.0, 230.0]); let ctx = egui::Context::default(); let view = xf(1.0, VIEW, 0.0); - // Whether the marks draw within a pixel of each of the points a quarter and three quarters of + // Whether `picture` draws within a pixel of each of the points a quarter and three quarters of // the way along each diagonal of `corners`, clear of the outline. - let crossed = |app: &VectorcraftApp, corners: [Point; 4]| -> [bool; 4] { - let picture = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), app, p, &view, false)); + let crossed_in = |picture: &Picture, corners: [Point; 4]| -> [bool; 4] { let drawn = |q: Point| { let s = view.to_screen(q); (-1..=1).any(|dy| { @@ -625,6 +624,10 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { assert!([(tl, tr), (tr, br), (br, bl), (bl, tl)].into_iter().all(|(a, b)| drawn(a.midpoint(b))), "the outline runs along the frame"); [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].map(drawn) }; + // The same for the selection marks. + let crossed = |app: &VectorcraftApp, corners: [Point; 4]| { + crossed_in(&picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), app, p, &view, false)), corners) + }; let corners = |app: &VectorcraftApp, id: NodeId| { let n = app.session.active().unwrap().doc.node(id).unwrap(); match &n.kind { @@ -637,19 +640,56 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { assert_eq!(crossed(&app, corners(&app, document)), [true; 4], "a placed document"); assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "an embedded image"); assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "linked and embedded images"); - app.run("select.set", json!({"ids": [linked.0]})).unwrap(); + app.run("select.set", json!({"ids": [linked.0, embedded.0]})).unwrap(); app.run("object.rotate", json!({"angle": 30})).unwrap(); assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a turned linked image, along its frame"); + assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "a turned embedded image, outlined along its frame"); + { + let doc = &app.session.active().unwrap().doc; + let [tl, tr, br, bl] = corners(&app, linked); + let bounds = doc.node(linked).unwrap().geometric_bounds().unwrap(); + let out = vectorcraft_testkit::raster::render_region(doc, bounds, 1.0); + let pixel = |q: Point| out.pixel((q.x - bounds.x0).round() as u32, (q.y - bounds.y0).round() as u32); + // Halfway between the middle of the left side and the center: clear of both diagonals. + let clear = pixel(tl.midpoint(bl).midpoint(tl.midpoint(br))); + assert!(clear[0] > 150 && clear[1] < 100 && clear[3] == 255, "the render shows the image: {clear:?}"); + let on_lines = [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)]; + assert!(on_lines.iter().all(|q| pixel(*q) == clear), "output of a selected linked image is not crossed"); + } + // Move each image's bottom right corner up its right side, so its corners no longer make a + // parallelogram and one diagonal turns away from where it ran. + app.session + .edit("Distort", |doc, _| { + for id in [linked, embedded] { + if let Some(n) = doc.node_mut(id) + && let Some([tl, tr, br, bl]) = n.image_corners() + { + n.set_image_corners([tl, tr, br.lerp(tr, 0.4), bl]).map_err(|e| vectorcraft_engine::EngineError::Other(format!("{e:?}")))?; + } + } + Ok(()) + }) + .unwrap(); let doc = &app.session.active().unwrap().doc; - let [tl, tr, br, bl] = corners(&app, linked); - let bounds = doc.node(linked).unwrap().geometric_bounds().unwrap(); - let out = vectorcraft_testkit::raster::render_region(doc, bounds, 1.0); - let pixel = |q: Point| out.pixel((q.x - bounds.x0).round() as u32, (q.y - bounds.y0).round() as u32); - // Halfway between the middle of the left side and the centre: clear of both diagonals. - let clear = pixel(tl.midpoint(bl).midpoint(tl.midpoint(br))); - assert!(clear[0] > 150 && clear[1] < 100 && clear[3] == 255, "the render shows the image: {clear:?}"); - let on_lines = [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)]; - assert!(on_lines.iter().all(|q| pixel(*q) == clear), "output of a selected linked image is not crossed"); + assert!([linked, embedded].iter().all(|id| doc.node(*id).unwrap().is_distorted_image()), "both images are distorted"); + assert_eq!(crossed(&app, corners(&app, linked)), [true; 4], "a distorted linked image, corner to corner"); + assert_eq!(crossed(&app, corners(&app, embedded)), [false; 4], "a distorted embedded image, outlined along its frame"); + // The key object's outline alone, with no other selection marks. + for id in [linked, embedded] { + let st = app.session.active_mut().unwrap(); + st.selection.objects.clear(); + st.selection.key = Some(id); + let key = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), &app, p, &view, false)); + assert_eq!(crossed_in(&key, corners(&app, id)), [false; 4], "the key object's outline of a distorted image, {id:?}"); + } + // The hover highlight outlines a linked image along its frame and does not cross it. + app.run("select.set", json!({"ids": []})).unwrap(); + for id in [linked, embedded] { + let [tl, tr, br, bl] = corners(&app, id); + app.hover_doc = Some(tl.midpoint(tr).midpoint(bl.midpoint(br))); + let hovered = picture(&ctx, 1.0, |p| super::super::overlays::hover_highlight(&app, p, &view)); + assert_eq!(crossed_in(&hovered, [tl, tr, br, bl]), [false; 4], "the hover highlight of a distorted image, {id:?}"); + } } /// A frame of the whole canvas keeps entries for the selected objects only. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5238029d7..e80d331bdb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -802,6 +802,47 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); } +/// View › Hide Edges hides the lines across a selected linked image along with its outline +/// (#9080). +#[test] +fn hide_edges_hides_the_lines_across_a_linked_image() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let dir = vectorcraft_testkit::temp_dir("hide-edges-linked"); + let png = dir.join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut place = + |link: bool, at: [f64; 2]| app.run("file.place", json!({"path": png, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap(); + let (linked, embedded) = (place(true, [100.0, 120.0]), place(false, [250.0, 120.0])); + let ctx = egui::Context::default(); + let select = |app: &mut VectorcraftApp, id: u64| { + app.run("select.set", json!({"ids": [id]})).unwrap(); + frame(app, &ctx, vec![]); + }; + // The vertices the next canvas frame draws in the layer color of `id`. + let marks = |app: &mut VectorcraftApp, id: u64| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let color = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id))); + let mesh = |p: &egui::ClippedPrimitive| match &p.primitive { + egui::epaint::Primitive::Mesh(m) => m.vertices.iter().filter(|v| v.color == color).count(), + egui::epaint::Primitive::Callback(_) => 0, + }; + ctx.tessellate(out.shapes, out.pixels_per_point).iter().map(mesh).sum::() + }; + select(&mut app, embedded); + let shown_embedded = marks(&mut app, embedded); + select(&mut app, linked); + let shown_linked = marks(&mut app, linked); + assert!(shown_linked > shown_embedded, "the lines across the linked image draw: {shown_linked} > {shown_embedded}"); + // The linked image stays selected, and the first frame after edges are hidden is checked. + app.ui.view.edges = false; + assert_eq!(marks(&mut app, linked), 0, "with edges hidden, a selected linked image draws nothing in its layer's color"); +} + /// #2422: the art inside a clip group still shows its whole outline when it is picked on its /// own: by Edit Contents, by a Direct Selection or Group Selection click, and in isolation mode; /// so does its Group Selection hover highlight. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dd61b03ce9..d15f17cd5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,7 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. -- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a turned one, a placed document, an embedded image and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours 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. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From e53a643c86804abc933e75537040e06aa9dbfdc2 Mon Sep 17 00:00:00 2001 From: centy Date: Sun, 22 Nov 2026 08:42:40 -0500 Subject: [PATCH 15/63] Reflect by two clicks passes its drag to solve as a SolveDrag Co-Authored-By: Claude Fable 5.2 --- crates/tools/src/xform/transform.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 5637ce3db1..713945a0f7 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -453,7 +453,7 @@ impl Tool for TransformTool { } self.drop_axis(); let copy = ev.mods.alt; - let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds); + let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds }); vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit] } else { // A click sets the reference point; with Alt, it opens the dialog too. With the From e79aa9836a7d86657ed6d66a05b5ad449fde71ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:45:22 -0800 Subject: [PATCH 16/63] Docs: linked image crosses above the outline point limit The progress-doc entry now says that above the 100,000-point overlay limit, counting 4 points for each linked image's or placed document's lines, both the current pane and other panes draw one rectangle around the selection instead of outlines and crossing lines. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d15f17cd5c..d6006c9e7e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,7 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. -- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours 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. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From 494635f9326e19212a81ed92fb8a931cc84985a7 Mon Sep 17 00:00:00 2001 From: centy Date: Sun, 22 Nov 2026 10:25:45 -0500 Subject: [PATCH 17/63] Format the Reflect solve call Co-Authored-By: Claude Fable 5.2 --- crates/tools/src/xform/transform.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 713945a0f7..c20f5f3a83 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -453,7 +453,11 @@ impl Tool for TransformTool { } self.drop_axis(); let copy = ev.mods.alt; - let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds }); + let (m, _, _) = self.solve( + d.angle_for(copy, ev.backquote), + first, + SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds }, + ); vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit] } else { // A click sets the reference point; with Alt, it opens the dialog too. With the From 9562ed9b04d7a89d101e9456bafbbbc54b177ab4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:26:19 -0800 Subject: [PATCH 18/63] Preferences: Reset Preferences resets Smart Guides, Snap to Grid and the Contextual Task Bar The Preferences dialog shows Smart Guides, Snap to Grid and General's Enable Contextual Task Bar, but the app keeps them with the interface state, and Reset Preferences left them as they were. Confirming Reset Preferences now puts their defaults in the dialog with the other defaults: Smart Guides on, Snap to Grid off, and the task bar as the current workspace was saved. OK applies them and Cancel keeps the values in use. On a touch screen, where the reset turns Enable Touch Workspace back on, OK sets the task bar in the workspace it leaves, and the Touch workspace keeps its own. prefs.reset (the Command Palette's Reset Preferences), alone or as a command.batch step, resets them too, each only when it resets every category or the setting's own (Smart Guides, Guides & Grid, General). With every category or File Handling it also clears the app chosen for Edit Original, as the dialog's reset does. The engine records the categories it reset (Session::take_prefs_resets), and the app resets its own settings from them after each command, each frame, and before a touch screen switches to the Touch workspace. A category that is not a string is now an error instead of a reset of every category. --- crates/engine/src/cmd/prefscmds.rs | 22 ++- crates/engine/src/lib.rs | 2 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/prefs.rs | 18 +++ crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/commands.rs | 3 + crates/ui-egui/src/dialogs/confirm.rs | 2 +- crates/ui-egui/src/original_editor.rs | 30 ++++ crates/ui-egui/src/prefs_dialog.rs | 53 ++++++- crates/ui-egui/src/prefs_dialog/tests.rs | 170 +++++++++++++++++++++++ crates/ui-egui/src/workspaces.rs | 2 + docs/mcp.md | 6 + docs/target-app-parity.md | 1 + 13 files changed, 299 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 46cdee28a5..16c64db12c 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -707,6 +707,12 @@ impl Prefs { } impl Session { + /// Take the categories `prefs.reset` reset since the last call, each once, with `None` for a + /// reset of every category. A frontend resets the settings it keeps itself in them. + pub fn take_prefs_resets(&mut self) -> Vec> { + std::mem::take(&mut self.prefs_resets) + } + /// Replace the preferences and push the ones with engine-side consumers into open documents /// and the renderer (grid, history depth, render threads). pub fn apply_prefs(&mut self, mut p: Prefs) { @@ -814,7 +820,7 @@ pub fn specs() -> Vec { always, set ), - cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset), + cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?: string} reset one category (or everything, with category left out or null) to defaults; an unknown category or one that is not a string is an error", always, reset), cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list), cmd!( query "prefs.export", @@ -997,15 +1003,17 @@ fn set(s: &mut Session, p: &Value) -> Result { } fn reset(s: &mut Session, p: &Value) -> Result { - let cat = str_param(p, "category"); - if let Some(c) = cat - && !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c)) - { - return Err(bad("prefs.reset", format!("unknown category `{c}`"))); - } + let cat = text_param(p, "category", "prefs.reset")?; + let known = |c: &str| { + PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`"))) + }; + let category = cat.map(known).transpose()?; let mut next = s.prefs.clone(); next.reset(cat); s.apply_prefs(next); + if !s.prefs_resets.contains(&category) { + s.prefs_resets.push(category); + } Ok(json!({ "prefs": shown_prefs(&s.prefs) })) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..f786340107 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -118,6 +118,8 @@ pub struct Session { /// Set when a command that draws a shape was journaled outside saved steps /// ([`Session::take_shape_drawn`]). shape_drawn: bool, + /// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]). + prefs_resets: Vec>, /// Set when the active tool panicked (see [`guard`]); reported by the next tool event. tool_panic: Option, /// How many times switching or closing documents, or replacing the active one, has started the diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..156cd59ea3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -74,6 +74,7 @@ impl Session { depth: 0, replaying: false, shape_drawn: false, + prefs_resets: Vec::new(), tool_panic: None, tool_resets: 0, tool_set_since_reset: false, diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 966e68dc60..0d5bdab829 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -216,6 +216,24 @@ fn reset_category_and_all() { assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); } +/// `prefs.reset` records each category it reset once, `None` for every category, and a failed +/// reset records nothing. +#[test] +fn prefs_reset_records_the_categories_it_reset() { + let mut s = Session::new(); + assert!(s.take_prefs_resets().is_empty()); + s.execute("prefs.reset", &json!({"category": "general"})).unwrap(); + s.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![Some("General")]); + assert!(s.take_prefs_resets().is_empty(), "taking clears the list"); + assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); + assert!(s.execute("prefs.reset", &json!({"category": 5})).is_err()); + assert!(s.take_prefs_resets().is_empty(), "a failed reset records nothing"); + s.execute("prefs.reset", &json!({})).unwrap(); + s.execute("prefs.reset", &json!({"category": "Type"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![None, Some("Type")]); +} + /// A rectangle made into a guide path; nothing is selected after. fn guide_path(s: &mut Session, x: f64) -> NodeId { let id = square(s, x, 0.0); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..8142b558a8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -652,6 +652,8 @@ impl VectorcraftApp { // panel (Show on Shape Creation). panels::transform::show_on_shape_creation(self, &ctx); crate::toasts::show(self, &ctx); + // A `prefs.reset` run in this pass outside `Self::run`. + crate::prefs_dialog::apply_prefs_resets(self); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); if self.custom_titlebar { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..e68f68c50b 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -75,6 +75,8 @@ impl VectorcraftApp { pub fn run(&mut self, id: &str, params: Value) -> Result { self.beacon.command(id); let touch_workspace = self.session.prefs.touch_workspace; + // A `prefs.reset` that ran straight on the session applies before this command can switch workspaces. + crate::prefs_dialog::apply_prefs_resets(self); // A file dialog it shows off the UI thread runs it again with the path picked. let result = if self.picks.is_entry_free() { let entry = picks::Entry::Command(id.to_string(), params.clone()); @@ -82,6 +84,7 @@ impl VectorcraftApp { } else { self.run_now(id, params) }; + crate::prefs_dialog::apply_prefs_resets(self); if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); } diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 756bf71255..2b0a26b832 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -129,7 +129,7 @@ pub(crate) fn ask_reset_prefs(app: &mut VectorcraftApp) { /// OK on [`ask_reset_prefs`]: Preferences again, its fields at their defaults. fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut prefs = super::parent(d).filter(|p| p.kind == "preferences").ok_or("the dialog it was opened over is no longer open")?; - crate::prefs_dialog::reset_fields(&mut prefs); + crate::prefs_dialog::reset_fields(&mut prefs, &app.ui); crate::original_editor::reset(app); app.ui.dialog = Some(prefs); Ok(Value::Null) diff --git a/crates/ui-egui/src/original_editor.rs b/crates/ui-egui/src/original_editor.rs index ebdfcc4233..0936dc634e 100644 --- a/crates/ui-egui/src/original_editor.rs +++ b/crates/ui-egui/src/original_editor.rs @@ -33,6 +33,12 @@ pub(crate) fn reset(app: &mut VectorcraftApp) { app.original_editor.generation = app.original_editor.generation.wrapping_add(1); } +/// `prefs.reset`: the saved choice goes back to the default, and the next Preferences shows it. +pub(crate) fn reset_saved(app: &mut VectorcraftApp) { + app.ui.original_editor = Choice::default(); + reset(app); +} + pub(crate) fn cancel(app: &mut VectorcraftApp) { open(app); } @@ -173,6 +179,30 @@ mod tests { assert!(app.ui.original_editor.path.is_none()); } + /// `prefs.reset` of every category or of File Handling, alone or as a batch step, resets the + /// saved choice; a reset of another category keeps it. + #[test] + fn prefs_reset_resets_the_saved_choice_with_file_handling() { + let mut app = app(); + let chosen = |app: &mut VectorcraftApp| { + prefs_dialog::open(app, Some("File Handling")); + choose(app, Some("/Apps/My Editor.app")).unwrap(); + prefs_dialog::confirm(app).unwrap(); + assert!(app.ui.original_editor.path.is_some()); + }; + chosen(&mut app); + app.run("prefs.reset", json!({"category": "General"})).unwrap(); + assert!(app.ui.original_editor.path.is_some(), "General keeps the choice"); + app.run("prefs.reset", json!({"category": "File Handling"})).unwrap(); + assert!(app.ui.original_editor.path.is_none(), "File Handling resets it"); + chosen(&mut app); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("command.batch", json!({"commands": [{"command": "prefs.reset", "params": {}}]})).unwrap(); + assert!(app.ui.original_editor.path.is_none(), "every category, as a batch step"); + prefs_dialog::open(&mut app, Some("File Handling")); + assert!(app.original_editor.choice.path.is_none(), "Preferences shows the default"); + } + #[test] fn original_editor_routing_and_errors() { let mut app = app(); diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index f6bd364449..70d7bc5d5f 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -225,12 +225,21 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result { let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); let document_units = d.fields.get(RESET_UNITS).is_none_or(|v| values.get("unitsGeneral") != Some(v)); app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?; + // Outside an automatic Touch switch, the task bar is set before OK can enter the Touch + // workspace, so it goes to the workspace being left; during one, after OK leaves it. + let task_bar = d.fields.get("__taskBar").and_then(Value::as_bool); + let before_switch = app.ui.touch_workspace_restore.is_none(); + if before_switch && let Some(on) = task_bar { + app.ui.task_bar = on; + } if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(app, app.touch_screen); } app.ui.view.smart_guides = d.fields.get("__smartGuides").and_then(Value::as_bool).unwrap_or(app.ui.view.smart_guides); app.ui.view.snap_to_grid = d.fields.get("__snapToGrid").and_then(Value::as_bool).unwrap_or(app.ui.view.snap_to_grid); - app.ui.task_bar = d.fields.get("__taskBar").and_then(Value::as_bool).unwrap_or(app.ui.task_bar); + if !before_switch && let Some(on) = task_bar { + app.ui.task_bar = on; + } crate::original_editor::commit(app); app.ui.dialog = None; app.ui.engine_prefs = app.session.prefs.to_json(); @@ -484,17 +493,51 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } /// Reset Preferences, once its question is confirmed: every preference in the Preferences dialog -/// `d` takes its default value. The category, the search and the UI-only rows stay as they were; -/// nothing is applied until OK, which leaves the open document's units alone unless Units › -/// General is changed after the reset. -pub(crate) fn reset_fields(d: &mut Dialog) { +/// `d` takes its default value, the UI-only rows ([`UI_FIELDS`]) included. The category and the +/// search stay as they were; nothing is applied until OK, which leaves the open document's units +/// alone unless Units › General is changed after the reset. +pub(crate) fn reset_fields(d: &mut Dialog, ui: &crate::UiState) { for (k, v) in Prefs::default().to_json().as_object().cloned().unwrap_or_default() { d.fields.insert(k, v); } + for (key, value) in default_ui_fields(ui) { + d.fields.insert(key.into(), json!(value)); + } // OK resets the Units ▸ General preference and leaves the open document's units alone. d.fields.insert(RESET_UNITS.into(), d.fields.get("unitsGeneral").cloned().unwrap_or(Value::Null)); } +/// The default of each UI-only row ([`UI_FIELDS`]), by key. Enable Contextual Task Bar takes the +/// value the current workspace was saved with, so a reset leaves the workspace as it was saved. +fn default_ui_fields(ui: &crate::UiState) -> [(&'static str, bool); 3] { + let first = crate::UiState::default(); + let task_bar = crate::workspaces::find_saved(ui, &ui.workspace).map_or(first.task_bar, |w| w.task_bar); + [("__smartGuides", first.view.smart_guides), ("__snapToGrid", first.view.snap_to_grid), ("__taskBar", task_bar)] +} + +/// After `prefs.reset`, alone or as a batch step, of every category or of one: the UI-only rows +/// ([`UI_FIELDS`]) and the Edit Original app of the categories it reset take their defaults too. +pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) { + let resets = app.session.take_prefs_resets(); + if resets.is_empty() { + return; + } + let in_reset = |category: &str| resets.iter().any(|r| r.is_none_or(|c| c == category)); + for (key, value) in default_ui_fields(&app.ui) { + let reset = UI_FIELDS.iter().any(|&(k, c, _)| k == key && in_reset(c)); + match key { + "__smartGuides" if reset => app.ui.view.smart_guides = value, + "__snapToGrid" if reset => app.ui.view.snap_to_grid = value, + "__taskBar" if reset => app.ui.task_bar = value, + _ => {} + } + } + // The Edit Original row shows the app's Edit Original choice. + if vectorcraft_engine::cmd::prefscmds::spec("editOriginalSystemDefaults").is_some_and(|s| in_reset(s.category)) { + crate::original_editor::reset_saved(app); + } +} + /// The height of the fields column under the category's name: the field list, the gap and the /// description line. const FIELDS_HEIGHT: f32 = 400.0; diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index c79ca22470..0074301e7d 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -495,6 +495,159 @@ fn reset_preferences_then_ok_leaves_the_documents_units() { assert_eq!(st.history.undo.len(), undo, "no undo step"); } +/// Reset Preferences returns every UI-only row (Smart Guides, Snap to Grid, Enable Contextual Task +/// Bar) to its default in the dialog, the value a new app shows. OK applies them; Cancel keeps the values in use. +#[test] +fn reset_preferences_resets_the_ui_only_rows() { + let mut fresh = app(); + open(&mut fresh, None); + let first = fresh.ui.dialog.take().unwrap().fields; + let rows = |a: &VectorcraftApp| (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar); + let default = rows(&fresh); + let changed = (!default.0, !default.1, !default.2); + let reset_changed = |a: &mut VectorcraftApp| { + (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) = changed; + open(a, Some("General")); + for (key, _, _) in UI_FIELDS { + assert_ne!(a.ui.dialog.as_ref().unwrap().fields[*key], first[*key], "{key} starts changed"); + } + reset_preferences(a); + }; + let mut a = app(); + reset_changed(&mut a); + for (key, _, _) in UI_FIELDS { + assert_eq!(a.ui.dialog.as_ref().unwrap().fields[*key], first[*key], "{key} is at its default in the dialog"); + } + assert_eq!(rows(&a), changed, "nothing applied before OK"); + confirm(&mut a).unwrap(); + assert_eq!(rows(&a), default, "OK applies the defaults"); + + let mut b = app(); + reset_changed(&mut b); + crate::dialogs::cancel(&mut b); + assert!(b.ui.dialog.is_none()); + assert_eq!(rows(&b), changed, "Cancel keeps the values in use"); +} + +/// `prefs.reset` (the Command Palette's Reset Preferences) also returns the UI-only rows to their +/// defaults, as a batch step too; with a category, only that category's rows; with an +/// unknown or malformed category, none. +#[test] +fn prefs_reset_resets_the_ui_only_rows_of_its_category() { + let fresh = app(); + let rows = |a: &VectorcraftApp| (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar); + let default = rows(&fresh); + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) = (!default.0, !default.1, !default.2); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + for bad in [json!("Nowhere"), json!(["General"]), json!(5)] { + assert!(a.run("prefs.reset", json!({"category": bad})).is_err(), "{bad}"); + assert_eq!(rows(&a), (!default.0, !default.1, !default.2), "{bad}: an unknown or malformed category resets nothing"); + assert_eq!(a.session.prefs.keyboard_increment, 7.0, "{bad}: the preferences are kept"); + } + a.run("prefs.reset", json!({"category": "general"})).unwrap(); + assert_eq!(rows(&a), (!default.0, !default.1, default.2), "General: Enable Contextual Task Bar only"); + a.run("command.batch", json!({"commands": [{"command": "prefs.reset", "params": {"category": "Guides & Grid"}}]})).unwrap(); + assert_eq!(rows(&a), (!default.0, default.1, default.2), "Guides & Grid, as a batch step: Snap to Grid only"); + a.run("prefs.reset", json!({"category": "Smart Guides"})).unwrap(); + assert_eq!(rows(&a), default, "Smart Guides: Smart Guides"); + (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) = (!default.0, !default.1, !default.2); + a.run("prefs.reset", json!({})).unwrap(); + assert_eq!(rows(&a), default, "every category"); +} + +/// Reset Preferences and `prefs.reset` give Enable Contextual Task Bar the value the current +/// workspace was saved with, which for a workspace saved with the bar off differs from the default. +#[test] +fn reset_preferences_gives_the_task_bar_the_workspaces_value() { + let off = crate::workspaces::builtins().into_iter().find(|w| !w.task_bar).unwrap(); + let in_workspace = |a: &mut VectorcraftApp| { + crate::workspaces::switch(&mut a.ui, &off.name).unwrap(); + assert!(!a.ui.task_bar, "{} starts with the bar off", off.name); + a.ui.task_bar = true; + }; + let mut a = app(); + in_workspace(&mut a); + open(&mut a, Some("General")); + reset_preferences(&mut a); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields["__taskBar"], json!(false), "the dialog shows the workspace's value"); + confirm(&mut a).unwrap(); + assert!(!a.ui.task_bar, "OK applies the workspace's value"); + + let mut b = app(); + in_workspace(&mut b); + b.run("prefs.reset", json!({"category": "General"})).unwrap(); + assert!(!b.ui.task_bar, "prefs.reset gives the workspace's value"); + let mut c = app(); + assert!(c.ui.task_bar, "the default workspace starts with the bar on"); + c.ui.task_bar = false; + c.run("prefs.reset", json!({})).unwrap(); + assert!(c.ui.task_bar, "the default workspace's value"); +} + +/// On a touch screen, OK after Reset Preferences turns Enable Touch Workspace back on: the reset task +/// bar goes to the workspace left, and Touch keeps its own. With Touch entered automatically while +/// Preferences was open, clearing Enable Touch Workspace gives the row to the workspace returned to. +#[test] +fn ok_sets_the_task_bar_in_the_workspace_outside_touch() { + let mut a = app(); + a.touch_screen = true; + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + crate::workspaces::switch(&mut a.ui, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + open(&mut a, Some("General")); + reset_preferences(&mut a); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields["touchWorkspace"], json!(true), "the reset turns it on"); + confirm(&mut a).unwrap(); + assert_eq!(a.ui.workspace, crate::workspaces::TOUCH); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + let classic = a.ui.workspace_changes.iter().find(|w| w.name == "Essentials Classic").unwrap(); + assert!(!classic.task_bar, "the workspace left takes the reset value"); + + let mut b = app(); + b.run("prefs.set", json!({"key": "touchWorkspace", "value": true})).unwrap(); + crate::workspaces::switch(&mut b.ui, "Essentials Classic").unwrap(); + open(&mut b, Some("General")); + b.touch_screen = true; + crate::workspaces::sync_touch_workspace(&mut b, true); + assert_eq!(b.ui.workspace, crate::workspaces::TOUCH); + b.ui.dialog.as_mut().unwrap().fields.insert("touchWorkspace".into(), json!(false)); + confirm(&mut b).unwrap(); + assert_eq!(b.ui.workspace, "Essentials Classic"); + assert!(!b.ui.task_bar, "the workspace returned to takes the row"); + let touch = b.ui.workspace_changes.iter().find(|w| w.name == crate::workspaces::TOUCH).unwrap(); + assert!(touch.task_bar, "Touch keeps its own task bar"); +} + +/// A `prefs.reset` run straight on the session, outside `VectorcraftApp::run`, resets the UI-only +/// rows by the end of the next frame. +#[test] +fn prefs_reset_outside_run_resets_the_ui_only_rows_in_the_next_frame() { + let mut a = app(); + let default = (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar); + (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) = (!default.0, !default.1, !default.2); + a.session.execute("prefs.reset", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + a.logic(ui.ctx()); + a.ui(ui); + }); + out.textures_delta.clear(); + assert_eq!((a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar), default); + + // Before the next command switches workspaces: the workspace left keeps the reset value. + let mut b = app(); + crate::workspaces::switch(&mut b.ui, "Essentials Classic").unwrap(); + b.ui.task_bar = true; + b.session.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + b.run("window.workspace", json!({"name": crate::workspaces::ESSENTIALS})).unwrap(); + assert!(b.ui.task_bar, "Essentials keeps its own task bar"); + let classic = b.ui.workspace_changes.iter().find(|w| w.name == "Essentials Classic").unwrap(); + assert!(!classic.task_bar, "the workspace left keeps the reset value"); +} + /// After Reset Preferences, choosing a General unit in the dialog still sets the document's units /// on OK, Points included once another unit was chosen in between. With no document open, Reset /// Preferences resets General to its default. @@ -1517,6 +1670,23 @@ fn prefs_import_of_touch_workspace_switches_the_workspace() { assert_eq!(a.ui.workspace, "Typography"); } +/// A `prefs.reset` run straight on the session, then a touch screen that switches to Touch: the +/// workspace left keeps the reset value. +#[test] +fn a_pending_prefs_reset_applies_before_a_touch_switch() { + let mut a = app(); + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + crate::workspaces::switch(&mut a.ui, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + a.session.execute("prefs.reset", &json!({})).unwrap(); + assert!(a.session.prefs.touch_workspace, "the reset turns Enable Touch Workspace on"); + crate::workspaces::sync_touch_workspace(&mut a, true); + assert_eq!(a.ui.workspace, crate::workspaces::TOUCH); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + let classic = a.ui.workspace_changes.iter().find(|w| w.name == "Essentials Classic").unwrap(); + assert!(!classic.task_bar, "the workspace left keeps the reset value"); +} + /// File Handling › Data Recovery › Folder has a Choose… button where the host has a folder /// picker, and none where it has not (the web). #[test] diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index c409b6b71a..a1c7464866 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -175,6 +175,8 @@ pub fn builtins() -> Vec { /// restored if Touch was entered automatically. Each switch keeps the layout it leaves and brings /// back the one it returns to as it was left, as Window › Workspace does. pub fn sync_touch_workspace(app: &mut VectorcraftApp, touch_screen: bool) { + // A pending `prefs.reset` applies to the workspace it was run in. + crate::prefs_dialog::apply_prefs_resets(app); let auto = app.session.prefs.touch_workspace && touch_screen; if auto { if app.ui.workspace != TOUCH { diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..3cda5a8c0b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8831,6 +8831,12 @@ Preferences. `prefs.reset` resets the preferences at once, without the question. {"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"unitsGeneral","value":"millimeters"}}} ``` +Reset Preferences also sets the dialog's `__smartGuides`, `__snapToGrid` and `__taskBar` fields to their defaults +(`__taskBar` takes the value the current workspace was saved with). In the app, `prefs.reset` also resets Smart Guides, +Snap to Grid and Enable Contextual Task Bar when it resets every category or their category (Smart Guides, Guides & +Grid and General), and the app chosen for Edit Original when it resets every category or File Handling. A `category` +left out or `null` resets every category, and one that is not a string is an error. + `prefs.export {path?}` writes the preferences as a JSON file, `{"format": "vectorcraft-preferences", "version": 1, "prefs": {…}}`, and replies `{path, count}`; without `path` it replies `{data, count}` with the file's text. The file holds every preference `prefs.list` lists and the `eyedropper`, `perspectiveWidget`, `pathfinder`, `glyphSnap` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..f605c84224 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -885,6 +885,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog (`resetPreferences`). Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Reset Preferences resets every setting the dialog shows:** Smart Guides and Snap to Grid also return to their defaults (on and off) when Reset Preferences is confirmed, and General's Enable Contextual Task Bar takes the value the current workspace was saved with. OK in Preferences applies them with the other defaults, and Cancel keeps the values in use. `prefs.reset` (the Command Palette's Reset Preferences) resets them too, each only when it resets every category or the setting's own, and with every category or File Handling it also clears the app chosen for Edit Original. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`, `crates/ui-egui/src/original_editor.rs`. - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. From 4f6e1515b46f52a71b7e2b79fe1b709bf2e0ebef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:16:18 -0800 Subject: [PATCH 19/63] Selection: a selected group leaves its hidden members unmarked The selection marks walked every member of a selected group or layer, so a hidden member, and the art inside a hidden group or a hidden sublayer, showed its outline, its anchors and the lines across a linked image, although the canvas does not draw hidden objects. The walk now skips hidden members, so the selection marks, the hover highlight and the outlines in other panes leave them out, and the overlay point limit no longer counts their points. The same holds for the members of a blend, a repeat and an intertwine. A compound path keeps every path, since it draws all of them, and an Image Trace object keeps its hidden source image in the views that show it. A hidden object that is itself selected keeps its marks. --- crates/doc/src/node/ops.rs | 3 +- crates/ui-egui/src/canvas/outline.rs | 24 +++++- .../src/canvas/selection_marks/tests.rs | 64 ++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 84 ++++++++++++++++++- docs/target-app-parity.md | 1 + 5 files changed, 170 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..42bece8844 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -361,7 +361,8 @@ impl Node { } /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. + /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. The canvas's selection + /// highlights also leave out hidden members, except a compound path's paths. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); let trace_source = self.extras().trace.is_some() diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 33e9553c2c..fbb2241f3d 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use super::{BezPath, Color32, Node, NodeKind, PathEl, Point, Pos2, Shape, Stroke, SymbolBoxes, VectorcraftApp, Xf, pos2}; pub(super) fn to_screen_path(bp: &BezPath, xf: &Xf) -> Vec> { @@ -163,7 +165,7 @@ fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> b if n.clips() { return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left, crosses)) + !matches!(n.kind, NodeKind::Envelope { .. }) && drawn_children(n).any(|c| over(c, left, crosses)) } let mut left = OVERLAY_MAX_ANCHORS; nodes.into_iter().any(|n| over(n, &mut left, crosses)) @@ -193,9 +195,23 @@ fn overlay_points(n: &Node) -> usize { } } +/// The children of `n` that [`walk_drawn`] visits: [`Node::editing_children`], without the hidden +/// members, which the canvas does not draw. An Image Trace object's hidden source image stays when +/// the object's view shows it. Every path of a compound path stays, since the compound path draws +/// all of them. +fn drawn_children(n: &Node) -> impl Iterator> { + let members = !matches!(n.kind, NodeKind::Compound { .. }); + let source = (n.extras().trace.is_some() && n.trace_view().shows_source()) + .then(|| n.children().and_then(|children| children.first())) + .flatten() + .filter(|c| matches!(c.kind, NodeKind::Image(_))); + n.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) +} + /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the -/// envelope shows its mesh instead), and a clip group or clipping layer shows only its clipping -/// path, its first child, not the art the path clips (#2422). +/// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, +/// its first child, not the art the path clips (#2422), and hidden members are left out +/// ([`drawn_children`]). pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { @@ -207,7 +223,7 @@ pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { } return; } - for c in n.editing_children().iter() { + for c in drawn_children(n) { walk_drawn(c, f); } } diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index b0fcbc5658..32459a5825 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -692,6 +692,70 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { } } +/// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member +/// and the members of a hidden group inside it leave no outline, anchors or crossing lines. +#[test] +fn a_selected_group_leaves_its_hidden_members_unmarked() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let dir = vectorcraft_testkit::temp_dir("selection-marks-hidden"); + let png = dir.join("red.png"); + let pixels = [200u8, 40, 40, 255].repeat(40 * 40); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, pixels).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let left = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let right = id_of(&app.run("shape.rectangle", json!({"x": 330, "y": 230, "width": 20, "height": 20})).unwrap()); + let hidden = id_of(&app.run("shape.rectangle", json!({"x": 120, "y": 100, "width": 40, "height": 40})).unwrap()); + let linked = NodeId(app.run("file.place", json!({"path": png, "link": true, "at": [240.0, 150.0]})).unwrap()["ids"][0].as_u64().unwrap()); + app.run("select.set", json!({"ids": [linked.0]})).unwrap(); + let inner = id_of(&app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [left.0, right.0, hidden.0, inner.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + app.session + .edit("Hide", |doc, _| { + for id in [hidden, inner] { + if let Some(n) = doc.node_mut(id) { + n.visible = false; + } + } + Ok(()) + }) + .unwrap(); + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let ctx = egui::Context::default(); + let view = xf(1.0, VIEW, 0.0); + let marks = picture(&ctx, 1.0, |p| paint(&mut SelectionMarks::default(), &app, p, &view, false)); + // Whether the marks draw within a pixel of document point `q`. + let drawn = |q: Point| { + let s = view.to_screen(q); + (-1..=1).any(|dy| { + (-1..=1).any(|dx| { + let (x, y) = ((s.x.round() as i64 + dx) as usize, (s.y.round() as i64 + dy) as usize); + marks.pixels[y * marks.size.0 + x][3] > 0.0 + }) + }) + }; + let doc = &app.session.active().unwrap().doc; + let sides = |id: NodeId| { + let b = doc.node(id).unwrap().geometric_bounds().unwrap(); + [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] + }; + for id in [left, right] { + let [tl, tr, br, bl] = sides(id); + assert!([tl, tr, br, bl, tl.midpoint(tr), br.midpoint(bl)].into_iter().all(drawn), "a visible member is outlined and marked"); + } + let [tl, tr, br, bl] = doc.node(linked).unwrap().image_corners().unwrap(); + assert!( + ![tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].into_iter().any(drawn), + "the lines across a linked image in a hidden group" + ); + assert!(![tl.midpoint(tr), tr.midpoint(br)].into_iter().any(drawn), "the outline of a linked image in a hidden group"); + let [tl, tr, br, bl] = sides(hidden); + assert!(![tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn), "a hidden member"); + assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "a group with hidden members"); +} + /// A frame of the whole canvas keeps entries for the selected objects only. #[test] fn the_canvas_drops_entries_it_does_not_draw() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index e80d331bdb..af4281cbbb 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -802,6 +802,41 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); } +/// The overlay's limit counts the points of the members the highlight outlines: a hidden member of +/// a group, and the art of a hidden sublayer, do not count toward it. +#[test] +fn the_overlay_limit_leaves_out_hidden_members() { + use super::outline::{too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::{PathData, SubPath}; + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let many = Arc::new(Node::path(NodeId(2), PathData::single(SubPath::polyline(&points, false)), Appearance::default())); + let few = Arc::new(Node::path( + NodeId(3), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::default(), + )); + for visible in [true, false] { + let mut member = (*many).clone(); + member.visible = visible; + let group = Node::group(NodeId(1), vec![Arc::new(member), few.clone()]); + let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = visible; + if let Some(children) = sublayer.children_mut() { + children.push(many.clone()); + } + let mut layer = Node::layer(NodeId(4), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(sublayer), few.clone()]); + } + for (n, what) in [(&group, "a group"), (&layer, "a layer")] { + assert_eq!(too_many_anchors([n]), visible, "{what}, member visible: {visible}"); + assert_eq!(too_many_marks([n]), visible, "{what}, member visible: {visible}"); + } + } +} + /// View › Hide Edges hides the lines across a selected linked image along with its outline /// (#9080). #[test] @@ -13466,8 +13501,55 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { }; assert_eq!(node_outline(&group, &symbols).bounding_box(), want); } + // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + // A hidden path sent to the back of a trace is not its source image, in any view. + let mut path = + Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); + path.visible = false; + let art = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)), Appearance::default()); + let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); + for view in TraceView::ALL { + group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); + assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), "{view:?}"); + } +} + +/// A compound path draws every path it holds, hidden ones included, so its highlight outlines them +/// all; a group, a blend, an intertwine and a layer leave out a hidden member, and a layer the art +/// of a hidden sublayer. +#[test] +fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::FillRule; + let rect = |id: u64, r: vectorcraft_geom::Rect, visible: bool| { + let mut n = Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + n.visible = visible; + Arc::new(n) + }; + let children = || { + vec![rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), true), rect(3, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0), false)] + }; + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let contours = |n: &Node| node_outline(n, &symbols).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); + assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); + let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = false; + if let Some(c) = sublayer.children_mut() { + c.push(rect(5, vectorcraft_geom::Rect::new(150.0, 150.0, 200.0, 200.0), true)); + } + if let Some(c) = layer.children_mut() { + c.extend(children()); + c.push(Arc::new(sublayer)); + } + assert_eq!(contours(&layer), 1, "a layer"); } /// Hovering over point type shows only its baseline (not the transform bounding box), while diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d6006c9e7e..446f395823 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -662,6 +662,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. - **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group, layer, blend or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours 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. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From b232fd8e96e4b1f7423510f55a7f76102377649d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 18:48:21 -0800 Subject: [PATCH 20/63] Tests: hidden members in a repeat, a clip group, hover and other panes The tests now cover the repeat, whose hidden source members are not outlined, a clip group, whose clipping path stays outlined whether or not it is hidden, a hidden object that is itself selected, the hover highlight of a group with hidden members and another pane's outlines of one. The overlay limit test reports the group and the layer case separately. The comment on editing_children is back to main's text, and the progress line lists the repeat and the new tests. --- crates/doc/src/node/ops.rs | 3 +- crates/ui-egui/src/canvas/panes/tests.rs | 30 +++++++++++++++++++ .../src/canvas/selection_marks/tests.rs | 25 ++++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 28 ++++++++++++++--- docs/target-app-parity.md | 2 +- 5 files changed, 81 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 42bece8844..20dae6ec4b 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -361,8 +361,7 @@ impl Node { } /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. The canvas's selection - /// highlights also leave out hidden members, except a compound path's paths. + /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); let trace_source = self.extras().trace.is_some() diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index b0f68367cc..5d664096b0 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -968,6 +968,36 @@ fn other_panes_cross_a_selected_linked_image() { assert_eq!(linked, embedded + 2, "the outline of a linked image and its two crossing lines; an embedded image's outline alone"); } +/// Another pane outlines a selected group's visible members only: hiding a member draws the same +/// outlines as deleting it. +#[test] +fn other_panes_leave_out_a_selected_groups_hidden_members() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = egui::Context::default(); + let shown = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone(); + let hidden = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone(); + in_first(&mut app, "select.set", json!({"ids": [shown, hidden]})); + let group = in_first(&mut app, "object.group", json!({}))["id"].clone(); + let outlines = |app: &mut VectorcraftApp| { + in_first(app, "select.set", json!({"ids": [group]})); + frame(app, &ctx, vec![]); + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn).to_vec() + }; + let both = outlines(&mut app); + in_first(&mut app, "select.set", json!({"ids": [hidden]})); + in_first(&mut app, "edit.clear", json!({})); + let without = outlines(&mut app); + in_first(&mut app, "edit.undo", json!({})); + in_first(&mut app, "select.set", json!({"ids": [hidden]})); + in_first(&mut app, "object.hide", json!({})); + let with_hidden = outlines(&mut app); + assert_ne!(both, without, "the outlines show both members"); + assert_eq!(with_hidden, without, "a hidden member is not outlined"); +} + #[test] fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() { let mut app = app_with(2); diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index 32459a5825..408b7c8ec0 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -754,6 +754,31 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { let [tl, tr, br, bl] = sides(hidden); assert!(![tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn), "a hidden member"); assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "a group with hidden members"); + // The hover highlight of the group outlines its visible members only. + let (left_sides, right_sides, hidden_sides, image) = + (sides(left), sides(right), sides(hidden), doc.node(linked).unwrap().image_corners().unwrap()); + app.run("select.set", json!({"ids": []})).unwrap(); + app.hover_doc = Some(left_sides[0].midpoint(left_sides[2])); + let hovered = picture(&ctx, 1.0, |p| super::super::overlays::hover_highlight(&app, p, &view)); + let lit = |q: Point| { + let s = view.to_screen(q); + (-1..=1).any(|dy| { + (-1..=1).any(|dx| { + let (x, y) = ((s.x.round() as i64 + dx) as usize, (s.y.round() as i64 + dy) as usize); + hovered.pixels[y * hovered.size.0 + x][3] > 0.0 + }) + }) + }; + for [tl, tr, br, bl] in [left_sides, right_sides] { + assert!([tl.midpoint(tr), br.midpoint(bl)].into_iter().all(lit), "the hover highlight outlines a visible member"); + } + let [tl, tr, br, bl] = hidden_sides; + assert!(![tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(lit), "the hover highlight of a hidden member"); + let [tl, tr, br, bl] = image; + assert!( + ![tl.midpoint(tr), tr.midpoint(br), tl.lerp(br, 0.25), tr.lerp(bl, 0.25)].into_iter().any(lit), + "the hover highlight of a linked image in a hidden group" + ); } /// A frame of the whole canvas keeps entries for the selected objects only. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index af4281cbbb..3e7d629b75 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -817,6 +817,7 @@ fn the_overlay_limit_leaves_out_hidden_members() { vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default(), )); + let mut wrong = vec![]; for visible in [true, false] { let mut member = (*many).clone(); member.visible = visible; @@ -831,10 +832,12 @@ fn the_overlay_limit_leaves_out_hidden_members() { children.extend([Arc::new(sublayer), few.clone()]); } for (n, what) in [(&group, "a group"), (&layer, "a layer")] { - assert_eq!(too_many_anchors([n]), visible, "{what}, member visible: {visible}"); - assert_eq!(too_many_marks([n]), visible, "{what}, member visible: {visible}"); + if too_many_anchors([n]) != visible || too_many_marks([n]) != visible { + wrong.push(format!("{what}, member visible: {visible}")); + } } } + assert!(wrong.is_empty(), "the limit is crossed only by visible points: {wrong:?}"); } /// View › Hide Edges hides the lines across a selected linked image along with its outline @@ -13517,8 +13520,9 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { } /// A compound path draws every path it holds, hidden ones included, so its highlight outlines them -/// all; a group, a blend, an intertwine and a layer leave out a hidden member, and a layer the art -/// of a hidden sublayer. +/// all; a group, a blend, a repeat, an intertwine and a layer leave out a hidden member, and a +/// layer the art of a hidden sublayer. A clip group shows its clipping path whether or not it is +/// hidden, and a hidden object on its own keeps its outline. #[test] fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { use std::sync::Arc; @@ -13539,6 +13543,22 @@ fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + let repeat = |source: Vec>| contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(source, 0.0, 0.0)))); + let visible = children().into_iter().take(1).collect(); + assert_eq!(repeat(children()), repeat(visible), "a repeat"); + // A clip group shows its clipping path, hidden or not, and none of the art it clips. + let clip = |visible: bool| { + let mut members = children(); + members.insert(0, rect(6, vectorcraft_geom::Rect::new(10.0, 10.0, 90.0, 90.0), visible)); + let mut n = Node::group(NodeId(1), members); + if let NodeKind::Group { clip, .. } = &mut n.kind { + *clip = true; + } + contours(&n) + }; + assert_eq!((clip(true), clip(false)), (1, 1), "a clip group"); + // A hidden object that is itself selected keeps its outline. + assert_eq!(contours(&rect(7, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0), false)), 1, "a hidden object"); let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); sublayer.visible = false; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 446f395823..af0e9a73d6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -662,7 +662,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. - **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. -- **Selection: hidden members are not marked:** a selected group, layer, blend or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group, layer, blend, repeat or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours 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. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From 1612f363c5b565debd606dd392cffa9de97f85b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 19:21:52 -0800 Subject: [PATCH 21/63] Selection: the hidden-member rule sits next to editing_children The rule for which children a selection highlight outlines moves from the canvas into Node::drawn_children in vectorcraft-doc, next to Node::editing_children. Both now read the Image Trace source image through one private helper, and editing_children's doc comment says it gives the editing bounds and that highlights outline drawn_children. The highlight's behavior is unchanged. - the_overlay_limit_leaves_out_hidden_members also covers a blend, a repeat and an intertwine. - The repeat case of the compound-path test asserts its contour count. - a_selected_group_leaves_its_hidden_members_unmarked reports every failed check together, so the hover highlight checks run even when an earlier check fails. - The docs line now states which marks are tested for blends, repeats and intertwines, and that the rectangle drawn above the point limit and the Show Center mark still use the selection's bounds, which include a group's hidden members. --- crates/doc/src/node/ops.rs | 25 ++++++++++--- crates/ui-egui/src/canvas/outline.rs | 21 ++--------- .../src/canvas/selection_marks/tests.rs | 37 ++++++++++++------- crates/ui-egui/src/canvas/tests.rs | 15 +++++--- docs/target-app-parity.md | 2 +- 5 files changed, 57 insertions(+), 43 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..aaa45c0c6f 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -360,17 +360,32 @@ impl Node { self.geometric(Some(symbols)) } - /// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a - /// hidden bitmap for re-tracing/release; only source-image views measure that bitmap. + /// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for + /// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline + /// [`Node::drawn_children`]. pub fn editing_children(&self) -> &[Arc] { let children = self.children().map(Vec::as_slice).unwrap_or_default(); - let trace_source = self.extras().trace.is_some() - && !self.trace_view().shows_source() - && children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_))); + let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible); let skip = usize::from(self.extras().shaper.is_some() || trace_source); children.get(skip..).unwrap_or_default() } + /// The children a selection highlight outlines: [`Node::editing_children`] without the hidden + /// members, which the canvas does not draw. An Image Trace object's hidden source image stays + /// when the object's view shows it, and every path of a compound path stays, since the compound + /// path draws all of them. + pub fn drawn_children(&self) -> impl Iterator> { + let members = !matches!(self.kind, NodeKind::Compound { .. }); + let source = self.trace_source().filter(|_| self.trace_view().shows_source()); + self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) + } + + /// The first child of an Image Trace object when it is an image: the bitmap the trace keeps. + fn trace_source(&self) -> Option<&Arc> { + self.extras().trace.as_ref()?; + self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_))) + } + /// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols` /// is given. pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option { diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index fbb2241f3d..e96cf2abcc 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use super::{BezPath, Color32, Node, NodeKind, PathEl, Point, Pos2, Shape, Stroke, SymbolBoxes, VectorcraftApp, Xf, pos2}; pub(super) fn to_screen_path(bp: &BezPath, xf: &Xf) -> Vec> { @@ -165,7 +163,7 @@ fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> b if n.clips() { return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && drawn_children(n).any(|c| over(c, left, crosses)) + !matches!(n.kind, NodeKind::Envelope { .. }) && n.drawn_children().any(|c| over(c, left, crosses)) } let mut left = OVERLAY_MAX_ANCHORS; nodes.into_iter().any(|n| over(n, &mut left, crosses)) @@ -195,23 +193,10 @@ fn overlay_points(n: &Node) -> usize { } } -/// The children of `n` that [`walk_drawn`] visits: [`Node::editing_children`], without the hidden -/// members, which the canvas does not draw. An Image Trace object's hidden source image stays when -/// the object's view shows it. Every path of a compound path stays, since the compound path draws -/// all of them. -fn drawn_children(n: &Node) -> impl Iterator> { - let members = !matches!(n.kind, NodeKind::Compound { .. }); - let source = (n.extras().trace.is_some() && n.trace_view().shows_source()) - .then(|| n.children().and_then(|children| children.first())) - .flatten() - .filter(|c| matches!(c.kind, NodeKind::Image(_))); - n.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c))) -} - /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the /// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, /// its first child, not the art the path clips (#2422), and hidden members are left out -/// ([`drawn_children`]). +/// ([`Node::drawn_children`]). pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { @@ -223,7 +208,7 @@ pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { } return; } - for c in drawn_children(n) { + for c in n.drawn_children() { walk_drawn(c, f); } } diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index 408b7c8ec0..171a0a2df7 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -741,18 +741,25 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { let b = doc.node(id).unwrap().geometric_bounds().unwrap(); [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] }; + // Every check runs, and the failures are reported together. + let mut wrong = vec![]; for id in [left, right] { let [tl, tr, br, bl] = sides(id); - assert!([tl, tr, br, bl, tl.midpoint(tr), br.midpoint(bl)].into_iter().all(drawn), "a visible member is outlined and marked"); + if ![tl, tr, br, bl, tl.midpoint(tr), br.midpoint(bl)].into_iter().all(drawn) { + wrong.push("a visible member is not outlined and marked"); + } } let [tl, tr, br, bl] = doc.node(linked).unwrap().image_corners().unwrap(); - assert!( - ![tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].into_iter().any(drawn), - "the lines across a linked image in a hidden group" - ); - assert!(![tl.midpoint(tr), tr.midpoint(br)].into_iter().any(drawn), "the outline of a linked image in a hidden group"); + if [tl.lerp(br, 0.25), tl.lerp(br, 0.75), tr.lerp(bl, 0.25), tr.lerp(bl, 0.75)].into_iter().any(drawn) { + wrong.push("the lines across a linked image in a hidden group"); + } + if [tl.midpoint(tr), tr.midpoint(br)].into_iter().any(drawn) { + wrong.push("the outline of a linked image in a hidden group"); + } let [tl, tr, br, bl] = sides(hidden); - assert!(![tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn), "a hidden member"); + if [tl, tr, br, bl, tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(drawn) { + wrong.push("a hidden member"); + } assert_matches_plain(&ctx, &mut SelectionMarks::default(), &app, &view, 1.0, "a group with hidden members"); // The hover highlight of the group outlines its visible members only. let (left_sides, right_sides, hidden_sides, image) = @@ -770,15 +777,19 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { }) }; for [tl, tr, br, bl] in [left_sides, right_sides] { - assert!([tl.midpoint(tr), br.midpoint(bl)].into_iter().all(lit), "the hover highlight outlines a visible member"); + if ![tl.midpoint(tr), br.midpoint(bl)].into_iter().all(lit) { + wrong.push("the hover highlight does not outline a visible member"); + } } let [tl, tr, br, bl] = hidden_sides; - assert!(![tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(lit), "the hover highlight of a hidden member"); + if [tl.midpoint(tr), tr.midpoint(br), br.midpoint(bl), bl.midpoint(tl)].into_iter().any(lit) { + wrong.push("the hover highlight of a hidden member"); + } let [tl, tr, br, bl] = image; - assert!( - ![tl.midpoint(tr), tr.midpoint(br), tl.lerp(br, 0.25), tr.lerp(bl, 0.25)].into_iter().any(lit), - "the hover highlight of a linked image in a hidden group" - ); + if [tl.midpoint(tr), tr.midpoint(br), tl.lerp(br, 0.25), tr.lerp(bl, 0.25)].into_iter().any(lit) { + wrong.push("the hover highlight of a linked image in a hidden group"); + } + assert!(wrong.is_empty(), "drawn where it should not be, or missing: {wrong:?}"); } /// A frame of the whole canvas keeps entries for the selected objects only. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3e7d629b75..e4dd0af97c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -803,7 +803,8 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { } /// The overlay's limit counts the points of the members the highlight outlines: a hidden member of -/// a group, and the art of a hidden sublayer, do not count toward it. +/// a group, a blend, a repeat or an intertwine, and the art of a hidden sublayer, do not count +/// toward it. #[test] fn the_overlay_limit_leaves_out_hidden_members() { use super::outline::{too_many_anchors, too_many_marks}; @@ -821,7 +822,11 @@ fn the_overlay_limit_leaves_out_hidden_members() { for visible in [true, false] { let mut member = (*many).clone(); member.visible = visible; - let group = Node::group(NodeId(1), vec![Arc::new(member), few.clone()]); + let members = || vec![Arc::new(member.clone()), few.clone()]; + let group = Node::group(NodeId(1), members()); + let blend = Node::new(NodeId(6), NodeKind::Blend { children: members(), spec: Default::default() }); + let repeat = Node::new(NodeId(7), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(members(), 0.0, 0.0))); + let intertwine = Node::new(NodeId(8), NodeKind::Intertwine { children: members() }); let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); sublayer.visible = visible; if let Some(children) = sublayer.children_mut() { @@ -831,7 +836,7 @@ fn the_overlay_limit_leaves_out_hidden_members() { if let Some(children) = layer.children_mut() { children.extend([Arc::new(sublayer), few.clone()]); } - for (n, what) in [(&group, "a group"), (&layer, "a layer")] { + for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { if too_many_anchors([n]) != visible || too_many_marks([n]) != visible { wrong.push(format!("{what}, member visible: {visible}")); } @@ -13543,9 +13548,7 @@ fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); - let repeat = |source: Vec>| contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(source, 0.0, 0.0)))); - let visible = children().into_iter().take(1).collect(); - assert_eq!(repeat(children()), repeat(visible), "a repeat"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(children(), 0.0, 0.0)))), 1, "a repeat"); // A clip group shows its clipping path, hidden or not, and none of the art it clips. let clip = |visible: bool| { let mut members = children(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af0e9a73d6..43c7fc1cb9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -662,7 +662,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. - **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. -- **Selection: hidden members are not marked:** a selected group, layer, blend, repeat or intertwine draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes; the points of those members do not count toward the 100,000-point limit. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. +- **Selection: hidden members are not marked:** a selected group or layer draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes. A selected blend, repeat or intertwine draws no outline for its hidden members. The points of hidden members do not count toward the 100,000-point limit. The rectangle drawn above that limit and the Show Center mark still use the selection's bounds, which include a group's hidden members. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours 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. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. From 270f7cb654e8d6d9905506e5897f3f43f4654fd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 20:50:22 -0800 Subject: [PATCH 22/63] Docs: the key object's rectangle above the outline point limit The current pane draws a thicker rectangle around the key object instead of its outline when the key object alone has more than 100,000 outline points. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 43c7fc1cb9..685ab5dc4b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -661,7 +661,7 @@ since 2026-10-01. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. -- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. +- **Selection: linked images are crossed (#9080):** a selected linked image or placed document shows two lines in its layer's color from corner to corner of its frame, in the current pane and in other panes of the same document. A selected embedded image shows its outline alone. A selected or highlighted image of either kind is outlined along its frame, so a turned or distorted image's outline follows its corners instead of the box square to the page around it. The lines are part of the selection marks, so View › Hide Edges hides them and output does not draw them. When the selection has more than VectorCraft's own limit of 100,000 outline points (each linked image or placed document adds 4 for the ends of its lines), the current pane and other panes draw one rectangle around the selected objects instead of their outlines and lines; the current pane still draws the key object's thicker outline, or a thicker rectangle around the key object when it alone has more than 100,000 outline points. `a_selected_linked_image_is_crossed_and_an_embedded_one_is_not` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` covers a linked image, a placed document and an embedded image, each image also turned and distorted, the key object's outline, the hover highlight and a render of the document; `other_panes_cross_a_selected_linked_image` in `crates/ui-egui/src/canvas/panes/tests.rs` covers another pane; `hide_edges_hides_the_lines_across_a_linked_image` in `crates/ui-egui/src/canvas/tests.rs` covers View › Hide Edges. Scores and hours unchanged. - **Selection: hidden members are not marked:** a selected group or layer draws no outline, anchors or lines across a linked image for its hidden members or for the art of a hidden sublayer, and neither do the hover highlight and other panes. A selected blend, repeat or intertwine draws no outline for its hidden members. The points of hidden members do not count toward the 100,000-point limit. The rectangle drawn above that limit and the Show Center mark still use the selection's bounds, which include a group's hidden members. Every path of a compound path, and an Image Trace object's source image in the views that show it, are still outlined. `a_selected_group_leaves_its_hidden_members_unmarked` in `crates/ui-egui/src/canvas/selection_marks/tests.rs` (with the hover highlight); `other_panes_leave_out_a_selected_groups_hidden_members` in `crates/ui-egui/src/canvas/panes/tests.rs`; `a_compound_path_outlines_its_hidden_paths_and_a_group_does_not`, `the_overlay_limit_leaves_out_hidden_members` and `live_trace_selection_highlight_excludes_the_retained_source_rectangle` in `crates/ui-egui/src/canvas/tests.rs`. Scores and hours 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. From 3b0823e432f472ec186e49f2db356533e66cc148 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 21:05:59 -0800 Subject: [PATCH 23/63] Preferences: OK puts the reset task bar in the workspace it leaves OK now sets Enable Contextual Task Bar before the Touch switch only when that switch enters Touch, decided from the Enable Touch Workspace preference, the touch screen and the current workspace. A Touch return marker left from an earlier automatic switch no longer sends the value to Touch. A prefs.reset applied after the panels draw requests a repaint, so the next pass shows the reset rows. --- crates/ui-egui/src/app.rs | 6 ++++-- crates/ui-egui/src/prefs_dialog.rs | 13 ++++++++----- crates/ui-egui/src/prefs_dialog/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/workspaces.rs | 5 +++++ 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8142b558a8..663ce32b90 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -652,8 +652,10 @@ impl VectorcraftApp { // panel (Show on Shape Creation). panels::transform::show_on_shape_creation(self, &ctx); crate::toasts::show(self, &ctx); - // A `prefs.reset` run in this pass outside `Self::run`. - crate::prefs_dialog::apply_prefs_resets(self); + // A `prefs.reset` run in this pass outside `Self::run`; the next pass draws the reset rows. + if crate::prefs_dialog::apply_prefs_resets(self) { + ctx.request_repaint(); + } // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); if self.custom_titlebar { diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 70d7bc5d5f..0f777a9dca 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -225,10 +225,11 @@ pub fn confirm(app: &mut VectorcraftApp) -> Result { let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); let document_units = d.fields.get(RESET_UNITS).is_none_or(|v| values.get("unitsGeneral") != Some(v)); app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?; - // Outside an automatic Touch switch, the task bar is set before OK can enter the Touch - // workspace, so it goes to the workspace being left; during one, after OK leaves it. + // When OK enters the Touch workspace, the task bar is set before the switch, so it goes to the + // workspace being left; otherwise after it, so a return from Touch gives it to the workspace + // returned to. let task_bar = d.fields.get("__taskBar").and_then(Value::as_bool); - let before_switch = app.ui.touch_workspace_restore.is_none(); + let before_switch = touch_ws.is_some() && crate::workspaces::enters_touch(app, app.touch_screen); if before_switch && let Some(on) = task_bar { app.ui.task_bar = on; } @@ -517,10 +518,11 @@ fn default_ui_fields(ui: &crate::UiState) -> [(&'static str, bool); 3] { /// After `prefs.reset`, alone or as a batch step, of every category or of one: the UI-only rows /// ([`UI_FIELDS`]) and the Edit Original app of the categories it reset take their defaults too. -pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) { +/// Returns whether any reset was pending. +pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) -> bool { let resets = app.session.take_prefs_resets(); if resets.is_empty() { - return; + return false; } let in_reset = |category: &str| resets.iter().any(|r| r.is_none_or(|c| c == category)); for (key, value) in default_ui_fields(&app.ui) { @@ -536,6 +538,7 @@ pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) { if vectorcraft_engine::cmd::prefscmds::spec("editOriginalSystemDefaults").is_some_and(|s| in_reset(s.category)) { crate::original_editor::reset_saved(app); } + true } /// The height of the fields column under the category's name: the field list, the gap and the diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 0074301e7d..05720a2e26 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -620,6 +620,26 @@ fn ok_sets_the_task_bar_in_the_workspace_outside_touch() { assert!(touch.task_bar, "Touch keeps its own task bar"); } +/// A Touch return marker left over from an earlier automatic switch (Window › Workspace does not +/// clear it) does not change where OK puts the task bar: OK enters Touch from the workspace it +/// leaves, so that workspace takes the row and Touch keeps its own. +#[test] +fn ok_sets_the_task_bar_in_the_workspace_left_with_a_stale_touch_marker() { + let mut a = app(); + a.touch_screen = true; + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + a.ui.touch_workspace_restore = Some("Typography".into()); + crate::workspaces::switch(&mut a.ui, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + open(&mut a, Some("General")); + reset_preferences(&mut a); + confirm(&mut a).unwrap(); + assert_eq!(a.ui.workspace, crate::workspaces::TOUCH); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + let classic = a.ui.workspace_changes.iter().find(|w| w.name == "Essentials Classic").unwrap(); + assert!(!classic.task_bar, "the workspace left takes the reset value"); +} + /// A `prefs.reset` run straight on the session, outside `VectorcraftApp::run`, resets the UI-only /// rows by the end of the next frame. #[test] diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index a1c7464866..a974d13358 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -170,6 +170,11 @@ pub fn builtins() -> Vec { ] } +/// Whether [`sync_touch_workspace`] with `touch_screen` switches to the Touch workspace. +pub fn enters_touch(app: &VectorcraftApp, touch_screen: bool) -> bool { + app.session.prefs.touch_workspace && touch_screen && app.ui.workspace != TOUCH +} + /// Preferences › Devices › Enable Touch Workspace (#394): on, a touch screen switches to the Touch /// workspace; off, or when no touch screen is reported, the workspace before that switch is /// restored if Touch was entered automatically. Each switch keeps the layout it leaves and brings From 99c37518d2ed601f2d60f5256be6ccb14a2d145c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 21:33:22 -0800 Subject: [PATCH 24/63] Preferences: prefs.reset with Preferences open keeps the reset on OK A prefs.reset run while the Preferences dialog is open now puts the reset values in the dialog: the UI-only rows and the preferences of the categories it reset, and the preference groups when it resets every category. OK applies a reset still pending from outside the command path before it reads the dialog. OK then applies the reset values instead of the dialog's earlier ones, and leaves the open document's units alone. --- crates/ui-egui/src/prefs_dialog.rs | 22 +++++++++++++ crates/ui-egui/src/prefs_dialog/tests.rs | 42 ++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index 0f777a9dca..d3e0f9641d 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -220,6 +220,8 @@ pub(crate) fn note_set(d: &mut Dialog, field: &str, value: &Value) { /// OK: validate and apply every preference in the dialog (nothing changes on error). pub fn confirm(app: &mut VectorcraftApp) -> Result { + // A `prefs.reset` run since the last frame shows in the dialog before OK reads it. + apply_prefs_resets(app); let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); @@ -525,6 +527,7 @@ pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) -> bool { return false; } let in_reset = |category: &str| resets.iter().any(|r| r.is_none_or(|c| c == category)); + let prefs = app.session.prefs.to_json(); for (key, value) in default_ui_fields(&app.ui) { let reset = UI_FIELDS.iter().any(|&(k, c, _)| k == key && in_reset(c)); match key { @@ -533,6 +536,25 @@ pub(crate) fn apply_prefs_resets(app: &mut VectorcraftApp) -> bool { "__taskBar" if reset => app.ui.task_bar = value, _ => {} } + // An open Preferences dialog shows the reset rows, so OK keeps them. + if reset && let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == "preferences") { + d.fields.insert(key.into(), json!(value)); + } + } + // And the reset preferences, the groups with a reset of every category; Units › General then + // leaves the open document's units alone on OK. + use vectorcraft_engine::cmd::prefscmds::{PREF_GROUPS, spec}; + let every = resets.contains(&None); + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == "preferences") { + for (k, v) in prefs.as_object().into_iter().flatten() { + let reset = spec(k).map_or(every && PREF_GROUPS.contains(&k.as_str()), |s| in_reset(s.category)); + if d.fields.contains_key(k) && reset { + d.fields.insert(k.clone(), v.clone()); + if k == "unitsGeneral" { + d.fields.insert(RESET_UNITS.into(), v.clone()); + } + } + } } // The Edit Original row shows the app's Edit Original choice. if vectorcraft_engine::cmd::prefscmds::spec("editOriginalSystemDefaults").is_some_and(|s| in_reset(s.category)) { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 05720a2e26..d3838a574f 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -557,6 +557,48 @@ fn prefs_reset_resets_the_ui_only_rows_of_its_category() { assert_eq!(rows(&a), default, "every category"); } +/// A `prefs.reset` run while Preferences is open shows the reset values in the dialog, for the +/// categories it reset, so OK keeps the reset; rows of other categories keep the dialog's values. +#[test] +fn prefs_reset_while_preferences_is_open_shows_the_reset_values() { + let fresh = app(); + let rows = |a: &VectorcraftApp| (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar); + let default = rows(&fresh); + let mut a = app(); + (a.ui.view.smart_guides, a.ui.view.snap_to_grid, a.ui.task_bar) = (!default.0, !default.1, !default.2); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + open(&mut a, Some("General")); + a.run("prefs.reset", json!({"category": "General"})).unwrap(); + let d = a.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["__taskBar"], json!(default.2), "the dialog shows the reset row"); + assert_eq!(d.fields["__smartGuides"], json!(!default.0), "a row of another category keeps its value"); + confirm(&mut a).unwrap(); + assert_eq!(rows(&a), (!default.0, !default.1, default.2), "OK keeps the reset"); + assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment, "OK keeps the reset preference"); + + // Every category, the preference groups included. + let group = fresh.session.prefs.to_json()["pixelSnap"].clone(); + let mut changed = group.clone(); + let flag = changed.as_object_mut().and_then(|o| o.values_mut().find(|v| v.is_boolean())).expect("a pixelSnap option is a boolean"); + *flag = json!(!flag.as_bool().unwrap_or_default()); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + a.run("prefs.set", json!({"key": "pixelSnap", "value": changed})).unwrap(); + open(&mut a, Some("General")); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields["pixelSnap"], changed); + a.run("prefs.reset", json!({})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(rows(&a), default, "every category"); + assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment); + assert_eq!(a.session.prefs.to_json()["pixelSnap"], group, "OK keeps the reset group"); + + // Run straight on the session, with OK before the next frame. + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + open(&mut a, Some("General")); + a.session.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, fresh.session.prefs.keyboard_increment, "OK keeps a reset outside run"); +} + /// Reset Preferences and `prefs.reset` give Enable Contextual Task Bar the value the current /// workspace was saved with, which for a workspace saved with the bar off differs from the default. #[test] From 2dece75952cde7debc82c85b86556369483d018e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 05:24:02 -0800 Subject: [PATCH 25/63] Windows: a pen reads only the airbrush whose wheel it read first Once a pen has read an airbrush cursor's wheel, a recent packet of another tablet's airbrush no longer gives that pen its wheel. The pen reads the other cursor only after the readings start afresh. --- apps/vectorcraft/src/windows_wintab.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 81a3f8efb2..c49bcbea7f 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -270,6 +270,9 @@ struct Readings { /// The pointer id of the pen whose message first read the wheel since the readings started /// afresh; another pen's messages read none. pen: Option, + /// The cursor whose wheel that pen read; the pen reads no other cursor's wheel until the + /// readings start afresh. + cursor: Option, } impl Readings { @@ -317,6 +320,7 @@ impl Readings { self.list.clear(); self.eraser = None; self.pen = None; + self.cursor = None; } /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took @@ -331,7 +335,8 @@ impl Readings { /// readings, the one cursor read since they started afresh, however long ago its last packet /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, /// or the cursor has read only 0 since the readings started afresh, or another pen's message - /// read a wheel first since then. A turn to the other end starts them afresh first. + /// read a wheel first since then, or the pen read another cursor's wheel since then. A turn to + /// the other end starts them afresh first. fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { if self.pen.is_some_and(|p| p != pen) { return None; @@ -351,11 +356,12 @@ impl Readings { r } }; - if !r.moved { + if !r.moved || self.cursor.is_some_and(|c| c != r.cursor) { return None; } let wheel = r.axis?.wheel(r.raw)?; self.pen = Some(pen); + self.cursor = Some(r.cursor); Some(wheel) } } @@ -1106,6 +1112,21 @@ mod tests { assert_eq!(r.wheel_at(500, false), None, "a value past the range"); } + #[test] + fn a_pen_keeps_the_airbrush_whose_wheel_it_read() { + let mut r = Readings::default(); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1000, false), Some(0.25)); + // Another tablet's airbrush moves while the pen is held still. + r.packet(packet(2, 750), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), None, "the other cursor's wheel"); + r.packet(packet(1, 500), AXIS, 6000); + assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.forget(); + r.packet(packet(2, 750), AXIS, 7000); + assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); + } + #[test] fn zero_is_no_wheel_until_the_pen_reports_another_value() { let mut r = Readings::default(); @@ -1136,6 +1157,7 @@ mod tests { r.forget(); r.packet(packet(1, 300), AXIS, 150); assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + r.forget(); for c in 0..10 { r.packet(packet(c, 300), AXIS, 1000 * c); } From db7810888df07eddeb5431abfff420df495db0f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 15:28:38 -0800 Subject: [PATCH 26/63] Dialogs: four dialogs use framework components, and count fields show no unit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Paragraph Style Options Tabs buttons, the Script File Access list, Split Into Grid's fields and the 3D Bevel heading are framework components, as the rest of their dialogs are. - Paragraph Style Options › Tabs: Add, Delete Tab and Clear All Tabs are framework buttons in a row. - Script File Access: the list of picked files is a scrolled stack named "Picked files", up to 120 pt high before it scrolls. New test `tests::script_run::a_scripts_file_dialog_lists_several_picked_files_in_a_named_group`. - Split Into Grid: the fields are a framework grid of two columns, rows on the left and columns on the right; before, the egui grid inside the form drew the Columns fields over the Rows fields. New test `dialogs::tests_accessibility::split_into_grid_lays_out_its_fields_above_add_guides`. - 3D Bevel: the heading is a section named Bevel with Reset as its control. New test `dialogs::revolve::tests::the_bevel_heading_is_a_section_between_cap_and_bevel_shape`. Zig Zag's Ridges per segment, the bevel's Repeat and Revolve's Segments are counts and show no unit after the number, as production's did; before, Ridges showed a percent sign and Repeat and Segments showed px. Roughen's Detail no longer shows a percent sign either. Production showed "/in" after it, and craft-libs has no per-inch count unit for that yet, so it shows no unit. New tests `dialogs::effect::tests::zig_zag_ridges_and_roughen_detail_show_no_percent_sign` and `dialogs::revolve::tests::the_bevel_repeat_and_the_revolve_segments_show_no_unit`. --- crates/ui-egui/src/dialogs/effect.rs | 15 ++++++++ crates/ui-egui/src/dialogs/effect_rows.rs | 9 +++-- .../ui-egui/src/dialogs/para_style_options.rs | 15 ++++---- crates/ui-egui/src/dialogs/path_ops.rs | 24 +++++++------ crates/ui-egui/src/dialogs/revolve.rs | 34 +++++++++++-------- crates/ui-egui/src/dialogs/revolve/tests.rs | 33 ++++++++++++++++++ crates/ui-egui/src/dialogs/script_run.rs | 12 +++++-- .../src/dialogs/tests_accessibility.rs | 24 ++++++++++++- crates/ui-egui/src/tests/script_run.rs | 22 ++++++++++++ 9 files changed, 152 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index bcfecb47e1..ebb78e8c90 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -561,6 +561,21 @@ mod tests { assert_eq!((pa["detail"].as_f64(), pb["detail"].as_f64()), (Some(3.0), Some(8.0)), "each keeps its untouched value"); } + /// Zig Zag's Ridges per segment and Roughen's Detail are counts: their rows show no percent sign, while Size + /// with Relative, a share of the object's size, shows one. + #[test] + fn zig_zag_ridges_and_roughen_detail_show_no_percent_sign() { + use craft::ui::runtime::env::UnitKind; + let app = app(); + for (effect, key) in [("distort.zigZag", "ridges"), ("distort.roughen", "detail")] { + let cx = EffectCx::new(&app, effect, false); + let rows = super::super::effect_rows::distort(&cx, &DialogFields::new()); + let unit = |k: &str| rows.iter().find(|p| p.key == k).map(|p| p.unit); + assert_eq!(unit(key), Some(None), "{effect} {key}"); + assert_eq!(unit("size"), Some(Some(UnitKind::Percent)), "{effect} size"); + } + } + /// The lists the dialogs draw hold the values the effect's parameter documentation lists, in /// its order; Rasterize's Color Model names the document's mode first. #[test] diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index f4e27e317b..9d0a47f806 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -35,7 +35,12 @@ fn data_label(text: &str) -> Label { /// A whole-number slider row over `0..=100` percent. fn percent_range(key: &str, label: Label, default: f64) -> Param { - Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0).unit(UnitKind::Percent) + count_range(key, label, default).unit(UnitKind::Percent) +} + +/// A whole-number slider row over `0..=100` with no unit after the number. +fn count_range(key: &str, label: Label, default: f64) -> Param { + Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0) } /// The row of `key` for either unit of a Relative/Absolute pair: a share of the object's size, or a distance in the @@ -81,7 +86,7 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec { pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec { let roughen = cx.id == "distort.roughen"; // PLAN: production suffixes Detail with "/in"; `Param::unit` takes a `UnitKind` and none stands for it - let second = if roughen { percent_range("detail", lbl!("Detail:"), 10.0) } else { percent_range("ridges", lbl!("Ridges per segment:"), 4.0) }; + let second = if roughen { count_range("detail", lbl!("Detail:"), 10.0) } else { count_range("ridges", lbl!("Ridges per segment:"), 4.0) }; let points: Vec<(String, Label)> = choices(&cx.id, "points") .unwrap_or_default() .iter() diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 119228b39f..04e86b346d 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -15,7 +15,10 @@ use std::sync::Arc; +use craft::ui::buttons::Button; +use craft::ui::contract::{Props as _, Show as _, ShowContainer as _, clicked}; use craft::ui::dialog::DialogResult; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesTab, PropertyRow}; use craft::ui::runtime::env::Label; use serde_json::{Map, Value, json}; @@ -599,8 +602,6 @@ fn seed_editors(fields: &mut DialogFields) { } } -// PLAN: the stop list is a Select over the stops and the buttons are egui buttons: the List and button -// components' signatures are not in the bundle. /// The Add, Delete Tab and Clear All Tabs buttons, which also keep the editors and the stop they edit in step. fn tabs_buttons(unit: Unit) -> Param { Param::custom("tabs", tl!("Tabs"), move |ui, fields, _| { @@ -608,10 +609,10 @@ fn tabs_buttons(unit: Unit) -> Param { let (rows, _, _) = tab_rows(fields); let can_add = new_tab_position(&rows, unit).is_some(); let (mut add, mut delete, mut clear) = (false, false, false); - let line = ui.horizontal(|ui| { - add = ui.add_enabled(can_add, egui::Button::new(tl!("Add"))).clicked(); - delete = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Delete Tab"))).clicked(); - clear = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Clear All Tabs"))).clicked(); + let line = Row::new().show(ui, |ui, _| { + add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui)); + delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui)); + clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui)); }); if add { add_tab(fields, unit); @@ -621,7 +622,7 @@ fn tabs_buttons(unit: Unit) -> Param { clear_tabs(fields); } seed_editors(fields); - line.response + line.output }) .companions(["__tabSel", "__tabEdited", "__tabShown", "__tabAlign", "__tabPosition", "__tabLeader", "__tabAlignOn"]) } diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index a17ddcb027..091f5a4d34 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -5,9 +5,12 @@ // PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). -use craft::ui::contract::{Bind, FieldLabelRole, Show as _, ShowContainer as _, SideLabel}; +use craft::behavior::ColumnWidth; +use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::DialogId; use craft::ui::form::Field; +use craft::ui::layout::GridFit; +use craft::ui::layout_components::Grid; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; @@ -29,6 +32,10 @@ use crate::VectorcraftApp; /// sends 180° less the threshold: 150° sends `object.path.simplify`'s default of 30°. pub(crate) const ANGLE_THRESHOLD: f64 = 150.0; +/// Split Into Grid's two columns, each as wide as its fields: the rows on the left, the columns on the right. The +/// grid keeps both columns in a narrow dialog. +const AXES: [ColumnWidth; 2] = [ColumnWidth::Content; 2]; + /// Simplify's tolerance when the dialog opens from the menu, in points. const DEFAULT_TOLERANCE: f64 = 1.0; @@ -174,7 +181,7 @@ pub(crate) fn split_fields(width: f64, height: f64) -> DialogFields { fn cell(ui: &mut egui::Ui, label: &'static str, name: String, describes: bool, value: f64, lengths: Option) -> Option { let role = if describes { FieldLabelRole::Describes } else { FieldLabelRole::Names }; let mut edited = None; - Field::new(label).side(SideLabel::new().role(role)).show(ui, |ui, _| { + Field::new(label).side(SideLabel::new().role(role)).id_salt(name.as_str()).show(ui, |ui, _| { let bind = Bind::given(Some(value)); let out: NumberOutput = match lengths { Some(l) => NumberField::length(name.clone(), bind, l).show(ui), @@ -193,16 +200,16 @@ fn split_grid(ui: &mut egui::Ui, f: &mut DialogFields, lengths: LengthUnits) -> ("rows", tl!("Rows:"), tl!("Height:"), "rowGutter", "totalHeight", 2.0), ("columns", tl!("Columns:"), tl!("Width:"), "columnGutter", "totalWidth", 2.0), ]; - egui::Grid::new("split-grid") - .num_columns(2) - .show(ui, |ui| { + Grid::new(&AXES) + .fit(GridFit::Fixed) + .id_salt("split-grid") + .show(ui, |ui, _| { for (number, label, _, _, _, default) in axes { let n = f.number(number).unwrap_or(default); if let Some(v) = cell(ui, label, label.to_string(), false, n, None) { f.set(number, v); } } - ui.end_row(); for (number, _, label, gutter, total, default) in axes { let n = f.number(number).unwrap_or(default).max(1.0); let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0); @@ -211,23 +218,20 @@ fn split_grid(ui: &mut egui::Ui, f: &mut DialogFields, lengths: LengthUnits) -> f.set(total, n * v + gaps); } } - ui.end_row(); for (_, axis, _, gutter, _, _) in axes { let label = tl!("Gutter:"); if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) { f.set(gutter, v); } } - ui.end_row(); for (_, axis, _, _, total, _) in axes { let label = tl!("Total:"); if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) { f.set(total, v); } } - ui.end_row(); }) - .response + .output } /// Split Into Grid's rows: the grid and Add Guides. diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 3804c4ea3a..5ea09d09e4 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -9,7 +9,7 @@ use craft::behavior::{DisplayOrder, ItemSource, SelectionChange}; use craft::theme::Srgba; use craft::ui::buttons::Button; use craft::ui::contract::Entry; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, clicked}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamKind, ParamRows}; use craft::ui::pickers::Select; use craft::ui::runtime::env::LengthUnits; @@ -174,8 +174,13 @@ impl Rows<'_> { self.defaults.get(key).and_then(Value::as_f64).unwrap_or(0.0) } - fn range(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32, unit: UnitKind) -> Param { - Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).unit(unit).resettable() + fn range(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32, unit: UnitKind) -> Param { + self.plain(key, label, range, decimals).unit(unit) + } + + /// A slider over a number shown with no unit after it, such as a count. + fn plain(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32) -> Param { + Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).resettable() } fn degrees(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32) -> Param { @@ -272,7 +277,7 @@ fn object_rows(data: &Data, rows: &Rows, effect: &str, place: Place) -> Vec Param { let defaults = bevel_defaults(); let keys: Vec = defaults.keys().cloned().collect(); Param::custom("__bevelHeading", c3("Bevel"), move |ui, fields, _| { - ui.horizontal(|ui| { - ui.label(egui::RichText::new(c3("Bevel")).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if pressed(ui, tl!("Reset"), differs_from(fields, &defaults), None) { - defaults.iter().for_each(|(k, v)| set_value(fields, k, v)); - } - }); - }) - .response + let mut reset = false; + let changed = differs_from(fields, &defaults); + let shown = crate::panels::section(c3("Bevel")) + .id_salt("bevel") + .controls(|ui, _| reset = pressed(ui, tl!("Reset"), changed, None)) + .show(ui, |_, _| {}); + if reset { + defaults.iter().for_each(|(k, v)| set_value(fields, k, v)); + } + shown.output.response }) .companions(keys) .full_width() @@ -408,7 +414,7 @@ fn differs_from(fields: &DialogFields, defaults: &serde_json::Map /// Revolve's Rotation page: shape, view and the advanced settings. fn revolve_rows(rows: &Rows, effect: &str, place: Place) -> Vec { - let mut advanced = vec![rows.range("segments", tl!("Segments"), (8.0, 128.0), 0, UnitKind::Pixels)]; + let mut advanced = vec![rows.plain("segments", tl!("Segments"), (8.0, 128.0), 0)]; if place == Place::Dialog { advanced.push(rows.flag("__showAxis", tl!("Show axis"))); } diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index f11bc461bf..9510c3c30a 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -377,6 +377,39 @@ fn the_bevel_reset_restores_the_bevel_settings_and_keeps_the_others() { assert_eq!(doc(&h), before); } +/// The Bevel heading is a section named Bevel that holds its Reset, on its own line between Cap and Bevel Shape. +#[test] +fn the_bevel_heading_is_a_section_between_cap_and_bevel_shape() { + use craft::ui::contract::Role; + let mut h = drawn(SQUARE, EXTRUDE); + h.set("__page", json!("object")); + let (cap, reset, shape) = (h.target("Cap").rect, h.target("Reset").rect, h.target("Bevel Shape").rect); + let tree = h.fixture.tree(); + let section = h.fixture.by_role(Role::GROUP).into_iter().find(|t| tree.name_of(t.node) == Some("Bevel")).map(|t| t.rect); + assert!(section.is_some_and(|s| s.contains_rect(reset)), "a section named Bevel holds Reset: {section:?} {reset:?}"); + assert!(reset.top() >= cap.bottom(), "Reset is below Cap: {cap:?} {reset:?}"); + assert!(shape.top() >= reset.bottom(), "Bevel Shape is below Reset: {reset:?} {shape:?}"); + h.cancel(); +} + +/// The bevel's Repeat and Revolve's Segments are counts: their rows show no unit after the number, while Taper, a +/// share, shows its percent sign. +#[test] +fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() { + use craft::ui::patterns::form_dialogs::DialogFields; + use craft::ui::runtime::env::UnitKind; + let app = VectorcraftApp::new(Session::new(), crate::Services::default()); + let unit = |effect: &str, page: &str, key: &str| { + let data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new()); + let mut fields = DialogFields::new(); + fields.set("__page", FieldValue::Text(page.into())); + super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit) + }; + assert_eq!(unit(EXTRUDE, "object", "bevelRepeat"), Some(None)); + assert_eq!(unit(REVOLVE, "rotation", "segments"), Some(None)); + assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent))); +} + #[test] fn reset_all_keeps_map_art_and_its_options() { let mut h = drawn(SQUARE, CLASSIC_EXTRUDE); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..b43ea00331 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -32,11 +32,12 @@ use std::path::Path; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Outcome as _, Show as _}; +use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::{ DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, PromptChoice, StackDialog, StandardPrompt, dialog_id, }; use craft::ui::display::Text; +use craft::ui::layout_components::Stack; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use egui::Ui; @@ -65,6 +66,8 @@ pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a /// The note the file dialog shows when the person picked more files than a script is given. const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; +/// The height of the Script File Access prompt's list of picked files before it scrolls, in points. +const PICKED_LIST_HEIGHT: f32 = 120.0; /// The warning before a script runs. One type per question, so the host's per-type results never /// mix the three questions of this area. @@ -353,7 +356,12 @@ impl StackDialog for ScriptFiles { } let rows = |ui: &mut Ui| paths.iter().for_each(|path| drop(Text::new(shown_text(path, false)).show(ui))); if paths.len() > 1 { - egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, rows); + Stack::new() + .label(tl!("Picked files")) + .scroll(Scroll::vertical()) + .room_height(PICKED_LIST_HEIGHT) + .id_salt("script-picked") + .show(ui, |ui, _| rows(ui)); } else { rows(ui); } diff --git a/crates/ui-egui/src/dialogs/tests_accessibility.rs b/crates/ui-egui/src/dialogs/tests_accessibility.rs index 524c3ddcfc..0a060089d6 100644 --- a/crates/ui-egui/src/dialogs/tests_accessibility.rs +++ b/crates/ui-egui/src/dialogs/tests_accessibility.rs @@ -1,4 +1,5 @@ -//! The Split Into Grid dialog names its row and column fields with their axis, read from the access tree of the window. +//! The Split Into Grid dialog names its row and column fields with their axis and lays them out in two columns, read +//! from the access tree of the window. use egui::accesskit::Role; use serde_json::json; @@ -27,3 +28,24 @@ fn split_into_grid_names_row_and_column_fields_with_context() { assert!(names.contains(&name), "{name} among the text inputs: {names:?}"); } } + +/// Split Into Grid lays its fields out as a grid: the columns' fields stand right of the rows' fields on the same +/// lines, and Add Guides stands below the last of them. +#[test] +fn split_into_grid_lays_out_its_fields_above_add_guides() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 120, "height": 80})).unwrap(); + app.run("select.all", json!({})).unwrap(); + assert!(super::object_dialogs::open_from_menu(&mut app, "object.path.splitIntoGrid")); + settle(&mut app); + let out = frame(&mut app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let rect = |name: &str| { + let node = update.nodes.iter().map(|(_, node)| node).find(|node| node.label() == Some(name)); + node.and_then(|node| node.bounds()).unwrap_or_else(|| panic!("{name} has a rect")) + }; + let (rows, columns, guides) = (rect("Rows: Total:"), rect("Columns: Total:"), rect("Add Guides")); + assert!(columns.x0 > rows.x1, "the columns' fields stand right of the rows' fields: {rows:?} {columns:?}"); + assert!(columns.y0 < rows.y1 && rows.y0 < columns.y1, "the two Total fields share a line: {rows:?} {columns:?}"); + assert!(guides.y0 >= rows.y1.max(columns.y1), "Add Guides stands below the grid: {guides:?} {rows:?} {columns:?}"); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4022cb7c65..354c67a3d6 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -465,3 +465,25 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { cancel(&mut app, PICKER_KIND); finish(&mut app); } + +/// With two files picked, the file dialog lists them in a scrolled group named Picked files. +#[test] +fn a_scripts_file_dialog_lists_several_picked_files_in_a_named_group() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "File.openDialog('Pick', '', true);" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let given = vec!["/picked/a.txt".to_string(), "/picked/b.txt".to_string()]; + script_run::with_host(&app, |host, _| host.get_mut::().map(|d| d.add(given, true, false))).unwrap(); + frame(&app, vec![]); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let groups: Vec<_> = + update.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Group).filter_map(|(_, node)| node.label()).collect(); + assert!(groups.contains(&"Picked files"), "a group named Picked files: {groups:?}"); + cancel(&mut app, PICKER_KIND); + finish(&mut app); +} From b1d67df34d549e0e4bdc8a6aa5c13fd1a2b36953 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:33:19 -0800 Subject: [PATCH 27/63] Tests: the Picked files group test checks that both paths are inside the group The test for a script's file dialog with two picked files checked only that a group named Picked files exists. It now walks that group's accessibility children and checks that /picked/a.txt and /picked/b.txt are among them, so a group drawn without the paths fails the test. --- crates/ui-egui/src/tests/script_run.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 354c67a3d6..fbb2e60bb7 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -484,6 +484,23 @@ fn a_scripts_file_dialog_lists_several_picked_files_in_a_named_group() { let groups: Vec<_> = update.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Group).filter_map(|(_, node)| node.label()).collect(); assert!(groups.contains(&"Picked files"), "a group named Picked files: {groups:?}"); + let nodes: std::collections::HashMap<_, _> = update.nodes.iter().map(|(id, node)| (*id, node)).collect(); + let (_, group) = update + .nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::Group && node.label() == Some("Picked files")) + .expect("the Picked files group"); + let mut texts = Vec::new(); + let mut pending = group.children().to_vec(); + while let Some(id) = pending.pop() { + if let Some(node) = nodes.get(&id) { + texts.extend(node.label().into_iter().chain(node.value()).map(str::to_owned)); + pending.extend_from_slice(node.children()); + } + } + for path in ["/picked/a.txt", "/picked/b.txt"] { + assert!(texts.iter().any(|text| text == path), "{path} is inside the Picked files group: {texts:?}"); + } cancel(&mut app, PICKER_KIND); finish(&mut app); } From b1a52160af8ac33c75b49cabf77a44ff7cde547e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 01:49:15 -0800 Subject: [PATCH 28/63] Export for Screens: the Formats row's buttons end at the column's right edge and wrap when the column is narrow The Formats row (iOS, Android, Format Presets and Format Settings) was a content-sized row aligned SpaceBetween, so it had no room to spread: the buttons sat right after the label instead of at the column's right edge, and the row could not narrow. In the app's least window (800 x 500) the format grid stacks its cells in a 183 pt column, and the row ran 41 pt past it, putting the Format Settings button past the dialog's right edge. The row now fills the column, and its buttons wrap onto another line when the column is too narrow for them. Asset Export draws the same row. --- crates/ui-egui/src/dialogs/screen_formats.rs | 5 +- crates/ui-egui/src/dialogs/tests_screens.rs | 89 ++++++++++++++++++++ 2 files changed, 92 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index f01bc521ee..f85cdfe558 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -374,9 +374,10 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map, mut menu: Optio let one = rows.len() == 1; let first = settings_format(&rows); let shown = Stack::new().show(ui, |ui, _| { - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + // The buttons end at the right edge; a column too narrow for them puts them on more lines. + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(tl!("Formats:")).shade(Shade::Muted).show(ui); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { for (id, label) in PLATFORMS { if Button::new(tl!(label)).selected(preset == id).id_salt(id).show(ui).clicked() { platform = Some(id); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 544985b8d2..b52e3408ed 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -1429,3 +1429,92 @@ fn an_artboard_name_stays_with_its_document() { assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]); assert!(log.borrow().is_empty(), "renaming must not export"); } + +/// In a window of the default size and in one of the app's least size, every control of the dialog stays between its +/// sides, the format rows stay in the right column, and in the default window the Formats heading's buttons end at +/// the column's right edge. +#[test] +fn the_format_rows_fit_the_right_column_at_the_default_and_least_window_sizes() { + let rows = json!([ + {"scale": "1x", "suffix": "", "format": "png"}, + {"scale": "2x", "suffix": "@2x-long-suffix", "format": "jpg", "quality": 100}, + {"scale": "100w", "format": "pdf"}, + ]); + // The default window, then the least size the desktop app's window takes. + for (size, default) in [(egui::vec2(1280.0, 900.0), true), (egui::vec2(800.0, 500.0), false)] { + let (mut app, _) = app(2, false); + let ctx = app.ui_ctx.clone().expect("a test app has a window"); + ctx.enable_accesskit(); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let out = crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)); + super::host::pump(app, &ctx); + out + }; + frame(&mut app); + open(&mut app); + set(&mut app, "formats", rows.clone()); + frame(&mut app); + let out = frame(&mut app); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let rect = |n: &egui::accesskit::Node| { + n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + }; + let find = |label: &str, role: Role| { + nodes + .iter() + .find(|(_, n)| n.label() == Some(label) && n.role() == role) + .and_then(|(_, n)| rect(n)) + .unwrap_or_else(|| panic!("no {role:?} {label:?}")) + }; + let Some((dialog_id, dialog)) = nodes.iter().find(|(_, n)| n.role() == Role::Dialog) else { panic!("no dialog at {size:?}") }; + let dialog = rect(dialog).expect("the dialog's bounds"); + // The Export to: section spans the right column. + let column = find("Export to:", Role::Group); + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let mut under = vec![*dialog_id]; + while let Some(id) = under.pop() { + let Some(n) = by_id.get(&id) else { continue }; + under.extend(n.children().iter().copied()); + if let Some(r) = rect(n) { + assert!( + r.left() >= dialog.left() - 0.5 && r.right() <= dialog.right() + 0.5, + "{:?} {:?} at {r:?} is outside the dialog at {dialog:?} in a {size:?} window", + n.role(), + n.label() + ); + } + } + // Each control with how many of it the three rows show. + let format_rows = [ + ("Formats:", Role::Label, 1), + ("iOS", Role::Button, 1), + ("Android", Role::Button, 1), + ("Format Presets", Role::Button, 1), + ("Format Settings", Role::Button, 1), + ("Scale", Role::ComboBox, 3), + ("Suffix", Role::TextInput, 3), + ("Format", Role::ComboBox, 3), + ("Remove", Role::Button, 3), + ("+ Add Scale", Role::Button, 1), + ]; + for (label, role, count) in format_rows { + let shown: Vec<_> = nodes.iter().filter(|(_, n)| n.label() == Some(label) && n.role() == role).collect(); + assert_eq!(shown.len(), count, "{role:?} {label:?} in a {size:?} window"); + for (_, n) in shown { + let r = rect(n).expect("bounds"); + assert!( + r.left() >= column.left() - 0.5 && r.right() <= column.right() + 0.5, + "{label} at {r:?} is outside the column at {column:?} in a {size:?} window" + ); + } + } + if default { + let gear = find("Format Settings", Role::Button); + assert!((gear.right() - column.right()).abs() <= 0.5, "the gear at {gear:?} ends at the column's edge {column:?}"); + } + } +} From fe1b80e0aa29b79e3372193854e83189cdbdd47c Mon Sep 17 00:00:00 2001 From: Ruchir <113586074+ruchirguitar@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:31:35 +0530 Subject: [PATCH 29/63] Add a context menu on OpenType feature rows. A right-click turns one feature on or off, or resets them, through the same undo step as the checkbox and the panel menu. Co-authored-by: Cursor Co-authored-by: Codex --- crates/ui-egui/src/panels/opentype.rs | 110 +++++++++++++++++++++++++- docs/gaps.md | 14 +++- 2 files changed, 122 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 4262179b3e..0034f47231 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -286,11 +286,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } Divider::horizontal().show(ui); // A row whose characters differ shows a dash, and a click turns the feature on for all of them. + // A secondary click keeps the text selection and opens that row's menu. for (label, flag) in rows() { - let out = Checkbox::new(Bind::given(mixed(shown_flag(app, flag)))).label(label).show(ui); + let shown = shown_flag(app, flag); + let out = Checkbox::new(Bind::given(mixed(shown))).label(label).show(ui); if let Some(on) = out.events.committed() { change = Some(Change::Toggle(flag, *on)); } + Menu::context(label, &out.response).show(ui, |ui, _| feature_row_menu(app, ui, flag, shown)); } let sets = set_entries(app, &st); let opener = Button::new(tl!("Stylistic Sets")).enabled(!sets.is_empty()).show(ui); @@ -309,6 +312,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The menu a secondary click on one feature row opens. Turn Off when the row is on +/// (`shown` is `Some(true)`); Turn On when it is off or mixed, through the same toggle a click +/// uses, so a mixed row turns the feature on for every character the panel acts on. Reset +/// OpenType Features applies the panel menu's default and is enabled on the same condition. +fn feature_row_menu(app: &mut VectorcraftApp, ui: &mut Ui, flag: Flag, shown: Option) { + let on = shown == Some(true); + if MenuItem::new(if on { tl!("Turn Off") } else { tl!("Turn On") }).show(ui).ran { + edit(app, Change::Toggle(flag, !on)); + } + if MenuItem::new(tl!("Reset OpenType Features")).enabled(text_style(app).is_some()).show(ui).ran { + set(app, OtFeatures::default()); + } +} + /// Whether tracking turns off the standard ligatures of any character the panel acts on: one with /// Standard Ligatures on, tracked past [`vectorcraft_text::ligatures_suppressed_by`]'s limit and /// without an explicit `liga` or `clig` tag ([`vectorcraft_text::explicit_ligatures`]). @@ -485,6 +502,7 @@ mod tests { use vectorcraft_doc::NodeId; use super::*; + use crate::tests::panel_harness::Panel; fn selected_text() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -1146,4 +1164,94 @@ mod tests { } } } + + fn row_flag(label: &str) -> Flag { + rows().into_iter().find(|(l, _)| *l == label).unwrap().1 + } + + #[test] + fn right_clicking_an_opentype_row_offers_turn_on_or_turn_off() { + let mut panel = Panel::new(selected_text(), show); + let ids = panel.app().session.active().unwrap().selection.objects.clone(); + let before = features(&panel.app()).to_tags(); + let undo = undo_steps(&panel.app()); + panel.secondary_click("Standard Ligatures"); + assert!(panel.menu_item_enabled("Turn Off")); + assert!(!panel.shows("Turn On")); + assert!(panel.menu_item_enabled("Reset OpenType Features")); + assert_eq!(panel.app().session.active().unwrap().selection.objects, ids); + assert_eq!(features(&panel.app()).to_tags(), before); + assert_eq!(undo_steps(&panel.app()), undo); + panel.click_menu_item("Turn Off"); + panel.secondary_click("Standard Ligatures"); + assert!(panel.menu_item_enabled("Turn On")); + assert!(!panel.shows("Turn Off")); + assert_eq!(panel.app().session.active().unwrap().selection.objects, ids); + } + + #[test] + fn clicking_turn_on_sets_that_feature_in_one_undo_step() { + let off = OtFeatures { ligatures: false, swash: true, ..OtFeatures::default() }; + let mut app = selected_text(); + set(&mut app, off); + let mut by_check = Panel::new(app, show); + by_check.click("Standard Ligatures"); + let mut app = selected_text(); + set(&mut app, off); + let before = features(&app).to_tags(); + let undo = undo_steps(&app); + let mut panel = Panel::new(app, show); + panel.secondary_click("Standard Ligatures"); + panel.click_menu_item("Turn On"); + assert_eq!(undo_steps(&panel.app()), undo + 1); + assert_eq!(features(&panel.app()).to_tags(), features(&by_check.app()).to_tags()); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(features(&panel.app()).to_tags(), before); + } + + #[test] + fn turn_on_preserves_the_mixed_character_range_and_undo_restores_its_runs() { + let mut app = selected_text(); + app.session.select_tool("type", Default::default()).unwrap(); + let id = app.run("text.create", json!({"x": 0, "y": 20, "text": "abcd"})).unwrap()["id"].clone(); + app.run("text.setRangeStyle", json!({"id": id, "start": 1, "end": 2, "features": ["frac"]})).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 1, "end": 3})); + let range = Some((NodeId(id.as_u64().unwrap()), 1, 3)); + assert_eq!(text_editing(&app), range); + assert_eq!(shown_flag(&app, row_flag("Fractions")), None); + let before = run_features(&mut app, &id, 4); + let undo = undo_steps(&app); + let mut panel = Panel::new(app, show); + panel.secondary_click("Fractions"); + assert_eq!(text_editing(&panel.app()), range); + assert_eq!(run_features(&mut panel.app(), &id, 4), before); + panel.click_menu_item("Turn On"); + assert_eq!(run_features(&mut panel.app(), &id, 4), [("a".into(), Value::Null), ("bc".into(), json!(["frac"])), ("d".into(), Value::Null)]); + assert_eq!(undo_steps(&panel.app()), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(run_features(&mut panel.app(), &id, 4), before); + } + + #[test] + fn clicking_reset_opentype_features_clears_the_rows() { + let custom = OtFeatures { ligatures: false, fractions: true, swash: true, ..OtFeatures::default() }; + let mut by_flyout = selected_text(); + set(&mut by_flyout, custom); + run(&mut by_flyout, RESET, &json!({})).unwrap().unwrap(); + let mut app = selected_text(); + set(&mut app, custom); + let before = features(&app).to_tags(); + let undo = undo_steps(&app); + let mut panel = Panel::new(app, show); + panel.secondary_click("Fractions"); + panel.click_menu_item("Reset OpenType Features"); + assert_eq!(undo_steps(&panel.app()), undo + 1); + assert_eq!(features(&panel.app()).to_tags(), features(&by_flyout).to_tags()); + assert_eq!(shown_flag(&panel.app(), row_flag("Standard Ligatures")), Some(true)); + assert_eq!(shown_flag(&panel.app(), row_flag("Fractions")), Some(false)); + assert_eq!(shown_flag(&panel.app(), row_flag("Swash")), Some(false)); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(features(&panel.app()).to_tags(), before); + } } diff --git a/docs/gaps.md b/docs/gaps.md index b502f9e146..7a85df271c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-21 · **Change:** minor (G12: Glyphs cells have an item context menu (Insert Glyph in the font grid, Apply in Alternates for Current Selection); scores and estimates unchanged; previously: G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -12,6 +12,10 @@ ## Feature submission evidence +Glyphs cell context menus (part of G12): a secondary click on a font-grid cell offers Insert Glyph, which does what a double-click on that cell does (insert an encoded character, or apply an unencoded glyph the selection can take), in one undo step. A secondary click in Alternates for Current Selection offers Apply, which applies that cell's feature or glyph choice the way a double-click does, in one undo step, and does not offer Insert Glyph. When a double-click would only report why the glyph cannot be applied, the item is disabled and the text is unchanged. Evidence: `panels::glyphs::tests::right_clicking_a_glyph_cell_offers_insert_glyph`, `panels::glyphs::tests::right_clicking_an_alternate_cell_offers_apply`, and `panels::glyphs::tests::a_glyph_that_cannot_be_applied_disables_the_menu_item` in `crates/ui-egui/src/panels/glyphs.rs`. Scores and estimates unchanged. + +OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. + Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. @@ -60,6 +64,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-21 | minor | G12: Glyphs cells have an item context menu: Insert Glyph in the font grid and Apply in Alternates for Current Selection, each doing that cell's double-click in one undo step; a glyph that cannot be applied disables the item. Headless regressions: panels::glyphs::tests. Scores and estimates unchanged. | +| 2026-11-21 | minor | G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); a secondary click keeps the text selection, a mixed row turns the feature on, and each choice is one undo step. Headless regressions: panels::opentype::tests. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); headless tests in crates/ui-egui/src/panels/properties/tests.rs; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | @@ -526,6 +532,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Implemented and tested (2026-11-21):** Glyphs cells have an item context menu. A secondary click on a font-grid cell offers Insert Glyph, which inserts an encoded character or applies an unencoded glyph the selection can take, the same as a double-click on that cell, in one undo step. A secondary click in Alternates for Current Selection offers Apply, which applies that cell's feature or glyph choice the way a double-click does, in one undo step, and does not offer Insert Glyph. When a double-click would only report why the glyph cannot be applied, the item is disabled and the text is unchanged. A double-click and the panel menu are unchanged. Headless regression coverage: `panels::glyphs::tests::right_clicking_a_glyph_cell_offers_insert_glyph`, `panels::glyphs::tests::right_clicking_an_alternate_cell_offers_apply`, and `panels::glyphs::tests::a_glyph_that_cannot_be_applied_disables_the_menu_item` in `crates/ui-egui/src/panels/glyphs.rs`. Scores and estimates unchanged. + +- **Implemented and tested (2026-11-21):** OpenType panel feature rows have an item context menu. A secondary click keeps the text selection and offers Turn Off when the feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step; a checkbox click stays a toggle. The Stylistic Sets button and the East Asian menu items are unchanged. Headless regression coverage: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. + - **Implemented (2026-11-20):** Asset Export tiles have item context menus: Export and Remove act on the asset selection (plural labels for multiple assets), Rename opens the clicked tile's inline field, Select Artwork on Canvas selects that tile's source nodes, and Add Selected Artwork as One Asset / Multiple Assets are enabled with canvas selection. A right-click selects an unselected tile, clearing the previous asset selection, and preserves a multi-selection when the tile is already selected. Export reuses the raster/3D export path; Remove is one undo step and keeps the artwork. Headless regression coverage: `crates/ui-egui/src/panels/tests_asset_export.rs`. Other G12 panel gaps remain; scores and estimates unchanged. - **Implemented and tested (2026-11-20):** Appearance panel row context menus: right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Headless regression coverage: `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged. @@ -988,6 +998,8 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-21 | minor | G12: Glyphs cells have an item context menu: Insert Glyph in the font grid and Apply in Alternates for Current Selection, each doing that cell's double-click in one undo step; a glyph that cannot be applied disables the item. Headless regressions: panels::glyphs::tests. Scores and estimates unchanged. | +| 2026-11-21 | minor | G12: OpenType panel feature rows have an item context menu (Turn On / Turn Off, Reset OpenType Features); a secondary click keeps the text selection, a mixed row turns the feature on, and each choice is one undo step. Headless regressions: panels::opentype::tests. Scores and estimates unchanged. | | 2026-11-20 | minor | G3: shadows from the first light and graphics on 3D surfaces moved from Missing to Done, as three-d.md documents them, and angular cut caps dropped from Missing, as Revolve's Cap closes a partial sweep's cut sides ([revolve.md](revolve.md)) (#8312); estimate unchanged | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel: right-click item context menus for rows (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | From 97561c8091fdfa74069fa1927de98c6c5d5aa100 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 25 Nov 2026 08:43:27 +0530 Subject: [PATCH 30/63] Document OpenType row menu parity evidence --- docs/target-app-parity.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c16b4c9567..6b4017b9ff 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1803,6 +1803,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). + Right-clicking an OpenType feature row preserves the text selection. The row offers **Turn Off** when every affected character has the feature on, and **Turn On** when the feature is off or mixed. On a mixed Type-tool selection, **Turn On** enables the feature across the selected range and leaves characters outside it untouched. **Reset OpenType Features** restores the same defaults as the panel menu. Each action takes one undo step. Focused tests in `panels::opentype::tests` include `right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `clicking_turn_on_sets_that_feature_in_one_undo_step`, `turn_on_preserves_the_mixed_character_range_and_undo_restores_its_runs`, and `clicking_reset_opentype_features_clears_the_rows`. The OpenType panel menu has a Stylistic Sets submenu after Reset OpenType Features, with the same sets, labels and checks as the panel's Stylistic Sets button; a set chosen there turns on or off for the characters the panel acts on in one undo step, keeping their other features, and the submenu is disabled with no text selected or when the font offers no sets. The 2019 user guide ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) has stylistic sets chosen from the OpenType panel menu. The submenu's place in the menu is VectorCraft's own. Tests: `panels::opentype::tests::the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off`. With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. With Show East Asian Options on, the OpenType panel menu also has Proportional Metrics, before H or V Style; [the help page](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) lists it among the OpenType panel options that this setting shows. It sets the `proportionalMetrics` character attribute that the Character panel menu's item sets (`palt` in horizontal type, `vpal` in vertical type), through `text.setFormat` for selected type and `text.setRangeStyle` while the Type tool edits text. It is checked when every character it changes has the attribute (at a Type tool caret, every character of the text), and choosing it turns the attribute on for all of them, or off when it is checked, in one undo step, keeping their other attributes; with no type selected it is disabled. Its place in the menu and the check rule are VectorCraft's own. Tests: `panels::opentype::tests::proportional_metrics_turns_on_and_off_for_a_mixed_range`, `panels::opentype::tests::proportional_metrics_reaches_a_selected_object_and_the_text_at_a_caret`. From 575f12bffac0140ded13dd6b59ca15cefd20aa43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:32:47 -0800 Subject: [PATCH 31/63] Panels: a panel is never resized narrower than the 220 pt panel minimum The dock's panel specs set no size limits, so a floating panel's side could be dragged in to any width and a docked column saved narrower than PANEL_MIN_WIDTH was drawn at that width, cutting the panel's rows. Every panel other than the canvas and the toolbars now gives PANEL_MIN_WIDTH as its least body width, as the app did before the move to the craft UI framework. A float placed narrower by window.panel.float or by a saved workspace is still drawn at the width it was given: the framework's floating window places that rect without its limits. --- crates/ui-egui/src/panel_docking.rs | 5 +-- crates/ui-egui/src/panel_docking/tests.rs | 41 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index c9d8c8dd7c..439ebe5503 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use craft::behavior::{Axis, DockSide, IconId}; use craft::ui::buttons::IconButton; -use craft::ui::contract::{Bind, BodyCx, PlainData, Show as _, Tracked}; +use craft::ui::contract::{Bind, BodyCx, PlainData, Show as _, SizeLimits, Tracked}; use craft::ui::docking::{ ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels, PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions, @@ -1192,9 +1192,10 @@ impl PanelSpecs for Specs { if panel == CANVAS { return spec.canvas(); } + // A toolbar's column is as wide as its grid's steps; every other panel is at least PANEL_MIN_WIDTH wide. let spec = match self.grids.iter().find(|(rail, _)| rail == panel) { Some((_, grid)) => spec.grid(*grid), - None => spec, + None => spec.limits(SizeLimits::at_least(egui::vec2(PANEL_MIN_WIDTH, 0.0))), }; let icon = crate::state::rail_panel(panel).map(|p| p.2).or_else(|| crate::panels::library_panel::parse(panel).map(|_| "library")); match icon { diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index b3eb083b42..6e79c603ea 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -970,3 +970,44 @@ fn cycle_options_rejects_panels_without_sizes() { } assert_eq!(h.layout(), before, "a refusal changes nothing"); } + +/// The width of the body of the panel titled `title` as the last frame drew it. +fn body_width(h: &Harness, title: &str) -> f32 { + h.nodes + .iter() + .find(|(_, node)| node.role() == egui::accesskit::Role::TabPanel && node.label() == Some(title)) + .and_then(|(_, node)| node.bounds()) + .map(|b| (b.x1 - b.x0) as f32) + .unwrap_or_else(|| panic!("{title}'s body is drawn")) +} + +/// A floating panel's side dragged in past `PANEL_MIN_WIDTH` stops at the minimum. +#[test] +fn a_floating_panel_resized_past_the_panel_minimum_stops_at_it() { + let mut h = Harness::new(); + h.app.run("window.panel.float", json!({"panel": "stroke", "x": 300, "y": 200, "width": 400, "height": 300})).unwrap(); + h.frames(3); + let before = body_width(&h, "Stroke"); + assert!((before - 400.0).abs() < 1.0, "a float wider than the minimum keeps its width: {before}"); + let rect = floating_window(&h.layout(), "stroke").expect("Stroke floats").rect; + // The window's right side is its resize grip; the drag goes 300 pt in, well past the minimum. + let grip = pos2(rect.right() - 1.0, rect.center().y); + h.drag(grip, grip - vec2(300.0, 0.0)); + let after = body_width(&h, "Stroke"); + assert!(after < before - 1.0, "the drag narrowed the window: {before} to {after}"); + assert!(after >= PANEL_MIN_WIDTH - 0.5, "dragged in past the minimum: {after}"); +} + +/// A docked column saved narrower than `PANEL_MIN_WIDTH` is drawn at the minimum. +#[test] +fn a_docked_column_is_never_narrower_than_the_panel_minimum() { + let mut h = Harness::new(); + let mut layout = h.layout(); + let columns = end_dock_mut(&mut layout).expect("the default layout has an end dock"); + for column in columns.iter_mut().filter(|column| !column.iconic) { + column.width = Some(100.0); + } + h.set_layout(layout); + h.frames(3); + assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties")); +} From 387b912010e5844e02fcb2fa0e143dc2f8656d70 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:34:06 -0800 Subject: [PATCH 32/63] Type: closing the last document releases the hidden-character and spelling marks On the Home screen and in the empty window, the canvas returned before the marks were gathered, so the hidden-character and spelling memos and the list of text objects kept the closed document's nodes until another document was shown. The canvas now releases them on any frame with no active document. --- crates/ui-egui/src/canvas.rs | 4 ++++ crates/ui-egui/src/canvas/marks.rs | 11 +++++++--- crates/ui-egui/src/canvas/marks/tests.rs | 27 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 596cb119f0..ddc7293fb8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -108,6 +108,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) { app.ui.home = None; } + // The Home screen and the empty window show no marks: a closed document's text nodes are not kept. + if app.session.active().is_none() { + marks::release_text_marks(app); + } let full = ui.available_rect_before_wrap(); if crate::menus::home_showing(app) { // No type editor shows to lose the keys: the marked text stays as typed. diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index ca21ef7119..abe7c5a6db 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -160,6 +160,13 @@ pub(crate) struct Marks { artboard_marks: Vec, } +/// Drops the hidden-character and spelling memos and the text nodes they hold. +pub(crate) fn release_text_marks(app: &mut VectorcraftApp) { + app.canvas.hidden_chars.marks.clear(); + app.canvas.spelling = SpellingMarks::default(); + app.canvas.text_nodes = TextNodes::default(); +} + /// The marks of one canvas pass over `view`. The memos of [`crate::CanvasCache`] are kept while their /// gate is on and dropped, with the text nodes they hold, when it is off. pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { @@ -183,9 +190,7 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { let fades = artboards::fades_outside_artboards(app); let shows_artboards = artboards::shows_artboards(app); let Some(st) = app.session.active() else { - app.canvas.hidden_chars.marks.clear(); - app.canvas.spelling = SpellingMarks::default(); - app.canvas.text_nodes = TextNodes::default(); + release_text_marks(app); return m; }; let key = (st.uid, st.revision); diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 2bb6ecda50..52fc5d67dd 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -122,6 +122,33 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() { assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept"); } +/// Closing the last document drops the memos' text nodes on the canvas's next frame, whether it +/// shows the Home screen or, with Show The Home Screen When No Documents Are Open off, an empty window. +#[test] +fn a_canvas_frame_without_a_document_releases_the_text_nodes() { + let frame = |app: &mut VectorcraftApp| { + let ctx = crate::testing::ui_context(); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::canvas::show(app, ui)); + out.textures_delta.clear(); + }; + for home in [true, false] { + let mut app = app(); + app.session.execute("prefs.set", &json!({"key": "showHomeScreen", "value": home})).unwrap(); + text(&mut app, 20, 60, "one\ttwo qzxv\nthree"); + app.ui.view.hidden_chars = true; + app.ui.view.auto_spell_check = true; + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_some() && !app.canvas.hidden_chars.marks.is_empty(), "home {home}: the canvas keeps the memos"); + app.session.execute("file.close", &json!({})).unwrap(); + assert_eq!(crate::menus::home_showing(&app), home); + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_none(), "home {home}: no list of the closed document's text objects is kept"); + assert!(app.canvas.hidden_chars.marks.is_empty(), "home {home}: no hidden-character marks of the closed document are kept"); + assert!(app.canvas.spelling.lines.is_empty(), "home {home}: no spelling marks of the closed document are kept"); + } +} + /// `paths` small rectangles and three point type objects with hidden characters and words no /// dictionary knows: the first on the first layer, the second in a group on that layer and the /// third on a second layer. Show Hidden Characters and Auto Spell Check are on. Returns the type From c88ae56bcf22ea1e0d43e21d6ab5936d2d4e8390 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:24:25 -0800 Subject: [PATCH 33/63] Flattener Preview: a click zooms in and an Alt-click zooms out again Since the move to the craft UI framework (#8800), a click on the preview only recentered it and an Alt-click (Option on macOS) did the same, so the only zoom left was Ctrl or Cmd with the wheel. A click now zooms in 2x about the point clicked and an Alt-click zooms out 2x, keeping that point under the pointer, within the preview's zoom range (the fit up to 8x). Zooming out to the fit returns to the fitting view. The pane's tooltip names the gestures again, and a zoom row under the preview zooms from the keyboard. --- .../ui-egui/src/panels/flattener_preview.rs | 102 +++++++++++++++++- 1 file changed, 97 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index e3baa39a27..da00eb4c48 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -1,8 +1,9 @@ //! Window → Flattener Preview: what flattening the document would touch (`flattener.preview`), //! highlighted in red over a grey preview of the art. Refresh takes a new snapshot of the //! document; Highlight picks what shows; Overprints, the preset and the options (Show Options in -//! the panel menu) set how it flattens. The preview is a `PreviewPane`: the wheel and the pane's -//! gestures zoom and pan, and a double click fits. +//! the panel menu) set how it flattens. The preview is a `PreviewPane`: a click zooms in about the +//! point clicked and an Alt-click (Option on macOS) zooms out, a drag pans, Ctrl or Cmd with the +//! wheel zooms, and a double click fits. The zoom row under it zooms from the keyboard. //! //! The settings live in `UiState::flattener_preview` (`ui.inspect`); `ui.flattenerPreview` sets //! them and refreshes. The snapshot, the view and the texture live in [`FlattenerPreviewModel`] @@ -10,12 +11,13 @@ use std::sync::Arc; +use craft::behavior::CanvasTransform; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; -use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView}; +use craft::ui::patterns::form_dialogs::{DialogFields, ParamRows, PreviewPane, PreviewView, PreviewZoom}; use craft::ui::pickers::Select; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; use craft::ui::runtime::env::Env; @@ -258,6 +260,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// The preview: the whole snapshot rendered once per [`Key`], grey under a highlight with the /// highlighted art in the theme's error colour, in a pane that zooms and pans it. +/// A click zooms in 2× about the point clicked and an Alt-click zooms out 2×, within [`fitting_view`]'s range. fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, h: Highlight, overprints: Overprints) { let FlattenerPreviewModel { shot, renderer, view, drawn, .. } = &mut app.flattener_preview; let Some(shot) = shot.as_ref() else { return }; @@ -282,12 +285,46 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, // At scale 1 the picture is the fit of the well (width `w`, height `w / ASPECT`), so the zoom reads relative to the fit. let s = (f64::from(w) / shot.fit.width()).min(f64::from(w / ASPECT) / shot.fit.height()); let size = vec2((shot.fit.width() * s) as f32, (shot.fit.height() * s) as f32); - let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view).aspect(ASPECT).show(ui); - if let Some(v) = out.view { + let out = PreviewPane::new(tl!("Flattener Preview"), SizedTexture::new(tx.id(), size), view) + .aspect(ASPECT) + .click_centres(false) + .tooltip(tl!("Click to zoom in, Alt-click to zoom out, drag to pan, double-click to fit")) + .show(ui); + *view = match out.clicked { + Some(at) => { + let factor = if ui.input(|i| i.modifiers.alt) { 0.5 } else { 2.0 }; + zoomed_about(&out.shown, at, size, out.response.rect.size(), factor) + } + // The view as drawn, so the zoom row steps from what is on screen while the pane fits. + None => out.view.unwrap_or(out.shown), + }; + // The zoom row zooms from the keyboard too. + if let Some(v) = PreviewZoom::new(view).show(ui).view { *view = v; } } +/// `shown` zoomed by `factor` within its zoom range, keeping the point `at` of a picture of `picture` points (from its +/// top-left corner) under the pointer, settled in a well of `well` points. A zoom out to the fit or past it returns +/// to the fitting view. +fn zoomed_about(shown: &PreviewView, at: egui::Pos2, picture: egui::Vec2, well: egui::Vec2, factor: f32) -> PreviewView { + let t = shown.transform; + let fit = PreviewPane::fit_view(picture, well, &shown.range); + let scale = (t.scale * factor).min(*shown.range.end()); + let mut next = shown.clone(); + if scale <= fit.scale { + next.transform = PreviewPane::settled(fit, picture, well); + next.fit = true; + return next; + } + // Where the point lies from the well's center; the new offset keeps it there at the new zoom. + let about = (at.to_vec2() - picture / 2.0) * t.scale + t.offset; + let offset = about - (about - t.offset) * (scale / t.scale); + next.transform = PreviewPane::settled(CanvasTransform::new(scale, offset), picture, well); + next.fit = false; + next +} + /// `visible` of the snapshot at most `px` pixels: in colour without a highlight, else in grey with /// the highlighted art in `color`. fn render( @@ -446,4 +483,59 @@ mod tests { let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); assert_eq!(back.flattener_preview, app.ui.flattener_preview); } + + /// The panel in a fixture, and the preview pane's bounds. + fn shown_pane() -> (std::rc::Rc>, craft::ui::testing::Fixture, egui::Rect) { + let app = std::rc::Rc::new(std::cell::RefCell::new(app())); + let drawn = std::rc::Rc::clone(&app); + let mut fixture = craft::ui::testing::Fixture::new(move |ui| show(&mut drawn.borrow_mut(), ui)); + fixture.settle(); + let pane = fixture.by_label("Flattener Preview").unwrap_or_else(|| panic!("no preview pane")); + (app, fixture, pane.rect) + } + + /// One click at `at` with `modifiers` held, far enough from the last that the two make no double click. + fn click(fixture: &mut craft::ui::testing::Fixture, at: egui::Pos2, modifiers: egui::Modifiers) { + fixture.advance(2.0).hold(modifiers).click_at(at).hold(egui::Modifiers::NONE).idle(1); + } + + fn view(app: &std::rc::Rc>) -> PreviewView { + app.borrow().flattener_preview.view.clone() + } + + #[test] + fn a_click_zooms_in_about_the_point_and_an_alt_click_zooms_out() { + let (app, mut fixture, well) = shown_pane(); + assert!(view(&app).fit); + let at = well.center() + egui::vec2(well.width() * 0.1, well.height() * 0.1); + click(&mut fixture, at, egui::Modifiers::NONE); + let zoomed = view(&app); + assert!(!zoomed.fit, "a click leaves fit"); + // 1 is about the fit: the picture is sized to the well. + assert!(zoomed.transform.scale > 1.5, "a click zooms in: {zoomed:?}"); + // The point clicked stays under the pointer: off center, the picture moved away from the well's center. + assert!(zoomed.transform.offset.x < 0.0 && zoomed.transform.offset.y < 0.0, "{zoomed:?}"); + click(&mut fixture, at, egui::Modifiers::NONE); + let closer = view(&app); + assert!(closer.transform.scale > zoomed.transform.scale * 1.9, "a second click zooms in further"); + click(&mut fixture, at, egui::Modifiers::ALT); + let out = view(&app); + assert!((out.transform.scale - zoomed.transform.scale).abs() < 1e-3, "an Alt-click zooms back out: {out:?}"); + click(&mut fixture, at, egui::Modifiers::ALT); + assert!(view(&app).fit, "an Alt-click to the fit returns to fit"); + } + + #[test] + fn click_zoom_stays_inside_the_zoom_range() { + let (app, mut fixture, well) = shown_pane(); + // Alt-click at fit stays at fit. + click(&mut fixture, well.center(), egui::Modifiers::ALT); + assert!(view(&app).fit, "no zoom below the fit"); + for _ in 0..6 { + click(&mut fixture, well.center(), egui::Modifiers::NONE); + } + let most = view(&app); + assert!(most.transform.scale <= *most.range.end(), "no zoom past the range: {most:?}"); + assert!(!most.can_zoom_in(), "clicks reach the most zoom: {most:?}"); + } } From c766f2f4501d7e2f05c53ad12889ac703e002554 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:44:31 +0530 Subject: [PATCH 34/63] History panel: add snapshot-safe row context menus and keyboard access --- crates/color/src/oklab.rs | 3 +- crates/engine/src/history.rs | 2 +- crates/ui-egui/src/panels/history.rs | 416 +++++++++++++++++++++++++-- docs/gaps.md | 13 +- docs/roadmap.md | 12 +- docs/target-app-parity.md | 14 +- docs/ui-parity.md | 9 +- 7 files changed, 433 insertions(+), 36 deletions(-) diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 31500d1ac5..ca8db5ae30 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 { 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]]; + for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) { 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]; diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..379b8837f4 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -248,7 +248,7 @@ impl History { /// The document at row `row` of the History panel, `now` being the document now: the rows before /// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first. - pub(crate) fn state<'a>(&'a self, now: &'a Arc, row: usize) -> Option<&'a Arc> { + pub fn state<'a>(&'a self, now: &'a Arc, row: usize) -> Option<&'a Arc> { let current = self.undo.len(); match row.cmp(¤t) { std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc), diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 80508d9e4e..66a519eac7 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -1,9 +1,17 @@ //! History panel: the document's states; click one to go back (or forward) to it. +use std::sync::Arc; + +use craft::behavior::{IconId, Selection, SelectionChange, keyed}; use craft::keymap::CommandRef; -use craft::ui::menu::PanelRow; -use craft::ui::patterns::panels::{HistoryEvent, HistoryFooter, HistoryKey, HistoryPanel, HistoryRow}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, ScrollAnchor, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; +use craft::ui::display::Divider; +use craft::ui::layout_components::Stack; +use craft::ui::list::{List, ListRow, RowInk}; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; +use craft::ui::patterns::panels::{HistoryKey, HistoryRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::sections::{FooterAction, FooterBar}; use egui::Ui; use serde_json::{Value, json}; @@ -69,34 +77,168 @@ fn rows(app: &VectorcraftApp) -> Vec { .collect() } -/// Moves the document to state `target`, stopping at the first step that fails. -fn step_to(app: &mut VectorcraftApp, target: usize) { - let Some(current) = app.session.active().map(|st| st.history.undo.len()) else { return }; - let s = steps_to(current, target); - let (cmd, n) = if s < 0 { ("edit.undo", -s) } else { ("edit.redo", s) }; - for _ in 0..n { - if app.run(cmd, json!({})).is_err() { - break; - } - } +#[derive(Clone)] +struct ContextState { + document: u64, + snapshot: Arc, } +/// The shared collection supplies row focus, keyboard context requests, scrolling and menu +/// dismissal. The app retains the chosen document snapshot and dispatches its history commands. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { - let Some(undone) = app.session.active().map(|st| st.history.undo.len()) else { + let state_id = ui.scope_id().with("history-context-state"); + let document = app.session.active().map(|st| st.uid); + let mut context = ui.ctx().data(|d| d.get_temp::(state_id)); + if context.as_ref().is_some_and(|state| document != Some(state.document)) { + craft::ui::runtime::overlay::close_popups(ui.ctx()); + context = None; + } + let Some(st) = app.session.active() else { + ui.ctx().data_mut(|d| d.remove::(state_id)); super::empty_state(ui, "history", tl!("No document"), tl!("Open a document to see its history.")); return; }; + let document = st.uid; + let current = st.history.undo.len(); let rows = rows(app); - // A click on a row moves to its state at once, so the current state is the selected one. - let out = HistoryPanel::new(&rows, Some(HistoryKey::State(undone as u64))) - .footer(HistoryFooter::default().new_document(true)) - .can_delete(|_| false) - .show(ui); - for event in out.events { - match event { - HistoryEvent::Select(HistoryKey::State(n)) => step_to(app, n as usize), - HistoryEvent::NewDocument => crate::menus::invoke(app, "edit.newDocumentFromState", json!({})), - _ => {} + let mut selected = Selection::single(HistoryKey::State(current as u64)); + let mut new_document = false; + let mut target = None; + let mut action = None; + Stack::new() + .fill() + .footer(|ui, _| { + let out = FooterBar::actions([FooterAction::new(IconId::new("new_file"), tl!("Create New Document from Current State"))]).show_footer(ui); + if !ui.is_sizing_pass() { + new_document |= out.picked.is_some(); + } + }) + .show(ui, |ui, _| { + let list = List::::new(tl!("History")) + .id(ui.scope_id().with(("history-rows", document))) + .select(SelectMode::Single) + .arrows_select(false) + .selection(Bind::bound(&mut selected)) + .row_menu() + .sizing(Sizing::Fill) + .scroll_anchor(ScrollAnchor::End); + let out = list.show_items(ui, &keyed(&rows, |row: &HistoryRow| row.key), &mut |_, icx| { + let row = &rows[icx.at]; + let mut item = ListRow::new(row.label.clone()).cells(icx.cells()).state(icx.row.clone()); + if let Some(icon) = row.icon.clone() { + item = item.icon(icon.into()); + } + if row.redo { + item = item.ink(RowInk::Dimmed); + } + item + }); + let requested = out.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => Some(request.key), + _ => None, + }); + if let Some(HistoryKey::State(row)) = requested { + context = app + .session + .active() + .and_then(|st| st.history.state(&st.doc, row as usize)) + .cloned() + .map(|snapshot| ContextState { document, snapshot }); + } else { + for event in &out.events { + if let CollectionEvent::Activate(HistoryKey::State(row)) = event { + target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned(); + } + if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event + && let Some(HistoryKey::State(row)) = keys.last() + && *row as usize != current + { + target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned(); + } + } + } + if let Some(state) = context.as_ref() { + let snapshot = state.snapshot.clone(); + let can_step = app.session.active().is_some_and(|st| !Arc::ptr_eq(&snapshot, &st.doc)); + let shown = Menu::context(tl!("History"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("New Document from State")).enabled(crate::menus::enabled(app, "edit.newDocumentFromState")).show(ui).ran { + action = Some(("edit.newDocumentFromState", snapshot.clone())); + } + if MenuItem::new(tl!("Step to This State")).enabled(can_step).show(ui).ran { + target = Some(snapshot.clone()); + } + Divider::horizontal().show(ui); + if MenuItem::new(tl!("Clear History")).enabled(crate::menus::enabled(app, "edit.clearHistory")).show(ui).ran { + action = Some(("edit.clearHistory", snapshot.clone())); + } + }); + if shown.output.closed.is_some() || action.is_some() || target.is_some() { + context = None; + } + } + }); + ui.ctx().data_mut(|d| { + if let Some(state) = context { + d.insert_temp(state_id, state); + } else { + d.remove::(state_id); + } + }); + if let Some((command, snapshot)) = action { + if command == "edit.newDocumentFromState" { + if let Some(row) = resolve_state(app, snapshot, false) { + crate::menus::invoke(app, command, json!({ "index": row })); + } + } else { + crate::menus::invoke(app, command, json!({})); + } + } + if let Some(target) = target { + step_to_state(app, target); + } + if new_document { + crate::menus::invoke(app, "edit.newDocumentFromState", json!({})); + } +} + +/// Keep the clicked snapshot while pending edits settle: they can add or trim history rows. +fn resolve_state(app: &mut VectorcraftApp, target: Arc, keep_typing: bool) -> Option { + let requests = app.session.finish_tool_edit(); + let failed = requests.is_err(); + crate::canvas::apply_requests(app, requests); + if failed { + return None; + } + if keep_typing && let Err(e) = app.keep_typing() { + app.status(e); + return None; + } + let st = app.session.active()?; + let current = st.history.undo.len(); + let row = if Arc::ptr_eq(&st.doc, &target) { + Some(current) + } else { + st.history + .undo + .iter() + .position(|h| Arc::ptr_eq(&h.doc, &target)) + .or_else(|| st.history.redo.iter().rev().position(|h| Arc::ptr_eq(&h.doc, &target)).map(|i| current + i + 1)) + }; + if row.is_none() { + app.status(tl!("That history state is no longer available.")); + } + row +} + +fn step_to_state(app: &mut VectorcraftApp, target: Arc) { + let Some(row) = resolve_state(app, target, true) else { return }; + let Some(st) = app.session.active() else { return }; + let steps = steps_to(st.history.undo.len(), row); + let (cmd, n) = if steps < 0 { ("edit.undo", -steps) } else { ("edit.redo", steps) }; + for _ in 0..n { + if let Err(e) = app.run(cmd, json!({})) { + app.status(e); + break; } } } @@ -284,4 +426,232 @@ mod tests { assert!(st.is_dirty(), "the new document is unsaved"); assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source), "the source stays at that state"); } + + fn history_harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(260.0, 400.0)) + .with_context_setup(crate::testing::install) + .build_ui_state(|ui, app| show(app, ui), app); + h.run_steps(2); + h + } + + fn row_menu_harness(app: VectorcraftApp, row: usize) -> egui_kittest::Harness<'static, VectorcraftApp> { + use egui_kittest::kittest::Queryable; + let mut h = history_harness(app); + let pos = h.get_all_by_role(egui::accesskit::Role::ListItem).nth(row).expect("history row").rect().center(); + h.event(egui::Event::PointerMoved(pos)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }); + } + h.run_steps(2); + h + } + + fn focus_previous_state(h: &mut egui_kittest::Harness<'static, VectorcraftApp>) { + use egui_kittest::kittest::{NodeT, Queryable}; + for _ in 0..4 { + h.key_press(egui::Key::Tab); + h.run_steps(1); + if h.get_all_by_role(egui::accesskit::Role::ListItem).nth(2).unwrap().accesskit_node().is_focused() { + break; + } + } + assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(2).unwrap().accesskit_node().is_focused()); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(1).unwrap().accesskit_node().is_focused()); + assert_eq!(depth(h.state()), (2, 0), "moving focus must not step history"); + } + + #[test] + fn keyboard_activation_steps_to_the_focused_state() { + let mut h = history_harness(app_with_two_rectangles()); + focus_previous_state(&mut h); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(depth(h.state()), (1, 1)); + assert_eq!(h.state().session.active().unwrap().doc.layers[0].children().unwrap().len(), 1); + } + #[test] + fn switching_documents_dismisses_the_row_menu_without_clearing_either_history() { + use egui_kittest::kittest::Queryable; + let mut app = app_with_two_rectangles(); + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap(); + for x in [10, 60] { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + } + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + let mut h = row_menu_harness(app, 1); + h.get_by_label("Clear History"); + h.state_mut().session.execute("document.activate", &json!({"index": 1})).unwrap(); + h.run_steps(2); + assert!(h.query_by_label("Clear History").is_none(), "the other document must not inherit the popup"); + h.state_mut().session.execute("document.activate", &json!({"index": 0})).unwrap(); + h.run_steps(2); + assert!(h.query_by_label("Clear History").is_none(), "switching back must not revive the popup"); + for st in h.state().session.documents() { + assert_eq!((st.history.undo.len(), st.history.redo.len()), (1, 1)); + } + } + + #[test] + fn keyboard_opens_dismisses_and_activates_the_focused_rows_menu() { + use egui_kittest::kittest::{NodeT, Queryable}; + let app = app_with_two_rectangles(); + let source = app.session.active().unwrap().doc.clone(); + let wanted = app.session.active().unwrap().history.undo[1].doc.clone(); + let mut h = history_harness(app); + focus_previous_state(&mut h); + h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + h.run_steps(2); + assert!(h.get_by_label("New Document from State").accesskit_node().is_focused()); + assert_eq!(depth(h.state()), (2, 0), "opening does not step"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.query_by_label("New Document from State").is_none()); + assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(1).unwrap().accesskit_node().is_focused()); + h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().session.documents().len(), 2); + assert_eq!(h.state().session.active().unwrap().doc.layers, wanted.layers); + assert!(Arc::ptr_eq(&h.state().session.documents()[0].doc, &source)); + assert_eq!(h.state().session.documents()[0].history.undo.len(), 2); + } + + #[test] + fn right_clicking_an_earlier_state_opens_its_menu_without_stepping() { + use egui_kittest::kittest::Queryable; + let h = row_menu_harness(app_with_two_rectangles(), 1); + h.get_by_label("New Document from State"); + h.get_by_label("Step to This State"); + h.get_by_label("Clear History"); + assert_eq!(depth(h.state()), (2, 0)); + } + + #[test] + fn the_row_menu_makes_a_new_document_from_that_snapshot() { + use egui_kittest::kittest::Queryable; + let mut app = app_with_two_rectangles(); + app.session.execute("edit.undo", &json!({})).unwrap(); + let snapshot = app.session.active().unwrap().doc.clone(); + app.session.execute("edit.redo", &json!({})).unwrap(); + let source = app.session.active().unwrap().doc.clone(); + let mut h = row_menu_harness(app, 1); + h.get_by_label("New Document from State").click(); + h.run_steps(2); + let app = h.state(); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.active_index(), Some(1)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers, snapshot.layers, "the historic artwork"); + assert!(st.is_dirty()); + assert_eq!(depth(app), (0, 0)); + assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source)); + assert_eq!(app.session.documents()[0].history.undo.len(), 2); + } + + #[test] + fn the_row_menu_steps_backward_and_forward_to_the_target() { + use egui_kittest::kittest::{NodeT, Queryable}; + for (current, target) in [(2, 0), (0, 2), (1, 1)] { + let mut app = app_with_two_rectangles(); + for _ in current..2 { + app.session.execute("edit.undo", &json!({})).unwrap(); + } + let mut h = row_menu_harness(app, target); + let item = h.get_by_label("Step to This State"); + assert_eq!(item.accesskit_node().is_disabled(), current == target); + item.click(); + h.run_steps(2); + assert_eq!(depth(h.state()), (target, 2 - target)); + assert_eq!(h.state().session.active().unwrap().doc.layers[0].children().unwrap().len(), target); + } + } + + #[test] + fn the_row_menu_clears_undo_and_redo_without_changing_art() { + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = app_with_two_rectangles(); + app.session.execute("edit.undo", &json!({})).unwrap(); + let source = app.session.active().unwrap().doc.clone(); + let mut h = row_menu_harness(app, 0); + h.get_by_label("Clear History").click(); + h.run_steps(2); + assert_eq!(depth(h.state()), (0, 0)); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &source)); + let mut empty = app_with_two_rectangles(); + empty.session.execute("edit.clearHistory", &json!({})).unwrap(); + let h = row_menu_harness(empty, 0); + assert!(h.get_by_label("Clear History").accesskit_node().is_disabled()); + } + + #[test] + fn stepping_settles_typing_and_follows_the_snapshot_when_rows_shift() { + use egui_kittest::kittest::Queryable; + for (limit, row) in [(10, 0), (2, 1)] { + let mut app = app_with_two_rectangles(); + app.session.active_mut().unwrap().history.limit = limit; + let st = app.session.active().unwrap(); + let wanted = st.history.state(&st.doc, row).unwrap().clone(); + app.session.begin_interaction("Typing").unwrap(); + app.session.preview("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let mut h = row_menu_harness(app, row); + h.get_by_label("Step to This State").click(); + h.run_steps(2); + let st = h.state().session.active().unwrap(); + assert_eq!(st.doc.layers, wanted.layers, "limit {limit}, row {row}"); + assert!(st.interaction.is_none()); + assert_eq!(st.history.undo.len(), 0); + } + } + + #[test] + fn copying_a_state_resolves_pending_tool_edits_without_copying_a_neighbor() { + use egui_kittest::kittest::Queryable; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + for (row, finishes_while_open) in [(0, false), (1, false), (0, true), (1, true)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 200})).unwrap(); + // A Shape Builder merge over this many segments computes on another thread. + for k in 0..40 { + app.run("shape.rectangle", json!({"x": k * 10, "y": 0, "width": 20, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app.run("tool.select", json!({"tool": "shapeBuilder"})).unwrap(); + let st = app.session.active_mut().unwrap(); + st.history.limit = 2; + st.history.trim(); + let wanted = st.history.state(&st.doc, row).unwrap().clone(); + let view = app.view_info(); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Move, 15.0, 10.0), view); + app.session.tool_poll(view, true).unwrap(); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, 15.0, 10.0), view); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Up, 15.0, 10.0), view); + assert!(app.session.tool_waiting()); + let mut h = row_menu_harness(app, row); + if finishes_while_open { + let requests = h.state_mut().session.finish_tool_edit(); + crate::canvas::apply_requests(h.state_mut(), requests); + h.run_steps(2); + } + h.get_by_label("New Document from State").click(); + h.run_steps(2); + let app = h.state(); + assert!(!app.session.tool_waiting()); + if row == 0 { + assert_eq!(app.session.documents().len(), 1, "the pruned snapshot must not copy its neighbor"); + assert_eq!(app.ui.status, "That history state is no longer available."); + } else { + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(app.session.active().unwrap().doc.layers, wanted.layers, "the retained snapshot moved from row 1 to row 0"); + } + } + } } diff --git a/docs/gaps.md b/docs/gaps.md index 0c9937458b..31ea0c8e80 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -12,6 +12,8 @@ ## Feature submission evidence +History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. + Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. @@ -24,7 +26,7 @@ Draft enhancement #5804: Preferences › File Handling can select a raster edito > **Eraser fill update (2026-11-11):** filled open paths without a visible painted stroke retain fill outside the sweep or Alt-drag marquee (#6582); stroked paths retain main behavior; scores and estimates unchanged. -**Feature evidence last updated:** 2026-11-20. +**Feature evidence last updated:** 2026-11-21. Properties panel Quick Actions include contextual text actions when live type is selected: Create Outlines (`type.createOutlines`), Retype (`ui.retype`), and Find and Replace… (`ui.findAndReplace`), while retaining standard object actions (Arrange: Bring to Front, Lock) and suppressing path-only actions (Offset Path, Simplify) for type-only selections. Evidence: `panels::properties::tests::type_quick_actions_show_text_commands_and_create_outlines` in `crates/ui-egui/src/panels/properties/tests.rs`. Scores and estimates unchanged. @@ -60,6 +62,9 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | +| 2026-11-20 | minor | G12: History panel row context menus: New Document from State uses the clicked snapshot; Step to This State runs undo/redo; Clear History clears both stacks. Current-state stepping and empty-history clearing are disabled. Headless tests in `crates/ui-egui/src/panels/history.rs`; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); headless tests in crates/ui-egui/src/panels/properties/tests.rs; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | @@ -526,6 +531,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Implemented (2026-11-20):** History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. + - **Implemented (2026-11-20):** Asset Export tiles have item context menus: Export and Remove act on the asset selection (plural labels for multiple assets), Rename opens the clicked tile's inline field, Select Artwork on Canvas selects that tile's source nodes, and Add Selected Artwork as One Asset / Multiple Assets are enabled with canvas selection. A right-click selects an unselected tile, clearing the previous asset selection, and preserves a multi-selection when the tile is already selected. Export reuses the raster/3D export path; Remove is one undo step and keeps the artwork. Headless regression coverage: `crates/ui-egui/src/panels/tests_asset_export.rs`. Other G12 panel gaps remain; scores and estimates unchanged. - **Implemented and tested (2026-11-20):** Appearance panel row context menus: right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Headless regression coverage: `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged. @@ -988,6 +995,8 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G3: shadows from the first light and graphics on 3D surfaces moved from Missing to Done, as three-d.md documents them, and angular cut caps dropped from Missing, as Revolve's Cap closes a partial sweep's cut sides ([revolve.md](revolve.md)) (#8312); estimate unchanged | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel: right-click item context menus for rows (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index b403e455e9..78f76ebdb5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel row context menus, #8809; previously: M1: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -53,7 +53,7 @@ Creating a gradient from solid or empty paint uses the document's color model fo Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-03. +**Feature evidence last updated:** 2026-11-21. M1 selection: Enclosing Lasso selects whole objects enclosed by a freehand loop. It is an add-on under Object › Plug-ins, and its tool is also in the Lasso tool's group in both shipped toolbars, @@ -76,6 +76,8 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | M14/G12: Appearance panel item context menus for stroke, fill, effect, and root object rows (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance); secondary-click selects unselected rows including via name label links; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | M14/G12: Graphic Styles panel item context menus in thumbnail and list views (Options…, Duplicate, Delete, Redefine, Break Link); regression tests in crates/ui-egui/src/panels/graphic_styles.rs; scores and estimates unchanged. | @@ -199,7 +201,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | 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 (hiding the guides and the grid while it is on, #8363), 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 (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), 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 | -| M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | +| M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -241,6 +243,8 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | @@ -485,3 +489,5 @@ Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transpare > **Swatches status (2026-11-15):** Item context menus are implemented and covered by headless tests; full CI passed on the latest-main integration (all 13 gates), including the updated panel-view harness; parity scores and estimates are unchanged. > **Text styles status (2026-11-19):** Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides) are implemented and covered by headless tests; parity scores and estimates are unchanged. + +> **History status (2026-11-20, G12/M14):** History row context menus are implemented with headless snapshot, pending-edit, typing, stepping, clear-history, keyboard menu and document-switch regressions in `panels::history::tests` (#8845). Other G12 work, scores and estimates are unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a80d4f8f97..104347e700 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side columns; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -32,6 +32,8 @@ ## Feature submission evidence +History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. + Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. @@ -58,7 +60,7 @@ Spiral decay now applies after each full wind of four segments. A newly drawn sp Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-19. +**Feature evidence last updated:** 2026-11-21. Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. @@ -79,6 +81,9 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | +| 2026-11-20 | minor | G12: History panel row context menus: New Document from State uses the clicked snapshot; Step to This State runs undo/redo; Clear History clears both stacks. Current-state stepping and empty-history clearing are disabled. Headless tests in `crates/ui-egui/src/panels/history.rs`; scores and estimates unchanged. | | 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | @@ -323,7 +328,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -1205,6 +1210,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Korean catalog (`crates/ui-egui/src/i18n/ko.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 39 Korean messages; they are the composite font, select-a-path, justification order and `path.freehand` connect errors that open #7211, #7214, #7116 and #7330 translate. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The Vietnamese catalog (`crates/ui-egui/src/i18n/vi.tsv`) has an `@msg` row for 115 of the status and error messages that the untranslated report listed for every complete-message catalog, among them the image export, color profile, color book, swatch exchange file, swatch library, DXF and DWG import, 3D and Revolve errors and the `index` whole-number error, 1,750 `@msg` rows in all. The untranslated report (`untranslated_report`) lists 1,875 Vietnamese messages without a row; open #7211, #7378, #7405 and #7434 translate 53 of them. - The Swedish catalog (`crates/ui-egui/src/i18n/sv.tsv`) translates status and error messages, among them the image export, color profile, color book, swatch exchange file, DXF import, 3D and Revolve errors and the `index` check of `document.activate`, 3,106 `@msg` rows in all. The untranslated report (`untranslated_report`) lists 518 Swedish messages, 54 of them messages that no catalog translates yet. + - History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. - The History panel menu's Clear History (`edit.clearHistory`) removes every step to undo and to redo and leaves the document as it is; it is not an undo step itself, and it is disabled when there is no step to clear. - The New Document from State button at the bottom of the History panel (`edit.newDocumentFromState`) makes a new document, which becomes active, from the state the panel has selected ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/undo-edits-and-manage-design-history.html)). VectorCraft's own rules: the new document takes the next Untitled-N name, is marked unsaved, has nothing selected and has no steps to undo or redo, and the source document and its steps stay as they are. @@ -3224,6 +3230,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c74a8a8d7b..729b33b673 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -44,7 +44,7 @@ Creating a gradient from solid or empty paint uses the document's color model fo Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-19. +**Feature evidence last updated:** 2026-11-21. Enclosing Lasso is an add-on under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select. A toolbar @@ -70,6 +70,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides); regression tests in crates/ui-egui/src/panels/text_styles/tests.rs; scores and estimates unchanged. | @@ -515,6 +517,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | +| History panel row context menu (G12) | done | New Document from State, Step to This State, and Clear History; current-row stepping and empty-history clearing are disabled. Snapshot identity is checked after pending tool edits, and jumps settle typing before counting undo/redo. A state discarded while an edit settles reports that it is unavailable. Shift+F10 opens the focused row menu; Escape returns focus to the row. Switching documents dismisses the menu. Headless tests: `panels::history::tests`. | | Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | | Appearance panel row context menu (G12) | done | Right-clicking a stroke or fill row offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide/Show Stroke / Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide/Show Effect; root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets it first before opening the context menu. Tests: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance`. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | @@ -633,6 +636,8 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | +| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. | From 1c4df7b3432e83c6781655cc384d57c317a8a5cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:42:21 -0800 Subject: [PATCH 35/63] Rerun CI From 7418753350ebbaa156412d6520fecfc3942d0d3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:53:19 -0800 Subject: [PATCH 36/63] Windows: the Wintab context opens only while the tool uses the wheel The Paintbrush with a brush whose Size or Width is on Stylus Wheel with a range the wheel can change, or the Eraser with a value on Stylus Wheel and a variation above 0, uses the wheel. The app asks the active tool (Tool::reads_wheel) once a frame and tells the host when the answer changes (Services::stylus_wheel). Until a tool uses the wheel, a pen message loads no Wintab32.dll, installs no hook, subclasses no window and opens no context; when it stops, the context closes. --- apps/vectorcraft/src/host_services.rs | 4 + apps/vectorcraft/src/windows_wintab.rs | 116 +++++++++++++++++++--- crates/engine/src/tooling.rs | 6 ++ crates/tools/src/draw2/gesture.rs | 5 + crates/tools/src/draw2/gesture/tests.rs | 19 ++++ crates/tools/src/lib.rs | 6 ++ crates/tools/src/symbolism.rs | 62 ++++++++++++ crates/ui-egui/src/app.rs | 5 + crates/ui-egui/src/canvas/tool_adapter.rs | 9 +- crates/ui-egui/src/services.rs | 3 + crates/ui-egui/src/stylus.rs | 62 ++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 13 files changed, 286 insertions(+), 17 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 06be570630..47813f192e 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services { open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. print: Some(Box::new(printing::SystemPrint)), + // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens + // only while the active tool uses the wheel. + #[cfg(all(windows, not(target_vendor = "win7")))] + stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)), ..Default::default() } } diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index c49bcbea7f..be43f918f2 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -8,9 +8,13 @@ //! Windows Ink comparison says the wheel comes only through Wintab //! (). //! +//! - Nothing here runs until the active tool draws with a brush or tip that varies with the +//! finger wheel (Stylus Wheel), as the app says through [`set_wheel_used`]: until then pen +//! messages load no library, install no hook and open no context, and when the tool stops +//! using the wheel the context closes ([`unused_context`]). //! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen -//! comes over a window. Without it, without one of its exports, or when a call fails, the pens -//! read no wheel and draw as before; the user sees no error. +//! comes over a window while the wheel is used. Without it, without one of its exports, or when +//! a call fails, the pens read no wheel and draw as before; the user sees no error. //! - The context is opened from the driver's default context for the window that owns the pen's //! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor //! and makes no press. When the pen comes over another top-level window, such as a separate @@ -403,6 +407,35 @@ fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, own (step, active && (due || step != Current::Keep)) } +/// The context step for a pen message while the active tool reads no wheel ([`Wheel::Unused`]): +/// an open context closes, or is dropped when its window is gone (`current` as for +/// [`next_context`]), and none opens. +fn unused_context(current: Option<(usize, bool)>) -> Current { + match current { + Some((_, false)) => Current::Drop, + Some(_) => Current::Close, + None => Current::Keep, + } +} + +/// Whether the active tool draws with a brush or tip that varies with the finger wheel, as the +/// app last said ([`set_wheel_used`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Wheel { + /// No pen message loads `Wintab32.dll`, installs the thread's hook or opens a context, and a + /// context still open closes. + #[default] + Unused, + /// Pen messages open the context as [`next_context`] says. + Used, +} + +/// Whether a pen message calls the driver at all: while the wheel is used, or to close a context +/// still open after it stopped being used. +fn calls_driver(wheel: Wheel, open: bool) -> bool { + wheel == Wheel::Used || open +} + /// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or /// more later, on the message clock, which wraps. fn retry_due(at: u32, time: u32) -> bool { @@ -533,12 +566,12 @@ fn message(message: u32, wparam: usize, lparam: isize) -> Message { } #[cfg(windows)] -pub use win::{forget, msg_hook, pen_wheel, wheel_pen}; +pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; #[cfg(windows)] #[allow(unsafe_code)] mod win { - use std::cell::RefCell; + use std::cell::{Cell, RefCell}; use std::ffi::c_void; use std::sync::OnceLock; @@ -554,8 +587,8 @@ mod win { use super::{ Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, - MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, - configure, decode, device_of, hooked_open, message, next_context, retry_due, wheel_axis, + MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, Wheel, + calls_driver, configure, decode, device_of, hooked_open, message, next_context, retry_due, unused_context, wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -598,6 +631,9 @@ mod win { /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends /// while [`STATE`] is borrowed for a driver call. static NOTICES: RefCell = RefCell::new(Notices::default()); + /// Whether the active tool uses the wheel ([`set_wheel_used`]), kept apart from [`STATE`] so + /// the app can say so while [`STATE`] is borrowed. + static WHEEL: Cell = const { Cell::new(Wheel::Unused) }; } /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. @@ -802,6 +838,11 @@ mod win { wheel_axis(csr_type, csr_pktdata, info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE)) } + /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. + fn context_open() -> bool { + STATE.with(|s| !s.try_borrow().is_ok_and(|s| s.context.is_none())) + } + fn is_window(hwnd: *mut c_void) -> bool { // SAFETY: `IsWindow` takes any handle value and reads no caller memory. unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() @@ -845,14 +886,18 @@ mod win { } /// Moves the context to the window that owns `hwnd`, for a pen message at the message time - /// `time` ([`next_context`]). - fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32) { + /// `time` ([`next_context`]), or closes it when the active tool does not use the wheel + /// (`wheel`, [`unused_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32, wheel: Wheel) { // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; let owner = if owner.is_null() { hwnd } else { owner }; let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); let tried = self.tried.map(|(w, at)| (w as usize, at)); - let (step, open) = next_context(current, tried, owner as usize, time, is_active()); + let (step, open) = match wheel { + Wheel::Used => next_context(current, tried, owner as usize, time, is_active()), + Wheel::Unused => (unused_context(current), false), + }; match step { Current::Keep => {} Current::Drop => { @@ -907,6 +952,9 @@ mod win { if what == Message::Other { return; } + if !calls_driver(WHEEL.get(), context_open()) { + return; + } let Some(api) = api() else { return }; note(what); STATE.with(|s| { @@ -935,21 +983,51 @@ mod win { /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when - /// none is open. The first call installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// none is open. While the active tool does not use the wheel ([`set_wheel_used`]), it reads + /// none and calls the driver only to close a context still open ([`calls_driver`]). The first + /// call that opens a context installs [`call_wnd_proc`] ([`hook_thread`]); until it is /// installed, no context opens and the pens read no wheel. pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { + let used = WHEEL.get(); + if !calls_driver(used, context_open()) { + return None; + } let api = api()?; - if !hook_thread(time) { + if used == Wheel::Used && !hook_thread(time) { return None; } let wheel = STATE.with(|s| { let mut s = s.try_borrow_mut().ok()?; s.take_notices(api); - s.open_for(api, hwnd.0, time); + s.open_for(api, hwnd.0, time, used); s.readings.wheel_for(time, pen, eraser) }); settle(); - wheel + wheel.filter(|_| used == Wheel::Used) + } + + /// The app says whether the active tool draws with a brush or tip that varies with the finger + /// wheel (`used`). Until it says so, pen messages read no wheel and leave the driver alone; when + /// it stops, the context closes now, or at the next pen message while the reader is in a call + /// of its own. + pub fn set_wheel_used(used: bool) { + let wheel = if used { Wheel::Used } else { Wheel::Unused }; + if WHEEL.replace(wheel) == wheel { + return; + } + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.tried = None; + if wheel == Wheel::Unused + && s.context.is_some() + && let Some(api) = api() + { + // A context the driver closed is dropped without `WTClose`. + s.take_notices(api); + s.close(api); + } + }); + settle(); } /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer @@ -1220,6 +1298,18 @@ mod tests { assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); } + #[test] + fn the_driver_is_left_alone_until_the_wheel_is_used() { + assert!(!calls_driver(Wheel::Unused, false), "no brush or tip on Stylus Wheel"); + assert!(calls_driver(Wheel::Used, false), "one is: the context opens"); + assert!(calls_driver(Wheel::Unused, true), "none any more: the open context closes"); + assert_eq!(Wheel::default(), Wheel::Unused, "at start-up"); + let main = 0x10; + assert_eq!(unused_context(None), Current::Keep, "nothing open"); + assert_eq!(unused_context(Some((main, true))), Current::Close, "the pen window's context closes"); + assert_eq!(unused_context(Some((main, false))), Current::Drop, "a gone window's is dropped"); + } + #[test] fn another_app_becoming_active_closes_the_context() { assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 446d441fc4..be665de83a 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1060,6 +1060,12 @@ impl Session { self.tool.wants_samples() } + /// Does a stroke the active tool draws now vary with an airbrush pen's finger wheel + /// ([`vectorcraft_tools::Tool::reads_wheel`])? False with no document open. + pub fn tool_reads_wheel(&mut self, view: ViewInfo) -> bool { + self.with_tool_cx(view, |t, cx| t.reads_wheel(cx)) + } + /// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input /// held until an edit it computes is applied, or are requests for the UI left from making it? pub fn tool_waiting(&self) -> bool { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 4f2fb7b463..67bb337774 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1861,6 +1861,11 @@ impl Tool for GestureTool { fn wants_samples(&self) -> bool { matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser") } + /// The Blob Brush's and the Eraser's tip varies with the wheel when a value is on Stylus Wheel + /// with a Variation above 0. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + self.tip_modes().contains(&Variation::StylusWheel) + } /// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again /// after a zoom change, reach the whole drag over several frames. fn overlays_pending(&self) -> bool { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 24a0e1e5e6..b6d2dc1073 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -4008,3 +4008,22 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil")); assert_eq!(last[1], Action::Commit); } + +#[test] +fn the_eraser_reads_the_wheel_only_with_a_value_on_stylus_wheel() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + for id in ["pencil", "paintbrush", "blobBrush", "eraser"] { + assert!(!GestureTool::new(id).reads_wheel(&cx), "{id} at its defaults"); + } + for value in ["angle", "roundness", "size"] { + let mut t = GestureTool::new("eraser"); + t.set_option(&format!("{value}Mode"), &json!("stylusWheel")); + assert!(!t.reads_wheel(&cx), "{value} on Stylus Wheel with no Variation"); + t.set_option(&format!("{value}Variation"), &json!(4)); + assert!(t.reads_wheel(&cx), "{value} on Stylus Wheel"); + t.set_option(&format!("{value}Mode"), &json!("pressure")); + assert!(!t.reads_wheel(&cx), "{value} on Pressure"); + } +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 486de86876..0942322124 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -319,6 +319,12 @@ pub trait Tool: Send { fn wants_samples(&self) -> bool { false } + /// Does a stroke the tool draws now vary with an airbrush pen's finger wheel (a brush or tip + /// with Stylus Wheel variation)? A host that has to open a tablet interface of its own to read + /// the wheel opens it only while this is so. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + false + } /// Is the tool waiting for work it runs on another thread (the planar map of a large selection /// for the Shape Builder and the Live Paint Bucket, a Shape Builder merge of one)? It /// highlights nothing under the pointer until a map is done. While this holds, the desktop app diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 165ced795e..9d6fe2e887 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -438,6 +438,20 @@ impl Tool for BrushPaintTool { fn wants_samples(&self) -> bool { self.inner.wants_samples() } + /// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus + /// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values + /// differ, or an Art brush whose width is on it with two different widths. + fn reads_wheel(&self, cx: &ToolContext) -> bool { + use vectorcraft_brush::{BrushKind, Variation}; + let wheel = |mode: Variation| mode == Variation::StylusWheel; + let Some(brush) = self.brush_name(cx).and_then(|n| vectorcraft_brush::find(cx.doc, &n)) else { return false }; + match brush.kind { + BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0), + BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b), + BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1, + BrushKind::Pattern(_) | BrushKind::Bristle(_) => false, + } + } fn busy(&self) -> bool { self.inner.busy() } @@ -758,4 +772,52 @@ mod tests { let a = drag(&d, &mut BrushPaintTool::default()); assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}"); } + + #[test] + fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation}; + let wheel = Variation::StylusWheel; + let calligraphic = + |modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() }); + let scatter = |size| { + BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() }) + }; + let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() }); + let library = [ + Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) }, + Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) }, + Brush { name: "Still nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 0.0) }, + Brush { name: "Dots".into(), kind: scatter((50.0, 150.0)) }, + Brush { name: "Even dots".into(), kind: scatter((100.0, 100.0)) }, + Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) }, + Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) }, + Brush { name: "Flat".into(), kind: art(None, 200.0) }, + ]; + let (mut d, _) = doc_with_rect(); + d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap()); + let (s, p) = (Selection::default(), paint()); + let reads = |d: &vectorcraft_doc::Document, t: &BrushPaintTool| t.reads_wheel(&cx(d, &s, &p)); + let mut t = BrushPaintTool::default(); + assert!(!reads(&d, &t), "no brush"); + let brushes = [ + ("Plain", false), + ("Nib", true), + ("Still nib", false), + ("Dots", true), + ("Even dots", false), + ("Taper", true), + ("Even taper", false), + ("Flat", false), + ("Deleted", false), + ]; + for (name, varies) in brushes { + d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!(name)); + assert_eq!(reads(&d, &t), varies, "the current brush {name}"); + } + t.set_option("brush", &json!("Plain")); + assert!(!reads(&d, &t), "the tool's own brush comes first"); + t.set_option("brush", &json!("Nib")); + d.unknown.remove(vectorcraft_brush::CURRENT_KEY); + assert!(reads(&d, &t), "and reads the wheel"); + } } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 299f4c22d5..3c08e487e2 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -441,6 +441,11 @@ impl VectorcraftApp { let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // With no document open too, so closing the last one stops the host reading the wheel. A + // held press, whose previews change the document each frame, keeps what it was told. + if self.canvas.grab.is_none() { + crate::stylus::sync_wheel_use(self); + } self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 3a8f20f69c..5bda6d918e 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -577,8 +577,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too } // Once a frame, before its press, which then uses the new tool; a held press (its grab) waits for the frame after // the release, and a pointer over another window for the pointer to come in. - if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() && ui.input(|i| i.pointer.has_pointer()) { - crate::stylus::sync_eraser_tool(app); + if ui.ctx().current_pass_index() == 0 + && app.canvas.grab.is_none() + && ui.input(|i| i.pointer.has_pointer()) + && crate::stylus::sync_eraser_tool(app) + { + // Before the press, which holds what the host was told about the wheel until its release. + crate::stylus::sync_wheel_use(app); } // A press on the canvas that a view tool takes (a middle-button pan, a held Space's Hand) counts as a press // elsewhere for the clicks the tool's double-click or triple-click compares. diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 40d7ff903f..8e653d8dce 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -62,6 +62,9 @@ pub struct Services { /// The pen the host reads itself (tablet APIs the window system doesn't route): the same /// handle the host installs for the framework's pointer feed. pub pen: Option, + /// Told whether the active tool reads an airbrush pen's finger wheel (Windows: the host opens + /// the tablet driver's Wintab context only while it does). Without it nothing is told. + pub stylus_wheel: Option>, pub read: Option, /// Read at most a number of bytes from a file (desktop). A file with a size limit is read one /// byte past the limit, so a larger file is refused without reading all of it. Without it, the diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index f92fc2f347..0491874822 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -22,6 +22,10 @@ use crate::VectorcraftApp; /// The tool the pen's eraser end selects. const ERASER: &str = "eraser"; +/// What decides whether the active tool reads an airbrush pen's finger wheel ([`sync_wheel_use`]): +/// the active document's uid and revision, its current brush, and the tool with its options. +type WheelKey = (Option<(u64, u64)>, Option, &'static str, serde_json::Value); + /// The end of the pen the canvas saw last, and the tool the eraser end stands in for /// ([`sync_eraser_tool`]). #[derive(Clone, Debug, Default)] @@ -30,6 +34,8 @@ pub(crate) struct PenEnd { end: Option, /// The tool that was active when the eraser end selected the Eraser. before: Option<&'static str>, + /// What the host was last told about the finger wheel, and for which state ([`sync_wheel_use`]). + wheel: Option<(WheelKey, bool)>, } impl PenEnd { @@ -79,6 +85,33 @@ pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool { } } +/// Tells the host whether the active tool reads an airbrush pen's finger wheel +/// ([`crate::Services::stylus_wheel`]): the Paintbrush with a brush on Stylus Wheel, or +/// the Eraser with a value on it. The host is told at the first call and then each time the answer +/// changes; the tool is asked again only when the document, its current brush, the tool or its +/// options change. +/// +/// [`VectorcraftApp::tick`] calls this once a frame, with no document open too, and the canvas +/// calls it again when the pen's end changes the tool ([`sync_eraser_tool`]). +pub(crate) fn sync_wheel_use(app: &mut VectorcraftApp) { + if app.services.stylus_wheel.is_none() { + return; + } + let st = app.session.active(); + let key = + (st.map(|s| (s.uid, s.revision)), st.and_then(|s| vectorcraft_brush::current(&s.doc)), app.session.tool_id(), app.session.tool_options()); + if app.pen_end.wheel.as_ref().is_some_and(|(k, _)| *k == key) { + return; + } + let used = app.session.tool_reads_wheel(app.view_info()); + let told = app.pen_end.wheel.replace((key, used)).map(|(_, u)| u); + if told != Some(used) + && let Some(tell) = app.services.stylus_wheel.as_mut() + { + tell(used); + } +} + #[cfg(test)] mod tests { use super::*; @@ -126,4 +159,33 @@ mod tests { assert!(!sync_eraser_tool(&mut app)); assert_eq!(app.session.tool_id(), "rectangle"); } + + #[test] + fn the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel() { + use serde_json::json; + let told = std::rc::Rc::new(std::cell::RefCell::new(vec![])); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let tell = told.clone(); + app.services.stylus_wheel = Some(Box::new(move |used| tell.borrow_mut().push(used))); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + app.select_tool("paintbrush"); + let frame = |app: &mut VectorcraftApp| { + sync_wheel_use(app); + told.borrow().clone() + }; + assert_eq!(frame(&mut app), [false], "told at the first frame"); + assert_eq!(frame(&mut app), [false], "and not again while nothing changes"); + app.session.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap(); + assert_eq!(frame(&mut app), [false], "a brush without Stylus Wheel"); + let params = json!({"variation": [0, 0, 2], "modes": ["fixed", "fixed", "stylusWheel"]}); + app.session.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap(); + assert_eq!(frame(&mut app), [false, true], "its size on Stylus Wheel"); + app.select_tool("rectangle"); + assert_eq!(frame(&mut app), [false, true, false], "another tool"); + app.select_tool(ERASER); + assert_eq!(frame(&mut app), [false, true, false], "the Eraser at its defaults"); + app.session.set_tool_option("sizeMode", &json!("stylusWheel")); + app.session.set_tool_option("sizeVariation", &json!(4)); + assert_eq!(frame(&mut app), [false, true, false, true], "its size on Stylus Wheel"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 754f36cec6..68bf1806b6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4304,7 +4304,9 @@ already walks Image Trace. Short agent entry points: way. Brush Options offers Stylus Wheel for a Calligraphic or Scatter brush's Size and an Art brush's Width. The desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` - is installed; without it a Windows pen reads no wheel. The web build does not read it. `.ai` brush definitions read + is installed; without it a Windows pen reads no wheel. Windows opens the Wintab context only while the active tool + uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Eraser with a + value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps no wheel. The web build does not read it. `.ai` brush definitions read and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2d75b2e000..f256cdbec1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2109,7 +2109,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample` and `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From 8c97641c4eb3dc5292d1736322f323dd499c5b0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:07:06 -0800 Subject: [PATCH 37/63] Export for Screens: the format rows test sizes its window through Window Window takes an optional size (Window::sized), and the test that checks the format rows at the default and least window sizes runs its frames through it instead of its own copy of Window::run's frame loop. --- crates/ui-egui/src/dialogs/tests_screens.rs | 29 +++++++++------------ 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index b52e3408ed..8a73810d89 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -837,18 +837,25 @@ fn big_tiff_tags(bytes: &[u8]) -> Vec<(u16, u16, u32, u16)> { } /// Frames of the app's own window (`app.ui_ctx`, where its dialogs are) with the accessibility -/// tree, input events and a clock; each frame runs the dialog layer's pump after it. +/// tree, input events and a clock; each frame runs the dialog layer's pump after it. The window is +/// 1280 by 900 unless `sized` gives another size. #[derive(Default)] pub(super) struct Window { time: f64, + size: Option, } impl Window { + /// A window of `size` instead of the default 1280 by 900. + fn sized(size: egui::Vec2) -> Self { + Self { size: Some(size), ..Self::default() } + } + fn run(&mut self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { let ctx = app.ui_ctx.clone().expect("a test app has a window"); ctx.enable_accesskit(); self.time += 0.1; - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, self.size.unwrap_or(egui::vec2(1280.0, 900.0))); let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() }; // The window's frame with the app's frame input, as the hosts run it: the controls' commands reach the app. let out = crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)); @@ -1443,22 +1450,12 @@ fn the_format_rows_fit_the_right_column_at_the_default_and_least_window_sizes() // The default window, then the least size the desktop app's window takes. for (size, default) in [(egui::vec2(1280.0, 900.0), true), (egui::vec2(800.0, 500.0), false)] { let (mut app, _) = app(2, false); - let ctx = app.ui_ctx.clone().expect("a test app has a window"); - ctx.enable_accesskit(); - let mut time = 0.0; - let mut frame = |app: &mut VectorcraftApp| { - time += 0.1; - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); - let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; - let out = crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)); - super::host::pump(app, &ctx); - out - }; - frame(&mut app); + let mut w = Window::sized(size); + w.run(&mut app, vec![]); open(&mut app); set(&mut app, "formats", rows.clone()); - frame(&mut app); - let out = frame(&mut app); + w.run(&mut app, vec![]); + let out = w.run(&mut app, vec![]); let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); let rect = |n: &egui::accesskit::Node| { n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) From c71817638bc8e4c7795ecf336b4e92d1b061852b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 26 Nov 2026 09:07:33 +0700 Subject: [PATCH 38/63] Color Wheel: the contrast cache keys on tool_paints, which replaced bucket_paints #9100 replaced Session::bucket_paints with tool_paints(stroke), and #7718's contrast cache key still called bucket_paints, so main stopped compiling. The key now records whether the active tool paints with the proxy in front, the paint color.contrast measures. --- crates/ui-egui/src/panels/color_wheel.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 9b9b45ab6b..5cc220b272 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -927,7 +927,7 @@ fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option r.clone(), From 54c84108a1bc46f8957d2a0006fbda6c94f53a45 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:13:02 -0800 Subject: [PATCH 39/63] Dialogs: Split Into Grid keeps one pass's edits, and the Picked files test uses the shared frame Split Into Grid's fields edit a copy of the dialog values inside the grid and keep it only when the pass takes effect, as form::stacked does, so a measuring pass no longer changes the values the real pass reads. tests::script_dialogs::frame returns the last pass's output, and the Picked files group test reads the accessibility tree from it instead of running its own frame. --- crates/ui-egui/src/dialogs/path_ops.rs | 64 ++++++++++++---------- crates/ui-egui/src/tests/script_dialogs.rs | 10 ++-- crates/ui-egui/src/tests/script_run.rs | 5 +- 3 files changed, 43 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 091f5a4d34..58cdde452b 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -13,6 +13,7 @@ use craft::ui::layout::GridFit; use craft::ui::layout_components::Grid; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; +use craft::ui::runtime::measure; use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft::ui::text::{NumberField, NumberOutput}; use craft::ui::value_drag::SliderScale; @@ -200,38 +201,45 @@ fn split_grid(ui: &mut egui::Ui, f: &mut DialogFields, lengths: LengthUnits) -> ("rows", tl!("Rows:"), tl!("Height:"), "rowGutter", "totalHeight", 2.0), ("columns", tl!("Columns:"), tl!("Width:"), "columnGutter", "totalWidth", 2.0), ]; - Grid::new(&AXES) - .fit(GridFit::Fixed) - .id_salt("split-grid") - .show(ui, |ui, _| { - for (number, label, _, _, _, default) in axes { - let n = f.number(number).unwrap_or(default); - if let Some(v) = cell(ui, label, label.to_string(), false, n, None) { - f.set(number, v); - } + // The grid can run its body twice in a pass, so the body edits a copy, kept only from the run that takes effect. + let before = f.clone(); + let mut edited = None; + let shown = Grid::new(&AXES).fit(GridFit::Fixed).id_salt("split-grid").show(ui, |ui, _| { + let mut f = before.clone(); + for (number, label, _, _, _, default) in axes { + let n = f.number(number).unwrap_or(default); + if let Some(v) = cell(ui, label, label.to_string(), false, n, None) { + f.set(number, v); } - for (number, _, label, gutter, total, default) in axes { - let n = f.number(number).unwrap_or(default).max(1.0); - let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0); - let size = (f.number(total).unwrap_or(0.0) - gaps) / n; - if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) { - f.set(total, n * v + gaps); - } + } + for (number, _, label, gutter, total, default) in axes { + let n = f.number(number).unwrap_or(default).max(1.0); + let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0); + let size = (f.number(total).unwrap_or(0.0) - gaps) / n; + if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) { + f.set(total, n * v + gaps); } - for (_, axis, _, gutter, _, _) in axes { - let label = tl!("Gutter:"); - if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) { - f.set(gutter, v); - } + } + for (_, axis, _, gutter, _, _) in axes { + let label = tl!("Gutter:"); + if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) { + f.set(gutter, v); } - for (_, axis, _, _, total, _) in axes { - let label = tl!("Total:"); - if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) { - f.set(total, v); - } + } + for (_, axis, _, _, total, _) in axes { + let label = tl!("Total:"); + if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) { + f.set(total, v); } - }) - .output + } + if measure::effect(ui.ctx(), "Split Into Grid's fields edit their values") { + edited = Some(f); + } + }); + if let Some(edited) = edited { + *f = edited; + } + shown.output } /// Split Into Grid's rows: the grid and Add Guides. diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 94e1bb9311..7e90dba636 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -77,8 +77,8 @@ pub(super) fn open_blocker(app: &VectorcraftApp) { } /// One pass of the dialog host with `events`; a key pressed in it is let go in a second pass, as a -/// person lets go of it. -pub(super) fn frame(app: &VectorcraftApp, events: Vec) { +/// person lets go of it. Returns the last pass's output. +pub(super) fn frame(app: &VectorcraftApp, events: Vec) -> egui::FullOutput { let ctx = app.ui_ctx.clone().unwrap(); let dialogs = app.dialogs().unwrap(); let released: Vec = events @@ -92,10 +92,12 @@ pub(super) fn frame(app: &VectorcraftApp, events: Vec) { .collect(); let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let pressed = !released.is_empty(); + let mut last = egui::FullOutput::default(); for events in std::iter::once(events).chain(pressed.then_some(released)) { - let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); - out.textures_delta.clear(); + last = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); + last.textures_delta.clear(); } + last } pub(super) fn key(k: egui::Key) -> egui::Event { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fbb2e60bb7..b5c11b5c03 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -476,10 +476,7 @@ fn a_scripts_file_dialog_lists_several_picked_files_in_a_named_group() { let given = vec!["/picked/a.txt".to_string(), "/picked/b.txt".to_string()]; script_run::with_host(&app, |host, _| host.get_mut::().map(|d| d.add(given, true, false))).unwrap(); frame(&app, vec![]); - let ctx = app.ui_ctx.clone().unwrap(); - let dialogs = app.dialogs().unwrap(); - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); - let out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); + let out = frame(&app, vec![]); let update = out.platform_output.accesskit_update.expect("an accessibility tree"); let groups: Vec<_> = update.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Group).filter_map(|(_, node)| node.label()).collect(); From bd8e9002518fa35b9aa07936e5de33f32f44e56d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:15:43 -0800 Subject: [PATCH 40/63] Windows: the Blob Brush's Stylus Wheel size also opens the Wintab context The Blob Brush takes Stylus Wheel for its Size, and its tip already counts through Tool::reads_wheel. The test and the docs name it. --- crates/tools/src/draw2/gesture/tests.rs | 6 +++++- crates/ui-egui/src/stylus.rs | 2 +- docs/mcp.md | 6 +++--- docs/target-app-parity.md | 2 +- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 5f4adbf4e2..c8aa002add 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -4131,7 +4131,7 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { } #[test] -fn the_eraser_reads_the_wheel_only_with_a_value_on_stylus_wheel() { +fn a_tip_reads_the_wheel_only_with_a_value_on_stylus_wheel() { let (d, _) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let cx = cx(&d, &s, &p); @@ -4147,4 +4147,8 @@ fn the_eraser_reads_the_wheel_only_with_a_value_on_stylus_wheel() { t.set_option(&format!("{value}Mode"), &json!("pressure")); assert!(!t.reads_wheel(&cx), "{value} on Pressure"); } + let mut t = GestureTool::new("blobBrush"); + t.set_option("sizeMode", &json!("stylusWheel")); + t.set_option("sizeVariation", &json!(4)); + assert!(t.reads_wheel(&cx), "the Blob Brush's size on Stylus Wheel"); } diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 0491874822..dc3a9f5195 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -87,7 +87,7 @@ pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool { /// Tells the host whether the active tool reads an airbrush pen's finger wheel /// ([`crate::Services::stylus_wheel`]): the Paintbrush with a brush on Stylus Wheel, or -/// the Eraser with a value on it. The host is told at the first call and then each time the answer +/// the Blob Brush or the Eraser with a value on it. The host is told at the first call and then each time the answer /// changes; the tool is asked again only when the document, its current brush, the tool or its /// options change. /// diff --git a/docs/mcp.md b/docs/mcp.md index b8b06d9d8b..938dedf84d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4477,9 +4477,9 @@ already walks Image Trace. Short agent entry points: desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11, from AppKit (`tangentialPressure`) on macOS, and on Windows from the tablet driver's Wintab interface (`pkTangentPressure`) of an airbrush pen, when `Wintab32.dll` is installed; without it a Windows pen reads no wheel. Windows opens the Wintab context only while the active tool - uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Eraser with a - value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps no wheel. The web build does not read it. `.ai` brush definitions read - and write the wheel as variation code 3. + uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Blob Brush or + the Eraser with a value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps + no wheel. The web build does not read it. `.ai` brush definitions read and write the wheel as variation code 3. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5c06d423e8..d05c441153 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2120,7 +2120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From 0f7844ecb6bdcf9e03056aef50d9a10136bd18d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:22:36 -0800 Subject: [PATCH 41/63] Preferences: Apply after entering Touch keeps Touch's task bar After an Apply that entered Touch, the Enable Contextual Task Bar row kept the value given to the workspace left, and the next Apply wrote it to Touch. The row now shows the task bar in use after each Apply. When OK leaves Touch, the workspace returned to takes the row only when it was edited; otherwise it keeps the value it left with. --- crates/ui-egui/src/prefs_dialog/model.rs | 10 +++++- crates/ui-egui/src/prefs_dialog/tests.rs | 46 ++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 0d03652289..25740a3dce 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -436,14 +436,19 @@ impl PreferencesDraft for Live<'_> { if before_switch && let Some(on) = self.w.draft.get::("__taskBar") { self.app.ui.task_bar = on; } + let was_touch = crate::workspaces::is_current(&self.app.ui, crate::workspaces::TOUCH); if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(self.app, self.app.touch_screen); } + // When OK leaves Touch, the workspace returned to takes the row only when it changed since the window opened or + // last applied; otherwise it keeps its own. + let left_touch = was_touch && !crate::workspaces::is_current(&self.app.ui, crate::workspaces::TOUCH); + let task_bar_row = self.w.draft.get::("__taskBar").filter(|on| !left_touch || self.w.opened.get::("__taskBar") != Some(*on)); let flag = |key: &str, now: bool| self.w.draft.get::(key).unwrap_or(now); let (smart_guides, snap_to_grid, task_bar) = ( flag("__smartGuides", self.app.ui.view.smart_guides), flag("__snapToGrid", self.app.ui.view.snap_to_grid), - if before_switch { self.app.ui.task_bar } else { flag("__taskBar", self.app.ui.task_bar) }, + if before_switch { self.app.ui.task_bar } else { task_bar_row.unwrap_or(self.app.ui.task_bar) }, ); self.app.ui.view.smart_guides = smart_guides; self.app.ui.view.snap_to_grid = snap_to_grid; @@ -451,6 +456,9 @@ impl PreferencesDraft for Live<'_> { crate::original_editor::commit(self.app); super::snapshot(self.app); self.app.prefs_changed = true; + // The row shows the task bar in use: after OK enters Touch, that is Touch's, not the value the workspace left + // took, so a later Apply does not give the workspace left's value to Touch. + self.w.draft.set("__taskBar", &self.app.ui.task_bar); self.w.opened = self.w.draft.clone(); Ok(()) } diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 1b09df5cb0..5930e2def0 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -495,6 +495,52 @@ fn ok_sets_the_task_bar_in_the_workspace_outside_touch() { assert!(left_task_bar(&b, TOUCH), "Touch keeps its own task bar"); } +/// After an Apply that enters Touch, the task bar row shows Touch's task bar: a later Apply that leaves the row +/// unedited keeps it, and an edit or a reset of the row reaches it. Leaving Touch with the row unedited gives the +/// workspace returned to the value it left with. +#[test] +fn apply_after_entering_touch_keeps_touchs_task_bar() { + use crate::workspaces::{TOUCH, is_current, switch}; + use craft::ui::patterns::preferences::PreferencesDraft as _; + let apply = |a: &mut VectorcraftApp| { + let mut w = a.prefs.take().expect("Preferences is open"); + let r = model::Live { app: &mut *a, w: &mut w }.apply(); + a.prefs = Some(w); + r.unwrap(); + }; + let mut a = app(); + a.touch_screen = true; + a.run("prefs.set", json!({"key": "touchWorkspace", "value": false})).unwrap(); + switch(&mut a, "Essentials Classic").unwrap(); + a.ui.task_bar = true; + open(&mut a, Some("General")); + reset_preferences(&mut a, PromptChoice::Proceed); + assert_eq!(field(&a, "__taskBar"), json!(false), "the reset row differs from Touch's task bar"); + apply(&mut a); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "Touch keeps its own task bar"); + set_field(&mut a, "keyboardIncrement", json!(9)).unwrap(); + apply(&mut a); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "an Apply without a task bar edit keeps Touch's task bar"); + assert_eq!(field(&a, "__taskBar"), json!(true), "the row shows Touch's task bar"); + set_field(&mut a, "__taskBar", json!(false)).unwrap(); + apply(&mut a); + assert!(!a.ui.task_bar, "an edit to the row reaches Touch"); + + // Reset Preferences in Touch gives Touch its saved value, the value the row showed before the edit. + reset_preferences(&mut a, PromptChoice::Proceed); + apply(&mut a); + assert!(is_current(&a.ui, TOUCH)); + assert!(a.ui.task_bar, "the reset reaches Touch"); + + // Leaving Touch with the row unedited: the workspace returned to keeps the value it left with. + set_field(&mut a, "touchWorkspace", json!(false)).unwrap(); + apply(&mut a); + assert!(is_current(&a.ui, "Essentials Classic")); + assert!(!a.ui.task_bar, "the workspace returned to keeps its reset value"); +} + /// A Touch return marker left over from an earlier automatic switch (Window › Workspace does not clear it) does not /// change where OK puts the task bar: OK enters Touch from the workspace it leaves, so that workspace takes the row /// and Touch keeps its own. From dd64c283e84e8c988a1c9201752a8f89e5263990 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:46:11 +0530 Subject: [PATCH 42/63] History tests: use the shared panel harness --- crates/ui-egui/src/panels/history.rs | 199 ++++++++++------------ crates/ui-egui/src/tests/panel_harness.rs | 20 +++ 2 files changed, 110 insertions(+), 109 deletions(-) diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 66a519eac7..ddd4fd7887 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -284,6 +284,8 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option mod tests { use super::*; use crate::i18n::LangExt; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; /// A step named after a style lists the template's translation with the style's name in it as /// the document holds it, also when the name looks like a template, like a step with a row of @@ -401,24 +403,9 @@ mod tests { let mut app = app_with_two_rectangles(); app.session.execute("edit.undo", &json!({})).unwrap(); let source = app.session.active().unwrap().doc.clone(); - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - egui_extras::install_image_loaders(&ctx); - let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(240.0, 400.0))); - let frame = |app: &mut VectorcraftApp, events: Vec| { - let out = crate::testing::part_frame(app, &ctx, egui::RawInput { events, screen_rect: screen, ..Default::default() }, show); - out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() - }; - frame(&mut app, vec![]); - let nodes = frame(&mut app, vec![]); - // PLAN: the button is named by the framework's words ("Create New Document from Current State"); the name is - // matched by the words it holds. - let button = nodes.iter().map(|(_, n)| n).find(|n| n.label().is_some_and(|l| l.contains("New Document"))).expect("the button"); - let at = button.bounds().expect("its bounds"); - let at = egui::pos2((at.x0 + at.x1) as f32 / 2.0, (at.y0 + at.y1) as f32 / 2.0); - let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); - frame(&mut app, vec![press(false)]); + let mut panel = Panel::new(app, show); + panel.click("Create New Document from Current State"); + let app = panel.app(); assert_eq!(app.session.documents().len(), 2); assert_eq!(app.session.active_index(), Some(1), "the new document is the active one"); let st = app.session.active().unwrap(); @@ -427,56 +414,45 @@ mod tests { assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source), "the source stays at that state"); } - fn history_harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + fn history_harness(app: VectorcraftApp) -> Panel { crate::i18n::set_current(crate::i18n::Lang::EN); - let mut h = egui_kittest::Harness::builder() - .with_size(egui::vec2(260.0, 400.0)) - .with_context_setup(crate::testing::install) - .build_ui_state(|ui, app| show(app, ui), app); - h.run_steps(2); - h + let mut panel = Panel::new(app, show); + panel.room(egui::vec2(260.0, 400.0)); + panel.frame(); + panel } - fn row_menu_harness(app: VectorcraftApp, row: usize) -> egui_kittest::Harness<'static, VectorcraftApp> { - use egui_kittest::kittest::Queryable; - let mut h = history_harness(app); - let pos = h.get_all_by_role(egui::accesskit::Role::ListItem).nth(row).expect("history row").rect().center(); - h.event(egui::Event::PointerMoved(pos)); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }); - } - h.run_steps(2); - h + fn row_menu_harness(app: VectorcraftApp, row: usize) -> Panel { + let mut panel = history_harness(app); + panel.secondary_click_nth(Role::LIST_ITEM, row); + panel } - fn focus_previous_state(h: &mut egui_kittest::Harness<'static, VectorcraftApp>) { - use egui_kittest::kittest::{NodeT, Queryable}; + fn focus_previous_state(panel: &mut Panel) { for _ in 0..4 { - h.key_press(egui::Key::Tab); - h.run_steps(1); - if h.get_all_by_role(egui::accesskit::Role::ListItem).nth(2).unwrap().accesskit_node().is_focused() { + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + if panel.focused_nth(Role::LIST_ITEM, 2) { break; } } - assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(2).unwrap().accesskit_node().is_focused()); - h.key_press(egui::Key::ArrowUp); - h.run_steps(2); - assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(1).unwrap().accesskit_node().is_focused()); - assert_eq!(depth(h.state()), (2, 0), "moving focus must not step history"); + assert!(panel.focused_nth(Role::LIST_ITEM, 2)); + panel.key(egui::Key::ArrowUp, egui::Modifiers::NONE); + assert!(panel.focused_nth(Role::LIST_ITEM, 1)); + assert_eq!(depth(&panel.app()), (2, 0), "moving focus must not step history"); } #[test] fn keyboard_activation_steps_to_the_focused_state() { let mut h = history_harness(app_with_two_rectangles()); focus_previous_state(&mut h); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert_eq!(depth(h.state()), (1, 1)); - assert_eq!(h.state().session.active().unwrap().doc.layers[0].children().unwrap().len(), 1); + h.key(egui::Key::Enter, egui::Modifiers::NONE); + h.frame(); + h.frame(); + assert_eq!(depth(&h.app()), (1, 1)); + assert_eq!(h.app().session.active().unwrap().doc.layers[0].children().unwrap().len(), 1); } #[test] fn switching_documents_dismisses_the_row_menu_without_clearing_either_history() { - use egui_kittest::kittest::Queryable; let mut app = app_with_two_rectangles(); app.session.execute("edit.undo", &json!({})).unwrap(); app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap(); @@ -486,114 +462,116 @@ mod tests { app.session.execute("edit.undo", &json!({})).unwrap(); app.session.execute("document.activate", &json!({"index": 0})).unwrap(); let mut h = row_menu_harness(app, 1); - h.get_by_label("Clear History"); - h.state_mut().session.execute("document.activate", &json!({"index": 1})).unwrap(); - h.run_steps(2); - assert!(h.query_by_label("Clear History").is_none(), "the other document must not inherit the popup"); - h.state_mut().session.execute("document.activate", &json!({"index": 0})).unwrap(); - h.run_steps(2); - assert!(h.query_by_label("Clear History").is_none(), "switching back must not revive the popup"); - for st in h.state().session.documents() { + assert!(h.shows("Clear History")); + h.app().session.execute("document.activate", &json!({"index": 1})).unwrap(); + h.frame(); + h.frame(); + assert!(!h.shows("Clear History"), "the other document must not inherit the popup"); + h.app().session.execute("document.activate", &json!({"index": 0})).unwrap(); + h.frame(); + h.frame(); + assert!(!h.shows("Clear History"), "switching back must not revive the popup"); + for st in h.app().session.documents() { assert_eq!((st.history.undo.len(), st.history.redo.len()), (1, 1)); } } #[test] fn keyboard_opens_dismisses_and_activates_the_focused_rows_menu() { - use egui_kittest::kittest::{NodeT, Queryable}; let app = app_with_two_rectangles(); let source = app.session.active().unwrap().doc.clone(); let wanted = app.session.active().unwrap().history.undo[1].doc.clone(); let mut h = history_harness(app); focus_previous_state(&mut h); - h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); - h.run_steps(2); - assert!(h.get_by_label("New Document from State").accesskit_node().is_focused()); - assert_eq!(depth(h.state()), (2, 0), "opening does not step"); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.query_by_label("New Document from State").is_none()); - assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(1).unwrap().accesskit_node().is_focused()); - h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); - h.run_steps(2); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert_eq!(h.state().session.documents().len(), 2); - assert_eq!(h.state().session.active().unwrap().doc.layers, wanted.layers); - assert!(Arc::ptr_eq(&h.state().session.documents()[0].doc, &source)); - assert_eq!(h.state().session.documents()[0].history.undo.len(), 2); + h.key(egui::Key::F10, egui::Modifiers::SHIFT); + h.frame(); + h.frame(); + assert!(h.focused("New Document from State")); + assert_eq!(depth(&h.app()), (2, 0), "opening does not step"); + h.key(egui::Key::Escape, egui::Modifiers::NONE); + h.frame(); + h.frame(); + assert!(!h.shows("New Document from State")); + assert!(h.focused_nth(Role::LIST_ITEM, 1)); + h.key(egui::Key::F10, egui::Modifiers::SHIFT); + h.frame(); + h.frame(); + h.key(egui::Key::Enter, egui::Modifiers::NONE); + h.frame(); + h.frame(); + assert_eq!(h.app().session.documents().len(), 2); + assert_eq!(h.app().session.active().unwrap().doc.layers, wanted.layers); + assert!(Arc::ptr_eq(&h.app().session.documents()[0].doc, &source)); + assert_eq!(h.app().session.documents()[0].history.undo.len(), 2); } #[test] fn right_clicking_an_earlier_state_opens_its_menu_without_stepping() { - use egui_kittest::kittest::Queryable; let h = row_menu_harness(app_with_two_rectangles(), 1); - h.get_by_label("New Document from State"); - h.get_by_label("Step to This State"); - h.get_by_label("Clear History"); - assert_eq!(depth(h.state()), (2, 0)); + assert!(h.shows("New Document from State")); + assert!(h.shows("Step to This State")); + assert!(h.shows("Clear History")); + assert_eq!(depth(&h.app()), (2, 0)); } #[test] fn the_row_menu_makes_a_new_document_from_that_snapshot() { - use egui_kittest::kittest::Queryable; let mut app = app_with_two_rectangles(); app.session.execute("edit.undo", &json!({})).unwrap(); let snapshot = app.session.active().unwrap().doc.clone(); app.session.execute("edit.redo", &json!({})).unwrap(); let source = app.session.active().unwrap().doc.clone(); let mut h = row_menu_harness(app, 1); - h.get_by_label("New Document from State").click(); - h.run_steps(2); - let app = h.state(); + h.click_menu_item("New Document from State"); + h.frame(); + h.frame(); + let app = h.app(); assert_eq!(app.session.documents().len(), 2); assert_eq!(app.session.active_index(), Some(1)); let st = app.session.active().unwrap(); assert_eq!(st.doc.layers, snapshot.layers, "the historic artwork"); assert!(st.is_dirty()); - assert_eq!(depth(app), (0, 0)); + assert_eq!(depth(&app), (0, 0)); assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source)); assert_eq!(app.session.documents()[0].history.undo.len(), 2); } #[test] fn the_row_menu_steps_backward_and_forward_to_the_target() { - use egui_kittest::kittest::{NodeT, Queryable}; for (current, target) in [(2, 0), (0, 2), (1, 1)] { let mut app = app_with_two_rectangles(); for _ in current..2 { app.session.execute("edit.undo", &json!({})).unwrap(); } let mut h = row_menu_harness(app, target); - let item = h.get_by_label("Step to This State"); - assert_eq!(item.accesskit_node().is_disabled(), current == target); - item.click(); - h.run_steps(2); - assert_eq!(depth(h.state()), (target, 2 - target)); - assert_eq!(h.state().session.active().unwrap().doc.layers[0].children().unwrap().len(), target); + assert_eq!(h.menu_item_enabled("Step to This State"), current != target); + h.click_menu_item("Step to This State"); + h.frame(); + h.frame(); + assert_eq!(depth(&h.app()), (target, 2 - target)); + assert_eq!(h.app().session.active().unwrap().doc.layers[0].children().unwrap().len(), target); } } #[test] fn the_row_menu_clears_undo_and_redo_without_changing_art() { - use egui_kittest::kittest::{NodeT, Queryable}; let mut app = app_with_two_rectangles(); app.session.execute("edit.undo", &json!({})).unwrap(); let source = app.session.active().unwrap().doc.clone(); let mut h = row_menu_harness(app, 0); - h.get_by_label("Clear History").click(); - h.run_steps(2); - assert_eq!(depth(h.state()), (0, 0)); - assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &source)); + h.click_menu_item("Clear History"); + h.frame(); + h.frame(); + assert_eq!(depth(&h.app()), (0, 0)); + assert!(std::sync::Arc::ptr_eq(&h.app().session.active().unwrap().doc, &source)); let mut empty = app_with_two_rectangles(); empty.session.execute("edit.clearHistory", &json!({})).unwrap(); let h = row_menu_harness(empty, 0); - assert!(h.get_by_label("Clear History").accesskit_node().is_disabled()); + assert!(!h.menu_item_enabled("Clear History")); } #[test] fn stepping_settles_typing_and_follows_the_snapshot_when_rows_shift() { - use egui_kittest::kittest::Queryable; for (limit, row) in [(10, 0), (2, 1)] { let mut app = app_with_two_rectangles(); app.session.active_mut().unwrap().history.limit = limit; @@ -602,9 +580,11 @@ mod tests { app.session.begin_interaction("Typing").unwrap(); app.session.preview("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); let mut h = row_menu_harness(app, row); - h.get_by_label("Step to This State").click(); - h.run_steps(2); - let st = h.state().session.active().unwrap(); + h.click_menu_item("Step to This State"); + h.frame(); + h.frame(); + let app = h.app(); + let st = app.session.active().unwrap(); assert_eq!(st.doc.layers, wanted.layers, "limit {limit}, row {row}"); assert!(st.interaction.is_none()); assert_eq!(st.history.undo.len(), 0); @@ -613,7 +593,6 @@ mod tests { #[test] fn copying_a_state_resolves_pending_tool_edits_without_copying_a_neighbor() { - use egui_kittest::kittest::Queryable; use vectorcraft_tools::{PointerEvent, PointerKind}; for (row, finishes_while_open) in [(0, false), (1, false), (0, true), (1, true)] { @@ -637,13 +616,15 @@ mod tests { assert!(app.session.tool_waiting()); let mut h = row_menu_harness(app, row); if finishes_while_open { - let requests = h.state_mut().session.finish_tool_edit(); - crate::canvas::apply_requests(h.state_mut(), requests); - h.run_steps(2); + let requests = h.app().session.finish_tool_edit(); + crate::canvas::apply_requests(&mut h.app(), requests); + h.frame(); + h.frame(); } - h.get_by_label("New Document from State").click(); - h.run_steps(2); - let app = h.state(); + h.click_menu_item("New Document from State"); + h.frame(); + h.frame(); + let app = h.app(); assert!(!app.session.tool_waiting()); if row == 0 { assert_eq!(app.session.documents().len(), 1, "the pruned snapshot must not copy its neighbor"); diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 0b36cec615..101c606d52 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -259,6 +259,21 @@ impl Panel { /// A right click on the control named `name`. pub(crate) fn secondary_click(&mut self, name: &str) { let at = self.find(name).center(); + self.secondary_click_at(at); + } + + /// Right-clicks the zero-based control of `role`, including rows with identical names. + pub(crate) fn secondary_click_nth(&mut self, role: craft::ui::contract::Role, index: usize) { + self.frame(); + let at = self.look_nth(role, index).center(); + self.secondary_click_at(at); + } + + fn look_nth(&self, role: craft::ui::contract::Role, index: usize) -> Target { + self.fixture.by_role(role).into_iter().nth(index).unwrap_or_else(|| panic!("no {role:?} at {index} in {:?}", self.names())) + } + + fn secondary_click_at(&mut self, at: Pos2) { let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }; self.frame_with(vec![Event::PointerMoved(at)]); self.frame_with(vec![button(true)]); @@ -360,4 +375,9 @@ impl Panel { pub(crate) fn focused(&self, name: &str) -> bool { self.fixture.tree().focused_key() == self.look(name).node } + + /// Whether the zero-based control of `role` has focus, including rows with identical names. + pub(crate) fn focused_nth(&self, role: craft::ui::contract::Role, index: usize) -> bool { + self.fixture.tree().focused_key() == self.look_nth(role, index).node + } } From 924c4409bb0faf3a5b9a11d0a8381e4a0b9e87f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:43:42 -0800 Subject: [PATCH 43/63] Preferences test: run the reset frame through testing::app_frame The test of a prefs.reset run outside VectorcraftApp::run now draws its frame with crate::testing::app_frame on the window's context. --- crates/ui-egui/src/prefs_dialog/tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 5930e2def0..daad8a6bef 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -569,9 +569,8 @@ fn prefs_reset_outside_run_resets_the_ui_only_rows_in_the_next_frame() { let default = ui_rows(&a); set_ui_rows(&mut a, (!default.0, !default.1, !default.2)); a.session.execute("prefs.reset", &json!({})).unwrap(); - let ctx = crate::testing::ui_context(); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| a.tick(ui.ctx())); - out.textures_delta.clear(); + let ctx = a.ui_ctx.clone().expect("a window context"); + crate::testing::app_frame(&mut a, &ctx, egui::RawInput::default()); assert_eq!(ui_rows(&a), default); // Before the next command switches workspaces: the workspace left keeps the reset value. From 476437f29dd11064dd18ff53ed1cf1487ce5d199 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:03:30 -0800 Subject: [PATCH 44/63] Tests: the no-document canvas test runs its frames through part_frame a_canvas_frame_without_a_document_releases_the_text_nodes creates its context once and runs each frame through crate::testing::part_frame with crate::canvas::show, in place of its own frame loop. --- crates/ui-egui/src/canvas/marks/tests.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 52fc5d67dd..29336a8ad8 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -126,11 +126,10 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() { /// shows the Home screen or, with Show The Home Screen When No Documents Are Open off, an empty window. #[test] fn a_canvas_frame_without_a_document_releases_the_text_nodes() { + let ctx = crate::testing::ui_context(); let frame = |app: &mut VectorcraftApp| { - let ctx = crate::testing::ui_context(); let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| crate::canvas::show(app, ui)); - out.textures_delta.clear(); + crate::testing::part_frame(app, &ctx, raw, crate::canvas::show); }; for home in [true, false] { let mut app = app(); From 6b7b780c22f83c91ae3a5c9a2902e302f15f6e70 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:09:41 -0800 Subject: [PATCH 45/63] Color Wheel: contrast measures a painting tool's color without the selection's drawing While the Live Paint Bucket (or the Shape Builder, for the fill) is the active tool, the Fill and Stroke proxies show the color the tool paints with. color.contrast still took the opacity and blend modes from the selected objects, so it rated the bucket's color at an opacity it is not drawn with, and refused to answer when the selected objects were drawn differently. It now draws the tool's color in Normal mode, at `opacity` or fully opaque, as for a given `color`. Docs: docs/mcp.md and the command's params text. --- crates/engine/src/cmd/colorcmds.rs | 7 ++++--- crates/engine/src/tests/colorcontrast.rs | 25 ++++++++++++++++++++++++ docs/mcp.md | 2 ++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 063c25f4b2..a7827e135b 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", always, contrast ), @@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re .transpose() }; let drawing; - // Selected objects that share a color but draw it differently have no one answer. - if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) { + // Selected objects that share a color but draw it differently have no one answer. While the + // active tool paints with the proxy's color, the selection does not draw it. + if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) { let item = s.appearance_item(); // Every painted object inside a selected group counts, as the proxy's color comes from all, // except hidden ones and those inside a hidden group, which draw nothing. The first shown diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 39f496557d..9b0147174e 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -68,6 +68,31 @@ fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() { assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}"); } +/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the +/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no +/// error. +#[test] +fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap(); + let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let bucket = s.execute("color.contrast", &json!({})).unwrap(); + assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}"); + assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}"); + // A second selected object drawn at another opacity does not make the answer ambiguous. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let both = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}"); +} + #[test] fn a_translucent_group_counts_for_the_art_inside_it() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..ccb877b571 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1222,6 +1222,8 @@ the art below it inside the object, groups and layer around it, the object's row the background when `against` or `opacity` is given; inside an object, group or layer that isolates its blending, the modes blend only with the art it holds); `opacity` (0 to 100) replaces that opacity. A given `color` is drawn in Normal mode, at `opacity` or fully opaque. +While the active tool paints with the proxy's color (the Live Paint Bucket, the Shape Builder's fill), that color is +drawn the same way, and the selected objects' opacities and blend modes do not apply. `against` takes a color, or `"below"` (the default, also for `null`): the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it (locked art, opacity, blend modes and images included; template layers and guides left out, as exports leave them out; the artboard's white where nothing From 9ddded7242b185eb036addd9149fcce24415fc72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:17:15 -0800 Subject: [PATCH 46/63] Flattener Preview: Alt-click reads Alt from the pointer frame, so a latched Alt zooms out The click's Alt comes from the framework's pointer frame (pick_mods), which adds the modifiers the app latches from the Modifier Keys panel, instead of raw egui input. --- .../ui-egui/src/panels/flattener_preview.rs | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/flattener_preview.rs b/crates/ui-egui/src/panels/flattener_preview.rs index da00eb4c48..e2c724fe2f 100644 --- a/crates/ui-egui/src/panels/flattener_preview.rs +++ b/crates/ui-egui/src/panels/flattener_preview.rs @@ -292,7 +292,7 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut Ui, highlight: egui::Color32, .show(ui); *view = match out.clicked { Some(at) => { - let factor = if ui.input(|i| i.modifiers.alt) { 0.5 } else { 2.0 }; + let factor = if craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt { 0.5 } else { 2.0 }; zoomed_about(&out.shown, at, size, out.response.rect.size(), factor) } // The view as drawn, so the zoom row steps from what is on screen while the pane fits. @@ -525,6 +525,42 @@ mod tests { assert!(view(&app).fit, "an Alt-click to the fit returns to fit"); } + #[test] + fn a_click_with_alt_latched_by_the_app_zooms_out() { + let mut app = app(); + let mut frames = craft::ui::testing::Frames::new(); + let mut pane = None; + for _ in 0..60 { + frames.frame(Vec::new(), |ui| show(&mut app, ui)); + let tree = frames.tree(); + pane = tree + .keys() + .into_iter() + .filter(|key| tree.name_of(*key) == Some("Flattener Preview")) + .filter_map(|key| tree.bounds_of(key)) + .max_by(|a, b| a.area().total_cmp(&b.area())); + if pane.is_some() { + break; + } + } + let well = pane.unwrap_or_else(|| panic!("no preview pane")); + let at = well.center(); + let primary = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let click = |frames: &mut craft::ui::testing::Frames, app: &mut VectorcraftApp| { + frames.advance(2.0); + frames.frame(vec![egui::Event::PointerMoved(at), primary(true)], |ui| show(app, ui)); + frames.frame(vec![primary(false)], |ui| show(app, ui)); + frames.idle(1, |ui| show(app, ui)); + }; + click(&mut frames, &mut app); + assert!(!app.flattener_preview.view.fit, "a click zooms in"); + // Alt held for the user by the app (the Modifier Keys panel), with no Alt key down. + frames.latched(craft::keymap::Mods { alt: true, ..Default::default() }); + click(&mut frames, &mut app); + assert!(app.flattener_preview.view.fit, "a click with Alt latched zooms back out to fit"); + } + #[test] fn click_zoom_stays_inside_the_zoom_range() { let (app, mut fixture, well) = shown_pane(); From 5ff353a23b32b89371e623018da8bd1cb2b61273 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:47:35 -0800 Subject: [PATCH 47/63] Windows: the Wintab reader keeps each pen's end and asks a failed cursor query again - Each pen's end is kept by its pointer id, so only the same pen turning over starts the readings afresh; another pen's message with the other end does not. - A cursor whose WTInfoW query failed is asked again 2 s of the message clock later, and only a cursor the driver describes without a wheel is cached as having none. - Whether the app is active is asked again right before WTOpenW, after the close and WTInfoW calls before it. - docs/target-app-parity.md: a pen first reads the wheel from a packet within 200 ms of its message, then holds the readings until they start afresh. --- apps/vectorcraft/src/windows_wintab.rs | 192 ++++++++++++++++++++----- docs/target-app-parity.md | 2 +- 2 files changed, 154 insertions(+), 40 deletions(-) diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index be43f918f2..13fe249a06 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -153,6 +153,8 @@ const MAX_DEVICES: u32 = 16; const MAX_SKEW_MS: u32 = 200; /// At most this many cursors' readings are kept. const MAX_READINGS: usize = 4; +/// At most this many pens' ends are kept. +const MAX_PENS: usize = 16; /// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, /// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on @@ -247,6 +249,52 @@ fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { found.next().is_none().then_some(d) } +/// What the driver said about a cursor's wheel range. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Lookup { + /// The range, or `None` for a cursor the driver describes without a wheel. + Known(Option), + /// A `WTInfoW` call failed at this message time. + Failed { at: u32 }, +} + +/// Each cursor's wheel range, as the driver reported it, until the driver's information changes. +#[derive(Clone, Debug, Default)] +struct Cursors(Vec<(u32, Lookup)>); + +impl Cursors { + /// The wheel range of `cursor` for a packet at the message time `time`, asking the driver with + /// `query` the first time, or again once [`retry_due`] after a query that failed (`Err`). + /// Until then a cursor whose query failed reads no wheel. + fn axis(&mut self, cursor: u32, time: u32, query: impl FnOnce() -> Result, ()>) -> Option { + if let Some(i) = self.0.iter().position(|(c, _)| *c == cursor) { + match self.0[i].1 { + Lookup::Known(axis) => return axis, + Lookup::Failed { at } if !retry_due(at, time) => return None, + Lookup::Failed { .. } => { + self.0.remove(i); + } + } + } + let lookup = match query() { + Ok(axis) => Lookup::Known(axis), + Err(()) => Lookup::Failed { at: time }, + }; + if self.0.len() >= MAX_READINGS * 4 { + self.0.remove(0); + } + self.0.push((cursor, lookup)); + match lookup { + Lookup::Known(axis) => axis, + Lookup::Failed { .. } => None, + } + } + + fn clear(&mut self) { + self.0.clear(); + } +} + /// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. fn near(a: u32, b: u32) -> bool { (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS @@ -269,8 +317,10 @@ struct Reading { #[derive(Clone, Debug, Default)] struct Readings { list: Vec, - /// The end of the pen the last pointer message read, `Some(true)` for the eraser end. - eraser: Option, + /// The pointer id of each pen whose pointer messages were read since the readings started + /// afresh, with the end its last message read (`true` for the eraser end), at most + /// [`MAX_PENS`] of them. + ends: Vec<(u32, bool)>, /// The pointer id of the pen whose message first read the wheel since the readings started /// afresh; another pen's messages read none. pen: Option, @@ -322,7 +372,7 @@ impl Readings { /// could not be read, the context's queue overflowed, or the context closed. fn forget(&mut self) { self.list.clear(); - self.eraser = None; + self.ends.clear(); self.pen = None; self.cursor = None; } @@ -339,16 +389,25 @@ impl Readings { /// readings, the one cursor read since they started afresh, however long ago its last packet /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, /// or the cursor has read only 0 since the readings started afresh, or another pen's message - /// read a wheel first since then, or the pen read another cursor's wheel since then. A turn to - /// the other end starts them afresh first. + /// read a wheel first since then, or the pen read another cursor's wheel since then. The same + /// pen's turn to its other end starts them afresh first; another pen's message with another end + /// does not. fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { if self.pen.is_some_and(|p| p != pen) { return None; } - if self.eraser.is_some_and(|e| e != eraser) { + if self.ends.iter().any(|&(p, e)| p == pen && e != eraser) { self.forget(); } - self.eraser = Some(eraser); + match self.ends.iter_mut().find(|(p, _)| *p == pen) { + Some(end) => end.1 = eraser, + None => { + if self.ends.len() >= MAX_PENS { + self.ends.remove(0); + } + self.ends.push((pen, eraser)); + } + } let r = match self.list.as_slice() { [one] if self.pen == Some(pen) => one, list => { @@ -517,10 +576,11 @@ impl Notices { } /// Opens a context with `open` only when `hook` put the window procedure that notes the driver's -/// notices in front of the window's own; otherwise opens none, and the window is tried again as +/// notices in front of the window's own and, asked after every other driver call, this app is +/// still the active one (`active`); otherwise opens none, and the window is tried again as /// [`next_context`] says. -fn hooked_open(hook: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { - if hook() { open() } else { None } +fn hooked_open(hook: impl FnOnce() -> bool, active: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() && active() { open() } else { None } } /// What a message does to the readings and the context. @@ -586,9 +646,10 @@ mod win { use windows::core::{PCWSTR, s, w}; use super::{ - Axis, CSR_PKTDATA, CSR_TYPE, Current, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, MAX_INDEX, - MAX_READINGS, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, WTI_INTERFACE, Wheel, - calls_driver, configure, decode, device_of, hooked_open, message, next_context, retry_due, unused_context, wheel_axis, + Axis, CSR_PKTDATA, CSR_TYPE, Current, Cursors, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, + MAX_INDEX, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, PK_TANGENT_PRESSURE, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, + WTI_INTERFACE, Wheel, calls_driver, configure, decode, device_of, hooked_open, is_airbrush, message, next_context, retry_due, unused_context, + wheel_axis, }; /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). @@ -621,8 +682,7 @@ mod win { /// The window an open was last tried for, and the message time it was tried at /// ([`next_context`]). tried: Option<(*mut c_void, u32)>, - /// Each cursor's wheel range, as the driver reported it. - cursors: Vec<(u32, Option)>, + cursors: Cursors, readings: Readings, } @@ -821,21 +881,27 @@ mod win { (wrote == N * 4).then_some(out) } - /// The wheel range of `cursor`, `None` for a cursor without one or one the driver does not - /// describe. - fn cursor_axis(api: Api, cursor: u32) -> Option { + /// The wheel range of `cursor`: `Ok(None)` for a cursor the driver describes without one, and + /// `Err` when a `WTInfoW` call it needs fails. + fn cursor_axis(api: Api, cursor: u32) -> Result, ()> { if cursor >= MAX_INDEX { - return None; + return Ok(None); } - let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE)?; - let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA)?; - let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES)?; + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE).ok_or(())?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA).ok_or(())?; + if !is_airbrush(csr_type) || csr_pktdata & PK_TANGENT_PRESSURE == 0 { + return Ok(None); + } + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES).ok_or(())?; let mut devices = vec![]; for d in 0..count.min(MAX_DEVICES) { - devices.push((info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR)?[0], info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES)?[0])); + let [first] = info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR).ok_or(())?; + let [n] = info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES).ok_or(())?; + devices.push((first, n)); } - let device = u32::try_from(device_of(cursor, &devices)?).ok()?; - wheel_axis(csr_type, csr_pktdata, info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE)) + let Some(device) = device_of(cursor, &devices).and_then(|d| u32::try_from(d).ok()) else { return Ok(None) }; + let range = info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE).ok_or(())?; + Ok(wheel_axis(csr_type, csr_pktdata, Some(range))) } /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. @@ -912,8 +978,10 @@ mod win { self.tried = Some((owner, time)); let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; configure(&mut words); + // Whether the app is active is asked again here, after the close and `WTInfoW` above. let handle = hooked_open( || subclass(owner), + is_active, || { // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for // the call. @@ -930,16 +998,8 @@ mod win { self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) } - fn axis(&mut self, api: Api, cursor: u32) -> Option { - if let Some(&(_, axis)) = self.cursors.iter().find(|(c, _)| *c == cursor) { - return axis; - } - let axis = cursor_axis(api, cursor); - if self.cursors.len() >= MAX_READINGS * 4 { - self.cursors.remove(0); - } - self.cursors.push((cursor, axis)); - axis + fn axis(&mut self, api: Api, cursor: u32, time: u32) -> Option { + self.cursors.axis(cursor, time, || cursor_axis(api, cursor)) } } @@ -967,7 +1027,7 @@ mod win { // SAFETY: the handle is the open context's, and `buf` holds more bytes than a // packet of every field. let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; - let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor))); + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor, msg.time))); s.readings.read(read, msg.time); } Message::Forget { ctx } => { @@ -1409,15 +1469,69 @@ mod tests { opens.set(opens.get() + 1); Some(7) }; - assert_eq!(hooked_open(|| true, open), Some(7)); + assert_eq!(hooked_open(|| true, || true, open), Some(7)); assert_eq!(opens.get(), 1); let open = || { opens.set(opens.get() + 1); Some(7) }; - assert_eq!(hooked_open(|| false, open), None, "no context without the procedure"); + assert_eq!(hooked_open(|| false, || true, open), None, "no context without the procedure"); assert_eq!(opens.get(), 1, "and the driver is not asked for one"); - assert_eq!(hooked_open(|| true, || None::), None, "an open that fails"); + assert_eq!(hooked_open(|| true, || true, || None::), None, "an open that fails"); + } + + #[test] + fn no_context_opens_when_another_app_became_active_before_the_open() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || false, open), None); + assert_eq!(opens.get(), 0, "the driver is not asked for one"); + } + + #[test] + fn another_pens_end_does_not_start_the_readings_afresh() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, true), None, "an eraser end before any packet"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(120, false), Some(0.3), "another pen's tip still reads the packet"); + assert_eq!(r.wheel_at(130, true), None, "the same pen turned over starts them afresh"); + // Pen 1's tip, then pen 2's, then pen 1's eraser, before either reads a wheel. + r.forget(); + assert_eq!(r.wheel_at(200, false), None, "no packet yet"); + assert_eq!(r.wheel_for(210, other, false), None); + r.packet(packet(1, 300), AXIS, 220); + assert_eq!(r.wheel_at(230, true), None, "pen 1's turn is seen past pen 2's message"); + for pen in 10..40 { + r.wheel_for(5000, pen, false); + } + assert_eq!(r.ends.len(), MAX_PENS, "bounded"); + } + + #[test] + fn a_failed_cursor_lookup_is_asked_again_later() { + let asks = std::cell::Cell::new(0); + let failing = || { + asks.set(asks.get() + 1); + Err(()) + }; + let mut c = Cursors::default(); + assert_eq!(c.axis(1, 1000, failing), None); + assert_eq!(c.axis(1, 1000 + RETRY_MS - 1, || Ok(AXIS)), None, "not asked again before the interval"); + assert_eq!(asks.get(), 1); + assert_eq!(c.axis(1, 1000 + RETRY_MS, || Ok(AXIS)), AXIS, "asked again after it"); + assert_eq!(c.axis(1, 9000, || Ok(None)), AXIS, "a range the driver gave is kept"); + assert_eq!(c.axis(2, 9000, || Ok(None)), None, "a cursor without a wheel"); + assert_eq!(c.axis(2, 9000 + RETRY_MS, || Ok(AXIS)), None, "is not asked again"); + c.clear(); + assert_eq!(c.axis(2, 9000, || Ok(AXIS)), AXIS, "until the driver's information changes"); + for cursor in 10..40 { + c.axis(cursor, 9000, || Ok(None)); + } + assert_eq!(c.0.len(), MAX_READINGS * 4, "bounded"); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d05c441153..e8a7fa1579 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2120,7 +2120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen's pointer message takes the last wheel the airbrush reported since it came near, even when the pen has been held still; when cursors of two tablets were read, it takes the one whose latest packet came within 200 ms of the message, and none when both or neither did. 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still and no packet has come for longer, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From 5668a3428eeff72936715e25c388fd82f4f981a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:05:33 -0800 Subject: [PATCH 48/63] Windows: a pen keeps its airbrush's wheel while another tablet's cursor is read The pen that took the Wintab readings now reads the latest packet of its own cursor whenever that cursor is still near the context, instead of only when it is the one cursor read. Another tablet's airbrush moving while the pen is held still no longer drops the pen's wheel. --- apps/vectorcraft/src/windows_wintab.rs | 40 ++++++++++++++------------ docs/target-app-parity.md | 2 +- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 13fe249a06..31da32a1ff 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -386,12 +386,11 @@ impl Readings { /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the - /// readings, the one cursor read since they started afresh, however long ago its last packet - /// came (a pen held still sends none). `None` when no cursor, or more than one, is that recent, - /// or the cursor has read only 0 since the readings started afresh, or another pen's message - /// read a wheel first since then, or the pen read another cursor's wheel since then. The same - /// pen's turn to its other end starts them afresh first; another pen's message with another end - /// does not. + /// readings, the latest packet of the cursor whose wheel it read, however long ago it came (a + /// pen held still sends none) and whatever other cursors were read since. `None` when no cursor, + /// or more than one, is that recent, or the cursor has read only 0 since the readings started + /// afresh, or another pen's message read a wheel first since then. The same pen's turn to its + /// other end starts them afresh first; another pen's message with another end does not. fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { if self.pen.is_some_and(|p| p != pen) { return None; @@ -408,18 +407,18 @@ impl Readings { self.ends.push((pen, eraser)); } } - let r = match self.list.as_slice() { - [one] if self.pen == Some(pen) => one, - list => { - let mut near_time = list.iter().filter(|r| near(time, r.time)); - let r = near_time.next()?; - if near_time.next().is_some() { - return None; - } - r + let r = if self.pen == Some(pen) { + let cursor = self.cursor?; + self.list.iter().find(|r| r.cursor == cursor)? + } else { + let mut near_time = self.list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; } + r }; - if !r.moved || self.cursor.is_some_and(|c| c != r.cursor) { + if !r.moved { return None; } let wheel = r.axis?.wheel(r.raw)?; @@ -1237,12 +1236,13 @@ mod tests { assert_eq!(r.wheel_at(1010, false), Some(0.25)); assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.forget(); r.packet(packet(1, 1000), AXIS, u32::MAX - 5); r.packet(packet(2, 500), None, u32::MAX); assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); r.packet(packet(1, 1000), AXIS, 5000); assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); - assert_eq!(r.wheel_at(9000, false), None, "neither recent"); r.forget(); r.packet(packet(2, 500), None, 100); assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); @@ -1257,9 +1257,13 @@ mod tests { assert_eq!(r.wheel_at(1000, false), Some(0.25)); // Another tablet's airbrush moves while the pen is held still. r.packet(packet(2, 750), AXIS, 5000); - assert_eq!(r.wheel_at(5010, false), None, "the other cursor's wheel"); + assert_eq!(r.wheel_at(5010, false), Some(0.25), "its own cursor's wheel, not the other's"); + assert_eq!(r.wheel_at(9000, false), Some(0.25), "however old both packets are"); r.packet(packet(1, 500), AXIS, 6000); assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 500) }, AXIS, 6100); + r.packet(packet(2, 750), AXIS, 6105); + assert_eq!(r.wheel_at(6110, false), None, "its own cursor left; the other's is not taken"); r.forget(); r.packet(packet(2, 750), AXIS, 7000); assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e8a7fa1579..ac268ed3cd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2120,7 +2120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still and no packet has come for longer, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; the web build does not read it yet. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still, no packet has come for longer, or another tablet's cursor has been read since, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS; these are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From eca0b0c0e1f56ad06200361be7a19878c2acad26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:38:29 -0800 Subject: [PATCH 49/63] Canvas: selection marks follow the pointer in the frame it moves The canvas drew the selection's outlines, anchors, handles and dots before the tool host took the frame's pointer event, so during a drag they showed where the art was one frame earlier. They are now drawn after the tool host and placed back at their old spot in the paint order through a PaintSlot, under the widgets and bars as before. Tests: a Selection tool drag draws its marks at the object's new corner and none at the old one; a Pen drag draws the handle end at the pointer of the same frame. --- crates/ui-egui/src/canvas.rs | 11 +++- crates/ui-egui/src/canvas/tests.rs | 93 ++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e0bc44b304..d2c137b3ce 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -8,6 +8,7 @@ use craft::ui::canvas::{ Canvas, CanvasScrollbars, CanvasSpace, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::primitives::PaintSlot; use craft::ui::runtime::env::Env; use craft::ui::runtime::focus::NudgeMods; use craft::ui::style::StyleCx; @@ -261,7 +262,8 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } -/// The body of the canvas in order: controls that take presses first, the tool host, the picture last. +/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the +/// picture last. fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; @@ -276,7 +278,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); - selection::show(app, ui, space, win, kind); + // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this + // frame's pointer event, from the document as the event leaves it. + let marks = PaintSlot::reserve(ui.painter()); widgets::show(app, ui, space, win, kind); if !presenting && !revolve_editing(app) { crate::panels::three_d::handles::show(app, ui, space); @@ -313,6 +317,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::type_editing::show(app, ui); } } + let after = PaintSlot::reserve(ui.painter()); + selection::show(app, ui, space, win, kind); + marks.extend(ui.ctx(), after.take_after(ui.ctx())); drops::show(app, ui, win, kind); raster::picture(app, ui, space, win, kind); out diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..e2752d11d0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -166,6 +166,99 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); } +/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the +/// points of lines and paths. +fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut points = vec![]; + for shape in flat_shapes(out.shapes) { + match shape { + Shape::Circle(c) => points.push(c.center), + Shape::Rect(r) => points.push(r.rect.center()), + Shape::LineSegment { points: ends, .. } => points.extend_from_slice(&ends), + Shape::Path(p) => points.extend_from_slice(&p.points), + _ => {} + } + } + points +} + +/// A document with smart guides and the task bar off, every frame drawn on this thread. +fn drag_app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.task_bar = false; + app.canvas.worker_started = true; + app +} + +fn press(at: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A drag with the Selection tool draws the moved object's marks in the frame the pointer moves: at the corner the +/// object has after that frame's event, and none at the corner it had before it. +#[test] +fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let corner = |app: &VectorcraftApp| { + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + xf.to_screen(Point::new(b.x0, b.y0)) + }; + let start = xf.to_screen(Point::new(180.0, 120.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut moved = 0; + for i in 1..=6 { + let before = corner(&app); + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(12.0, 7.0) * i as f32)]); + let after = corner(&app); + if after.distance(before) < 4.0 { + continue; + } + moved += 1; + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(after), "move {i}: a mark at the corner after the move, {after:?}"); + assert!(!near(before), "move {i}: no mark at the corner before it, {before:?}"); + } + assert!(moved >= 4, "the drag moves the object: {moved} frames"); +} + +/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and +/// none at the pointer of the frame before. +#[test] +fn a_pen_drag_draws_its_handle_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pen"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let start = xf.to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut before = start; + for i in 1..=6 { + let at = start + vec2(9.0, 5.0) * i as f32; + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(at), "move {i}: the handle's end at this frame's pointer, {at:?}"); + if i > 1 { + assert!(!near(before), "move {i}: no handle end at the pointer of the frame before, {before:?}"); + } + before = at; + } +} + /// A click with the Selection tool inside an artboard makes it the active one, and Paste in /// Place then pastes onto it, where the objects were on their own artboard (#693). #[test] From 272c24a119759a7acc35c27201a9b0475f51c75d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:40:11 -0800 Subject: [PATCH 50/63] Selection: a selected group leaves out guides and templates the view hides A selected group or layer outlined and marked a member made into a guide while the guides were hidden, and the art of a template sublayer while View > Hide Template was on, although the canvas does not draw them. - Node::hidden_by_view (crates/doc/src/node/ops.rs) holds the rule; the renderer's left_out now uses it too. - walk_drawn and the overlay's point limit in canvas/outline.rs leave out the members the view hides, so the selection's outlines, key outline, anchors, hover outline and point count skip them. - The selection's bounds are unchanged. --- crates/doc/src/node/ops.rs | 7 ++ crates/render/src/node_checks.rs | 4 +- crates/ui-egui/src/canvas/outline.rs | 74 +++++++++------ crates/ui-egui/src/canvas/selection.rs | 41 ++++---- crates/ui-egui/src/canvas/selection/tests.rs | 98 ++++++++++++++++++-- crates/ui-egui/src/canvas/tests.rs | 26 ++++-- 6 files changed, 188 insertions(+), 62 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index aaa45c0c6f..cadfb6b7a6 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -131,6 +131,13 @@ impl Node { matches!(self.kind, NodeKind::Layer { template: true, .. }) } + /// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this + /// object out: a template layer while templates are hidden, or a path made into a guide while + /// guides are hidden. The canvas draws ruler guides apart from the art. + pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool { + (templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. })) + } + /// The art objects of this container: its children, looking through sublayers, which are not /// objects (bottom first). With `editable`, only the visible, unlocked objects in visible, /// unlocked, non-template sublayers. diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index a4d9fda7af..ecba138052 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -112,9 +112,7 @@ pub(crate) fn holds_instance(n: &Node) -> bool { /// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its /// symbol is being edited from? pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool { - let view_item = a.is_ruler_guide() - || (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) - || (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); + let view_item = a.is_ruler_guide() || a.hidden_by_view(opts.skip_templates || opts.hide_templates, opts.skip_templates || opts.hide_guides); !a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id) } diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 4e83b1197b..6ebda8e24a 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,12 +8,33 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } +/// What the view hides among a selected object's members, which the selection marks leave out as +/// the canvas does ([`Node::hidden_by_view`]): template layers while View › Hide Template is on, +/// and paths made into guides while the guides are hidden. The default hides nothing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ViewHides { + pub(super) templates: bool, + pub(super) guides: bool, +} + +impl ViewHides { + /// What `app`'s view hides. + pub(super) fn of(app: &VectorcraftApp) -> Self { + Self { templates: !app.ui.view.templates, guides: !app.ui.view.guides_shown() } + } + + /// Whether the view leaves `n` out. + fn hides(self, n: &Node) -> bool { + n.hidden_by_view(self.templates, self.guides) + } +} + /// Outline of a node for highlighting (paths, compound children, area type frames, other text /// bounds, images' frames, symbol instances' bounds measured by their art from `symbols`; a clip -/// group's clipping path only, as [`walk_drawn`] visits it). -pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { +/// group's clipping path only, as [`walk_drawn`] visits it, without the members `hides` leaves out). +pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Path { path, .. } => bp.extend(path.to_bezpath()), // Area type shows its frame: the type area Direct Selection reshapes; type on a path its // path, which the selection tools' brackets sit on; point type shows its baseline(s). @@ -72,11 +93,11 @@ fn is_linked(n: &Node) -> bool { } /// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, -/// from corner to corner of its frame or box (#9080). The selection marks draw them; the hover -/// highlight does not. -pub(super) fn linked_crosses(n: &Node) -> BezPath { +/// from corner to corner of its frame or box (#9080), without the members `hides` leaves out. The +/// selection marks draw them; the hover highlight does not. +pub(super) fn linked_crosses(n: &Node, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Image(_) if is_linked(c) => { if let Some(cross) = c.image_cross() { bp.extend(cross); @@ -101,22 +122,23 @@ pub(super) fn linked_crosses(n: &Node) -> BezPath { /// #2460). pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; -/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; -/// counting stops there). -pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - over_limit(nodes, false) +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`], +/// without the members `hides` leaves out; counting stops there). +pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, false, hides) } /// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they -/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them. -pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator) -> bool { - over_limit(nodes, true) +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them +/// without the members `hides` leaves out. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, true, hides) } /// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the -/// ends of the crossing lines when `crosses`); counting stops there. -fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> bool { - fn over(n: &Node, left: &mut usize, crosses: bool) -> bool { +/// ends of the crossing lines when `crosses`) in what [`walk_drawn`] visits; counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool, hides: ViewHides) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool, hides: ViewHides) -> bool { let ends = if crosses && is_linked(n) { 4 } else { 0 }; match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, @@ -124,12 +146,12 @@ fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool) -> b } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses, hides)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.drawn_children().any(|c| over(c, left, crosses)) + !matches!(n.kind, NodeKind::Envelope { .. }) && n.drawn_children().filter(|c| !hides.hides(c)).any(|c| over(c, left, crosses, hides)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left, crosses)) + nodes.into_iter().any(|n| over(n, &mut left, crosses, hides)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a @@ -158,21 +180,21 @@ fn overlay_points(n: &Node) -> usize { /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the /// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, -/// its first child, not the art the path clips (#2422), and hidden members are left out -/// ([`Node::drawn_children`]). -pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { +/// its first child, not the art the path clips (#2422), and hidden members +/// ([`Node::drawn_children`]) and the members `hides` leaves out are left out. +pub(super) fn walk_drawn<'a>(n: &'a Node, hides: ViewHides, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { return; } if n.clips() { if let Some(clip) = n.children().and_then(|children| children.first()) { - walk_drawn(clip, f); + walk_drawn(clip, hides, f); } return; } - for c in n.drawn_children() { - walk_drawn(c, f); + for c in n.drawn_children().filter(|c| !hides.hides(c)) { + walk_drawn(c, hides, f); } } diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 55da766408..c8e0dd5212 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -24,7 +24,7 @@ use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; -use super::outline::{c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; +use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). @@ -147,9 +147,9 @@ fn hidden(app: &VectorcraftApp) -> bool { crate::dialogs::halftone::previewing(app) } -/// Whether the selection has too many points to outline and cross: its bounds stand for it. -fn too_big(st: &DocState) -> bool { - too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id))) +/// Whether the selection has too many points to outline and cross in `app`'s view: its bounds stand for it. +fn too_big(app: &VectorcraftApp, st: &DocState) -> bool { + too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)), ViewHides::of(app)) } /// The rectangle of `bounds` as a path. @@ -174,9 +174,9 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { if hidden(app) { return out; } - let (sel, symbols) = (&st.selection, st.doc.symbol_boxes()); + let (sel, symbols, hides) = (&st.selection, st.doc.symbol_boxes(), ViewHides::of(app)); let color_of = |id: NodeId| c32(st.doc.layer_color(id)); - if too_big(st) { + if too_big(app, st) { // The cache is warmed by `show`; a test or a miss measures again. let bounds = match app.canvas.selection_bounds { Some((key, bounds)) if key == (st.uid, st.revision) => bounds, @@ -189,7 +189,7 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; // Linked images and placed documents are also crossed from corner to corner. - for path in [node_outline(node, &symbols), linked_crosses(node)] { + for path in [node_outline(node, &symbols, hides), linked_crosses(node, hides)] { if !path.elements().is_empty() { group(&mut out, color_of(*id)).paths.push(path); } @@ -200,7 +200,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } } if let Some((key, node)) = sel.key.and_then(|key| Some((key, st.doc.node(key)?))) { - let path = if too_many_anchors([node]) { node.geometric_bounds_with(&symbols).map(bounds_path) } else { Some(node_outline(node, &symbols)) }; + let path = if too_many_anchors([node], hides) { + node.geometric_bounds_with(&symbols).map(bounds_path) + } else { + Some(node_outline(node, &symbols, hides)) + }; if let Some(path) = path { group(&mut out, color_of(key)).key = Some(path); } @@ -268,10 +272,10 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin segment_mark: SegmentMark::Line, options: path_options(prefs), }; - if hidden(app) || too_big(st) || (curvature && tool_points) { + if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; } - let sel = &st.selection; + let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; @@ -279,7 +283,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let Some(node) = st.doc.node(*id) else { continue }; let partial = sel.partial(*id); let color = c32(st.doc.layer_color(*id)); - walk_drawn(node, &mut |c| { + walk_drawn(node, hides, &mut |c| { let envelope = vectorcraft_doc::live::envelope_overlay(c).and_then(|(_, grid)| grid); let grid = match &c.kind { NodeKind::Mesh(m) => Some(m), @@ -371,13 +375,14 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, if kept { return None; } - outline_of(st, id) + outline_of(st, id, ViewHides::of(app)) } -/// The hover outline of `id` in its layer colour, unless it has too many points. -fn outline_of(st: &DocState, id: NodeId) -> Option { - let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?; - Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) }) +/// The hover outline of `id` in its layer colour, without the members `hides` leaves out, unless it has too many +/// points. +fn outline_of(st: &DocState, id: NodeId, hides: ViewHides) -> Option { + let node = st.doc.node(id).filter(|n| !too_many_anchors([*n], hides))?; + Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes(), hides), color: c32(st.doc.layer_color(id)) }) } /// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view @@ -407,7 +412,7 @@ pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, } let info = app.view_info(); let id = eyedropper_hover_object(app, at, mods, info)?; - outline_of(app.session.active()?, id) + outline_of(app.session.active()?, id, ViewHides::of(app)) } /// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and @@ -497,7 +502,7 @@ fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view /// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor. pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots { let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() }; - if hidden(app) || too_big(st) { + if hidden(app) || too_big(app, st) { return out; } let symbols = st.doc.symbol_boxes(); diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 0e8dd77e45..bef89f1f41 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -243,7 +243,7 @@ fn the_key_object_has_its_own_outline() { let ids = app.session.active().unwrap().selection.objects.clone(); app.run("select.key", json!({"id": curve.0})).unwrap(); let st = app.session.active().unwrap(); - let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes()); + let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes(), ViewHides::default()); let color = c32(st.doc.layer_color(curve)); let out = outlines(&app, st); let key = out.iter().find(|o| o.color == color).and_then(|o| o.key.as_ref()).unwrap(); @@ -331,7 +331,11 @@ fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { let st = app.session.active().unwrap(); let key = outlines(&app, st).into_iter().find_map(|o| o.key).unwrap(); assert_eq!(key.elements(), frame_of(corners(&app, id)).as_slice(), "the key object's outline of {id:?}"); - assert_eq!(outline_of(st, id).unwrap().path.elements(), frame_of(corners(&app, id)).as_slice(), "the hover outline of {id:?}"); + assert_eq!( + outline_of(st, id, ViewHides::default()).unwrap().path.elements(), + frame_of(corners(&app, id)).as_slice(), + "the hover outline of {id:?}" + ); } } @@ -356,8 +360,9 @@ fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { let count = OVERLAY_MAX_ANCHORS / 6; let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; let embedded = vec![image(None); count]; - assert!(!too_many_anchors(&linked) && too_many_marks(&linked), "linked images"); - assert!(!too_many_anchors(&embedded) && !too_many_marks(&embedded), "embedded images"); + let all = ViewHides::default(); + assert!(!too_many_anchors(&linked, all) && too_many_marks(&linked, all), "linked images"); + assert!(!too_many_anchors(&embedded, all) && !too_many_marks(&embedded, all), "embedded images"); } /// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member and a linked image @@ -385,7 +390,7 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { let st = app.session.active().unwrap(); let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); - let hovered = outline_of(st, group).map(|h| h.path.elements().to_vec()); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); (outlined, anchored, hovered) }; let both = shown(&mut app, &[]); @@ -396,6 +401,87 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { assert_eq!(with_hidden, without, "hidden members are not marked"); } +/// A selected group leaves out a member made into a guide while the guides are hidden, as the canvas does: its +/// outlines, anchors and hover outline are the same as with that member deleted. With the guides shown, the guide is +/// marked too. +#[test] +fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { + let mut app = blank(); + let path = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let guide = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [path.0, guide.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + assert!( + matches!(app.session.active().unwrap().doc.node(guide).map(|n| &n.kind), Some(NodeKind::Path { guide: true, .. })), + "the group holds a guide" + ); + // With the group selected: the boxes of its outline paths, the paths that show anchors, and its hover outline's box. + let shown = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides_shown(), "the guides are hidden"); + let guides_hidden = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let without = shown(&mut app); + assert_eq!(both.1.len(), 2, "with the guides shown, the guide shows its anchors too: {both:?}"); + assert_ne!(both, without, "with the guides shown, the guide is marked"); + assert_eq!(guides_hidden, without, "with the guides hidden, only the path is marked"); +} + +/// A selected layer leaves out the art of a template sublayer while View › Hide Template is on, and a group a guide +/// while the guides are hidden: their outlines and the overlay's point limit count only what the canvas draws. +#[test] +fn the_marks_leave_out_template_layers_and_guides_the_view_hides() { + use super::super::outline::{node_outline, too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let rect = |id: u64, r: vectorcraft_geom::Rect| Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + let path = Arc::new(rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0))); + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut many = Node::path(NodeId(3), PathData::single(SubPath::polyline(&points, false)), Appearance::default()); + let mut template = Node::layer(NodeId(4), "Template", LayerColor::Preset(1)); + if let NodeKind::Layer { template: on, children, .. } = &mut template.kind { + *on = true; + children.push(Arc::new(many.clone())); + } + let mut layer = Node::layer(NodeId(5), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(template), path.clone()]); + } + if let NodeKind::Path { guide, .. } = &mut many.kind { + *guide = true; + } + let group = Node::group(NodeId(6), vec![Arc::new(many), path.clone()]); + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let alone = node_outline(&path, &symbols, ViewHides::default()).bounding_box(); + let mut wrong = vec![]; + for (n, what, hides) in [ + (&layer, "a layer with a template sublayer", ViewHides { templates: true, guides: false }), + (&group, "a group with a guide", ViewHides { templates: false, guides: true }), + ] { + for (hides, hidden) in [(ViewHides::default(), false), (hides, true)] { + let outline = node_outline(n, &symbols, hides).bounding_box(); + if (outline == alone) != hidden || too_many_anchors([n], hides) == hidden || too_many_marks([n], hides) == hidden { + wrong.push(format!("{what}, hidden by the view: {hidden}")); + } + } + } + assert!(wrong.is_empty(), "the marks count only what the view draws: {wrong:?}"); +} + /// The overlay's limit counts the points of the members the highlight outlines: a hidden member of a group, a blend, a /// repeat or an intertwine, and the art of a hidden sublayer, do not count toward it. #[test] @@ -430,7 +516,7 @@ fn the_overlay_limit_leaves_out_hidden_members() { children.extend([Arc::new(sublayer), few.clone()]); } for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { - if too_many_anchors([n]) != visible || too_many_marks([n]) != visible { + if too_many_anchors([n], ViewHides::default()) != visible || too_many_marks([n], ViewHides::default()) != visible { wrong.push(format!("{what}, member visible: {visible}")); } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 00c503addb..801a5c401e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11,7 +11,7 @@ use super::artboards::names_an_artboard; use super::cursor::still_wait; use super::fill::{fill_view, polygon_area}; use super::marks::{HiddenMarks, thread_overlays}; -use super::outline::{node_outline, walk_drawn}; +use super::outline::{ViewHides, node_outline, walk_drawn}; use super::raster::{frame_view, pixel_region, placed_changes, placed_key_at, placed_since, poll_worker}; use super::*; use crate::CacheKey; @@ -31,9 +31,13 @@ fn shaper_selection_highlights_only_the_visible_result() { let g = st.doc.node(st.selection.objects[0]).unwrap(); assert!(g.extras().shaper.is_some()); let symbols = st.doc.symbol_boxes(); - let bounds = node_outline(g, &symbols).bounding_box(); + let bounds = node_outline(g, &symbols, ViewHides::default()).bounding_box(); assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}"); - assert_eq!(node_outline(st.doc.node(line).unwrap(), &symbols).bounding_box().x0, 50.0, "an isolated original still shows its full outline"); + assert_eq!( + node_outline(st.doc.node(line).unwrap(), &symbols, ViewHides::default()).bounding_box().x0, + 50.0, + "an isolated original still shows its full outline" + ); } #[test] @@ -50,7 +54,7 @@ fn a_symbol_instance_is_outlined_around_its_art() { inst = Some(n); } }); - assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); + assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes(), ViewHides::default()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); } /// One headless canvas frame on an 800 × 600 window. @@ -4537,18 +4541,18 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); let mut visited = vec![]; - walk_drawn(&group, &mut |n| visited.push(n.id)); + walk_drawn(&group, ViewHides::default(), &mut |n| visited.push(n.id)); assert_eq!(visited.contains(&NodeId(2)), view.shows_source()); let want = if view.shows_source() { vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0) } else { vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0) }; - assert_eq!(node_outline(&group, &symbols).bounding_box(), want); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), want); } // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); // A hidden path sent to the back of a trace is not its source image, in any view. let mut path = Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); @@ -4557,7 +4561,11 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), "{view:?}"); + assert_eq!( + node_outline(&group, &symbols, ViewHides::default()).bounding_box(), + vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), + "{view:?}" + ); } } @@ -4580,7 +4588,7 @@ fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { }; let doc = vectorcraft_doc::Document::new(300.0, 300.0); let symbols = doc.symbol_boxes(); - let contours = |n: &Node| node_outline(n, &symbols).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + let contours = |n: &Node| node_outline(n, &symbols, ViewHides::default()).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); From 6d908ec05197c0aac0c32e9a524c147fc97fabe2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:41:37 -0800 Subject: [PATCH 51/63] Pathfinder: the Repeat row names the operation that ran last The Pathfinder panel menu's Repeat row read "Repeat Pathfinder" after every operation. The label for pathfinder.repeat now reads "Repeat Unite", "Repeat Minus Front" and so on from the last Shape Mode or Pathfinder operation, through the existing "Repeat {name}" template, and keeps "Repeat Pathfinder" before any has run. Every row of the command uses the same label. --- crates/ui-egui/src/menus/labels.rs | 14 ++++++++++++++ crates/ui-egui/src/panels/pathfinder.rs | 22 ++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index bce650899b..93e13ae22f 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -99,6 +99,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())), None => label.into(), }, + // Repeat Pathfinder is named after the Shape Mode or Pathfinder operation that ran last. + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => format!("Repeat {name}"), + None => label.into(), + }, // Apply Last Filter and Last Filter… are named after the filter that ran last. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => format!("Apply {name}"), @@ -129,6 +134,11 @@ fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option Some(text) } +/// The Pathfinder panel's name for the Shape Mode or Pathfinder operation that ran last. +fn last_pathfinder_label(app: &VectorcraftApp) -> Option<&'static str> { + app.last_pathfinder.as_deref().and_then(crate::panels::pathfinder::operation_label) +} + /// Does the menu item `id` show a name that is user, file or system data rather than an interface /// label: a recent file, a saved view, a font, a user library or preset, a custom workspace, a /// plug-in, an SVG filter, a script of the Scripts folder? Such names are shown as they are, never @@ -201,6 +211,10 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } None => crate::i18n::tr_id(lang, id, label).to_string(), }, + "pathfinder.repeat" => match last_pathfinder_label(app) { + Some(name) => fmt(tl!("Repeat {name}"), &[("name", tl!(name))]), + None => crate::i18n::tr_id(lang, id, label).to_string(), + }, // The filter's name is the plug-in's own text, never translated. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => match crate::dialogs::plugin::last_filter_name(app) { Some(name) if id == crate::dialogs::plugin::APPLY_LAST => fmt(tl!("Apply {filter}"), &[("filter", &name)]), diff --git a/crates/ui-egui/src/panels/pathfinder.rs b/crates/ui-egui/src/panels/pathfinder.rs index 8280c4c3d1..d1ee58262d 100644 --- a/crates/ui-egui/src/panels/pathfinder.rs +++ b/crates/ui-egui/src/panels/pathfinder.rs @@ -520,6 +520,28 @@ mod tests { assert!(p.app().run("pathfinder.repeat", json!({})).is_err()); } + /// The state the window's menus give the Repeat row, which the panel menu's row reads. + fn repeat_row(p: &Panel) -> Option { + crate::menus::model::refresh(&mut p.app(), p.ctx()); + p.app().menus.states.get(&CommandRef::new("pathfinder.repeat")).cloned() + } + + /// Before an operation has run, the Repeat row reads Repeat Pathfinder and is dimmed; after Unite + /// or Minus Front from the panel it names that operation. + #[test] + fn the_repeat_row_names_the_last_operation() { + let mut p = Panel::new(two_squares(), show); + let command = CommandRef::new("pathfinder.repeat"); + let off = crate::menus::model::off_reason(&p.app(), &command, "Repeat Pathfinder"); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(false).hint(off)), "the plain label, dimmed"); + p.click("Unite"); + select_two_squares(&mut p.app(), 110.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Unite"))); + p.click("Minus Front"); + select_two_squares(&mut p.app(), 210.0); + assert_eq!(repeat_row(&p), Some(CommandState::new().enabled(true).title("Repeat Minus Front"))); + } + /// One selected path cannot supply the operands for Unite; the command reports the failure. #[test] fn repeat_with_one_path_keeps_art_and_history() { From 94a0890b53671da5ffd0a489a3834d64bb477a6b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:57:07 +0700 Subject: [PATCH 52/63] OpenType row menu: apply its choice with the panel's other changes The row menu ran edit/set in the middle of the panel's pass, so rows drawn after the click read a different state from those before it. It now returns the chosen Change (a new Change::Reset for Reset OpenType Features), and show applies it once at the end like the checkbox and Stylistic Sets menu do. Reset still writes the default as the whole feature list. Answers bflatastic's review. --- crates/ui-egui/src/panels/opentype.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 0034f47231..b0025b5f82 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -197,6 +197,8 @@ enum Change { Position(usize), /// A checkbox row turned on or off. Toggle(Flag, bool), + /// A row menu's Reset OpenType Features: the panel menu's default. + Reset, } impl Change { @@ -205,6 +207,7 @@ impl Change { Change::Figure(i) => set_figure(f, i), Change::Position(i) => set_position(f, i), Change::Toggle(flag, on) => flag.put(f, on), + Change::Reset => *f = OtFeatures::default(), } } } @@ -293,7 +296,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(on) = out.events.committed() { change = Some(Change::Toggle(flag, *on)); } - Menu::context(label, &out.response).show(ui, |ui, _| feature_row_menu(app, ui, flag, shown)); + // The row menu's choice is applied with the rest at the end of the pass, so the rows drawn + // after it still read the state the pass started with. + if let Some(c) = Menu::context(label, &out.response).show(ui, |ui, _| feature_row_menu(app, ui, flag, shown)).inner.flatten() { + change = Some(c); + } } let sets = set_entries(app, &st); let opener = Button::new(tl!("Stylistic Sets")).enabled(!sets.is_empty()).show(ui); @@ -307,8 +314,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if tracking_drops_ligatures(app) { Text::new(tl!("Ligatures are off while the text is tracked.")).shade(Shade::Muted).show(ui); } - if let Some(c) = change { - edit(app, c); + match change { + // Reset writes the default as the whole feature list, as the panel menu's entry does. + Some(Change::Reset) => set(app, OtFeatures::default()), + Some(c) => edit(app, c), + None => {} } } @@ -316,14 +326,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// (`shown` is `Some(true)`); Turn On when it is off or mixed, through the same toggle a click /// uses, so a mixed row turns the feature on for every character the panel acts on. Reset /// OpenType Features applies the panel menu's default and is enabled on the same condition. -fn feature_row_menu(app: &mut VectorcraftApp, ui: &mut Ui, flag: Flag, shown: Option) { +fn feature_row_menu(app: &VectorcraftApp, ui: &mut Ui, flag: Flag, shown: Option) -> Option { let on = shown == Some(true); + let mut chosen = None; if MenuItem::new(if on { tl!("Turn Off") } else { tl!("Turn On") }).show(ui).ran { - edit(app, Change::Toggle(flag, !on)); + chosen = Some(Change::Toggle(flag, !on)); } if MenuItem::new(tl!("Reset OpenType Features")).enabled(text_style(app).is_some()).show(ui).ran { - set(app, OtFeatures::default()); + chosen = Some(Change::Reset); } + chosen } /// Whether tracking turns off the standard ligatures of any character the panel acts on: one with From dcc688915d3b2bad694a347297f07e9218d96ae3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:29:03 -0800 Subject: [PATCH 53/63] Graphic Styles: restore the New and Delete Alt-click hints --- crates/ui-egui/src/panels/graphic_styles.rs | 25 +++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 2d4fcad4d5..a1f3dabb97 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -485,9 +485,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .popup(PopupKind::Menu) .pressed(library_panel::any_open::(&app.ui)), FooterAction::new(svg("link-2-off"), tl!("Break Link to Graphic Style")).enabled(linked), - FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style")).enabled(!sel.is_empty()).takes_drops_disabled(true).accepts_drops(ours), + FooterAction::new(svg("trash-2"), tl!("Delete Graphic Style (Alt-click: without asking)")) + .enabled(!sel.is_empty()) + .takes_drops_disabled(true) + .accepts_drops(ours), // A style dropped here is duplicated with or without art selected. - FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style")) + FooterAction::new(svg("dc-new-item"), tl!("New Graphic Style (Alt-click to name it)")) .enabled(selection_len(app) > 0) .takes_drops_disabled(true) .accepts_drops(ours), @@ -1430,4 +1433,22 @@ mod tests { app.session.documents().iter().map(|st| st.doc.graphic_styles.iter().map(|g| g.name.clone()).collect()).collect(); assert!(names.iter().all(|n| n.iter().any(|g| g == "Mine")), "no style is renamed: {names:?}"); } + + /// The New and Delete buttons name what an Alt-click does, and an Alt-click does it: New asks for a name, Delete + /// deletes without asking. + #[test] + fn the_new_and_delete_buttons_name_their_alt_click() { + use crate::tests::panel_harness::Panel; + use egui::Modifiers; + let mut panel = Panel::new(app(), show); + panel.click_with("New Graphic Style (Alt-click to name it)", Modifiers::ALT); + assert!(open_dialog(&panel.app(), graphic_style_options::KIND).is_some(), "Alt-click on New asks for a name"); + let mut app = app(); + app.session.execute("graphicStyle.new", &json!({"name": "Mine"})).unwrap(); + let mut panel = Panel::new(app, show); + panel.click("Mine"); + panel.click_with("Delete Graphic Style (Alt-click: without asking)", Modifiers::ALT); + let app = panel.app(); + assert!(!names(&app).iter().any(|s| s == "Mine") && confirm::open_question(&app).is_none(), "Alt-click on Delete deletes at once"); + } } From e26efcb1659b661d5e3648dc7951608bf3fb3f3c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:36:14 -0800 Subject: [PATCH 54/63] Kinsoku Shori Sets: show None when the set list is empty --- crates/ui-egui/src/dialogs/kinsoku_sets.rs | 5 +++-- crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index 1aac4c28b8..6eb690989d 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -361,10 +361,11 @@ impl KinsokuDialog { let rows: Vec> = list.iter().map(|s| PresetRow::item(name_of(s).to_owned(), name_of(s), 0)).collect(); let mut value = list.get(self.index(list.len())).map(|s| name_of(s).to_owned()); let suggestion = new_name(&list, &self.opened); - // PLAN: PresetPicker has no placeholder: an empty list shows an empty name field, not "None". let source = PresetSource::listed(&rows); let refuses = |typed: &str| name_problem(&list, typed); - let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)).field(PickerField::Name); + let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)) + .field(PickerField::Name) + .placeholder(tl!("None")); let out = NamedPresetRow::new(tl!("Kinsoku Set"), picker).suggest_name(suggestion).check_name(NameCheck::of_host(&refuses)).show(ui); self.apply(out.events); diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index f39cf6d596..887dbbc202 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -47,6 +47,21 @@ fn cancel(app: &VectorcraftApp) { app.dialogs().unwrap().with(|h| h.cancel::(&ctx)); } +#[test] +fn empty_kinsoku_list_shows_none_in_the_preset_picker() { + let mut fixture = craft::ui::testing::Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui))); + fixture.room(egui::vec2(800.0, 600.0)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(fixture.ctx().clone()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + open(&mut app).unwrap(); + fixture.settle(); + + let picker = fixture.by_label("Kinsoku Set").expect("Kinsoku Set picker"); + assert_eq!(fixture.tree().value_of(picker.node), Some("None")); + assert!(picked(&app).is_empty(), "the caption does not select a set"); +} + /// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its /// categories edited in their fields and Add putting in a character by its code point; nothing /// changes until OK, which sets them as one undo step; Cancel leaves them. From 75fd52fca639e3d85918be6adcc4b560f199ac82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:40:33 -0800 Subject: [PATCH 55/63] Scripts: keep nested apply operands alive during collection --- crates/js/src/interp.rs | 5 ++++- crates/js/src/interp_tests.rs | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index c2b707e3c6..6a57041cfe 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2830,9 +2830,12 @@ impl Interp { return Err(self.type_error("apply was called on a value that is not a function")); } let list = args.get(1).cloned().unwrap_or(Value::Undefined); + let mut roots = vec![f.clone(), this.clone()]; + roots.extend(args.iter().cloned()); + let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?; f = this; this = args.first().cloned().unwrap_or(Value::Undefined); - args = self.list_from_array_like(&list)?; + args = expanded; } Func::Bound { target, this: bound_this, args: bound_args } => { self.use_fuel()?; diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 586ae77e24..a300d22451 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -613,6 +613,26 @@ fn apply_keeps_its_arguments_alive_while_a_native_function_runs() { assert_eq!(realm.run(src), Ok(JsValue::Number(42.0))); } +#[test] +fn successive_apply_expansions_keep_getter_receivers_alive() { + for queued in [false, true] { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 1 << 20, ..Limits::default() }); + let src = "var result; function callback(a) { result = this.kept + a; } \ + var inner = {length: 1, get 0() { for (var i = 0; i < 20000; i++) ({i: i}); return 2; }}; \ + var outer = {length: 2, get 0() { return {kept: 40}; }, get 1() { return inner; }};"; + realm.run(src).unwrap(); + let collections = realm.interp().heap.collections; + let call = if queued { + "Promise.resolve(outer).then(Function.prototype.apply.bind(Function.prototype.apply, callback));" + } else { + "Function.prototype.apply.apply(callback, outer);" + }; + realm.run(call).unwrap(); + assert!(realm.interp().heap.collections > collections); + assert_eq!(realm.run("result"), Ok(JsValue::Number(42.0)), "queued: {queued}"); + } +} + #[test] fn to_number_skips_the_white_space_the_lexer_skips() { let mut realm = small(Limits::default()); From 1b6bcd370ac11fa318da69ca1930a15a72f7a66f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:42:40 -0800 Subject: [PATCH 56/63] JavaScript: cache shared rejection reason attribution --- crates/js/src/builtins/promise.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..6a2b5005a6 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -731,6 +731,7 @@ impl Interp { pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { let rejected = std::mem::take(&mut self.promises.rejected); let mut out = Vec::new(); + let mut attribution = Vec::new(); let mut count = 0; for p in rejected { let (reason, site) = match self.heap.object(p).map(|o| &o.class) { @@ -748,7 +749,17 @@ impl Interp { message.truncate(cut); message.push('…'); } - let authored = self.thrown_by_script(&reason); + let authored = if let Some(object) = reason.as_object() { + if let Some((_, authored)) = attribution.iter().find(|(seen, _)| *seen == object) { + *authored + } else { + let authored = self.thrown_by_script(&reason); + attribution.push((object, authored)); + authored + } + } else { + self.thrown_by_script(&reason) + }; let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc))); out.push(crate::Rejection { message, line, column, tag, authored }); } From ff9bd64003f21a1cb9f83a1b7c49ca632c850b78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:53:49 -0800 Subject: [PATCH 57/63] JavaScript: preserve Promise rejection relay locations --- crates/js/src/builtins/promise.rs | 15 +++++++++------ crates/js/src/promise_tests.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 3 +++ docs/target-app-parity.md | 2 +- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 276acf7e96..a464dd348d 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -140,7 +140,7 @@ enum Job { /// What happens when the running job's call ends. enum Then { /// The result resolves this promise, and an exception rejects it. - Settle(ObjId), + Settle(ObjId, Option), /// An exception rejects through this resolving record. Reject(ObjId), /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or @@ -214,7 +214,7 @@ impl Promises { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); roots.values.extend(self.completion.iter()); match &self.running { - Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Settle(o, _) | Then::Reject(o)) => roots.objects.push(*o), Some(Then::Finally { derived, value, .. }) => { roots.objects.push(*derived); roots.values.push(value); @@ -662,7 +662,7 @@ impl Interp { interp.temp_roots.extend([handler, argument.clone()]); (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws }) } - None => (handler, Value::Undefined, vec![argument], Then::Settle(derived)), + None => (handler, Value::Undefined, vec![argument], Then::Settle(derived, site)), } } Job::Thenable { promise, thenable, then } => { @@ -689,8 +689,8 @@ impl Interp { let site = if r.is_err() { caught(self) } else { None }; let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) }; match (then, r) { - (Then::Settle(d), Ok(v)) => resolve_promise(self, d, v), - (Then::Settle(d), Err(e)) => reject_promise(self, d, e, site), + (Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v), + (Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site), (Then::Reject(_), Ok(_)) => Ok(()), (Then::Reject(rec), Err(e)) => scoped(self, |interp| { root(interp, &Value::Object(rec)); @@ -796,7 +796,10 @@ fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// A promise's reject function (section 25.6.1.3.1). fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?; - let site = here(interp); + let site = here(interp).or_else(|| match &interp.promises.running { + Some(Then::Settle(_, site)) => site.clone(), + _ => None, + }); reject_through(interp, rec, arg(args, 1), site)?; Ok(Value::Undefined) } diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 915427de89..ef0ed1d0d1 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -226,6 +226,30 @@ fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { assert_eq!(got, want); } +#[test] +fn combinator_rejection_relays_keep_the_input_location() { + for method in ["all", "race"] { + let mut r = realm(); + r.run(&format!("var input =\n Promise.reject('lost');\nPromise.{method}([input]);")).unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 1, "{method}: {reported:?}"); + assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]); + assert!(reported[0].column > 0); + assert_eq!(reported[0].tag, r.script_tag()); + } + let mut r = realm(); + r.run("var reject; new Promise(function (_, no) { reject = no; });\nPromise.reject('handled').catch(function () {\n reject('lost');\n});") + .unwrap(); + assert_eq!(r.unhandled_rejections().len(), 1); + assert_eq!(r.unhandled_rejections()[0].line, 3); + assert!(r.unhandled_rejections()[0].column > 0); + let mut r = realm(); + r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 2); + assert!(reported.iter().all(|r| r.tag == UNKNOWN_SOURCE), "{reported:?}"); +} + #[test] fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() { let mut r = realm(); diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..18f0c52537 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2895,6 +2895,9 @@ own rules: rejected (the `throw`, or the call of its reject function or of `Promise.reject`), `unhandledRejectionCount` counts all of them, and the Script Console shows an error line for each, as in `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. + `all` and `race` preserve an input rejection's known location. Calling a saved reject function from script uses + that call's location. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits + `file` and sets `line` and `column` to 0. The first run in an engine decides whether the engine has `Symbol` and the iterators of arrays, strings and `arguments` objects, and each run's script decides which syntax that run reads. The built-in functions' names follow diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b564a77730..da7d19a638 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1107,7 +1107,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. From fc07f8a326996d106537458b10d8794606e90fb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:56:03 -0800 Subject: [PATCH 58/63] JavaScript: root the running rejection site code --- crates/js/src/builtins/promise.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index a464dd348d..92e5c25796 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -214,7 +214,11 @@ impl Promises { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); roots.values.extend(self.completion.iter()); match &self.running { - Some(Then::Settle(o, _) | Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Settle(o, site)) => { + roots.objects.push(*o); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Some(Then::Reject(o)) => roots.objects.push(*o), Some(Then::Finally { derived, value, .. }) => { roots.objects.push(*derived); roots.values.push(value); From acda8bed2747980e1f1271c597c34b736d174bdd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:07:41 -0800 Subject: [PATCH 59/63] Effects: restore the blend-mode menu for shadows and glows Use the grouped picker in the effect dialogs and Appearance editor. Validate new automation requests while preserving earlier spellings, recorded steps, and untouched stored modes. --- crates/effects/src/catalog.rs | 6 +- crates/effects/src/lib.rs | 5 +- crates/effects/src/params.rs | 22 ++++++ crates/engine/src/cmd/effectcmd.rs | 11 ++- crates/engine/src/cmd/params.rs | 23 +++++- crates/engine/tests/it/param_keys.rs | 50 +++++++++++++ crates/ui-egui/src/control.rs | 5 ++ crates/ui-egui/src/dialogs/effect.rs | 20 ++++++ crates/ui-egui/src/dialogs/effect_params.rs | 5 ++ crates/ui-egui/src/dialogs/form.rs | 7 ++ crates/ui-egui/src/dialogs/tests.rs | 79 +++++++++++++++++++++ crates/ui-egui/src/fields.rs | 9 +++ docs/mcp.md | 14 ++++ 13 files changed, 245 insertions(+), 11 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..071d3c3b64 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec { "stylize.dropShadow", "Drop Shadow…", STYLIZE, - "{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", + "{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)", json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}), ), r( "stylize.innerGlow", "Inner Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}), ), r( "stylize.outerGlow", "Outer Glow…", STYLIZE, - "{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", + "{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}", json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}), ), r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})), diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 1b8067e91c..555610f206 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -82,11 +82,12 @@ pub use group::{ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; +pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use placement::pinned_gradient_item; pub use raster::{ - RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects, - without_geometry, + RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, + staged_effects, without_geometry, }; pub use reshape::{ SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index fed9df7811..d97c16b554 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -1,6 +1,28 @@ +use vectorcraft_doc::color::BlendMode; + use super::catalog::{catalog_index, plugin_info}; use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util}; +/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in. +pub fn takes_blend_mode(effect: &str, key: &str) -> bool { + key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow") +} + +/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode. +pub fn parse_blend_mode(s: &str) -> Option { + let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect(); + BlendMode::parse(&name) +} + +/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`. +pub fn blend_mode_id(mode: BlendMode) -> String { + let mut name = format!("{mode:?}"); + if let Some(first) = name.get_mut(..1) { + first.make_ascii_lowercase(); + } + name +} + /// Dialog defaults for `id` (`None` for unknown effects). pub fn default_params(id: &str) -> Option { match catalog_index().get(id) { diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index f29e2e3745..25d7d38321 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption } } +/// The effect an apply request names, including the older `id` parameter. +pub(crate) fn requested_effect(p: &Value) -> Option<&str> { + str_param(p, "effect").or_else(|| str_param(p, "id")) +} + /// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the -/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one; -/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. +/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one. +/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "effect.apply"; - let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?; + let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?; // An effect given as `id` names no objects: the targets are read with that `id` as null. let effect_as_id; let p = if str_param(p, "effect").is_none() { diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 64ce29e337..e88f348085 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -34,7 +34,8 @@ //! plays. A key a schema doesn't name passes there too, and the values of the parameters it names //! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` -//! themselves ([`check_effect_color`], [`check_effect_channel`]). +//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown +//! shadow or glow blend mode, which the effect draws as Normal. use std::collections::HashMap; use std::sync::OnceLock; @@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> { /// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the /// effect takes (those of its dialog defaults and of its params description), each of the type /// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`]) -/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range +/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or +/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range /// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its /// manifest, and an unknown effect is the command's to report. pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { @@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) { return Err(unknown(id, key, &keys)); } + check_effect_blend(id, effect, params)?; check_effect_types(id, effect, params)?; // An SVG filter's XML is one drawable element. if effect == vectorcraft_render::effects::SVG_FILTER @@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", ")))) } +/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was +/// given it: a parameter error naming the blend modes unless the effect reads it as one +/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal. +fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects; + let key = "mode"; + let Some(v) = params.get(key) else { return Ok(()) }; + if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() { + return Ok(()); + } + let modes: Vec = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect(); + Err(bad(id, format!("`{key}` must be one of {}", modes.join(", ")))) +} + /// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id` /// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's /// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they @@ -1067,7 +1084,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = - (id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params")) + (id, super::effectcmd::requested_effect(params), params.get("params")) { check_effect_params(id, effect, given)?; } diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index cb364167a2..fb30bf3c5c 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -263,6 +263,56 @@ fn a_tone_curve_channel_it_does_not_have_is_refused() { assert_eq!(back.layers[0].children().unwrap()[0].appearance.effects[0].params["channel"], json!("alpha")); } +/// A Drop Shadow's or glow's `mode` that names no blend mode (which it drew as Normal) is refused +/// in new calls to `effect.apply`, `appearance.addEffect` and `effect.setParams`, with the modes it +/// takes, and the document and its undo history stay as they were. Blend-mode names in any +/// spelling pass, an omitted `mode` keeps the default, and an older saved step still plays. +#[test] +fn a_shadow_or_glow_mode_that_is_no_blend_mode_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"opacity": 50}})).unwrap(); + let state = |s: &Session| { + let st = s.active().unwrap(); + (st.doc.clone(), st.history.undo.len()) + }; + let before = state(&s); + let why = "`mode` must be one of normal, darken, multiply, colorBurn"; + for bad in [json!("multipy"), json!(""), json!("passThrough"), json!(null), json!(["multiply"]), json!(1), json!(false)] { + for (cmd, params) in [ + ("effect.setParams", json!({"index": 0, "params": {"mode": bad}})), + ("effect.apply", json!({"effect": "stylize.innerGlow", "params": {"mode": bad}})), + ("effect.apply", json!({"effect": null, "id": "stylize.dropShadow", "ids": [id], "params": {"mode": bad}})), + ("appearance.addEffect", json!({"effect": "stylize.outerGlow", "params": {"mode": bad}})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{cmd} {params}: {e}"); + let checked = s.check_params(cmd, ¶ms).unwrap_err().to_string(); + assert!(checked.contains(why), "{cmd} {params}: {checked}"); + assert!(state(&s) == before, "{cmd} {params} changed the document or its undo history"); + } + } + let effect = |s: &Session| s.active().unwrap().doc.layers[0].children().unwrap()[0].appearance.effects[0].clone(); + let shadow = effect(&s); + let drawn = vectorcraft_render::effects::merged_params(&shadow.id, &shadow.params); + assert_eq!(drawn["mode"], json!("multiply"), "an omitted mode keeps the default"); + for good in ["screen", "Color Burn", "color-burn", "COlor!!Burn#", "softLight", "LUMINOSITY"] { + let params = json!({"index": 0, "params": {"mode": good}}); + s.check_params("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + s.execute("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + assert_eq!(effect(&s).params["mode"], json!(good)); + } + s.replay("effect.setParams", &json!({"index": 0, "params": {"mode": "multipy"}})).unwrap(); + assert_eq!(effect(&s).params["mode"], json!("multipy")); + assert_eq!(vectorcraft_render::effects::blend_mode("multipy"), vectorcraft_color::BlendMode::Normal); + for mode in vectorcraft_color::BlendMode::ALL { + let id = vectorcraft_render::effects::blend_mode_id(mode); + assert_eq!(vectorcraft_render::effects::parse_blend_mode(&id), Some(mode)); + assert_eq!(vectorcraft_render::effects::blend_mode(&id), mode); + } +} + /// What a command adds to its own journal entry passes the check, so a recorded journal can be /// sent back through the control channel or MCP. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 813ed31d97..9d729c31d4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1465,6 +1465,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { params["dialog"] = json!(top.id.value().to_string()); } + if method == "ui.dialog.set" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::effect::normalize_set_mode(app, id, &mut params); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index bcfecb47e1..a765bebbc8 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -69,6 +69,26 @@ pub(crate) struct Open { asking: bool, } +/// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog. +pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) { + let Some(open) = app.effect_dialogs.effect.as_ref() else { return }; + if id != open.id || open.asking || !vectorcraft_effects::takes_blend_mode(&open.cx.id, "mode") { + return; + } + let normalize = |field: &mut Value| { + if field["field"] == "mode" + && let Some(mode) = field["value"].as_str().and_then(vectorcraft_effects::parse_blend_mode) + { + field["value"] = json!(vectorcraft_effects::blend_mode_id(mode)); + } + }; + if let Some(fields) = params.get_mut("fields").and_then(Value::as_array_mut) { + fields.iter_mut().for_each(normalize); + } else { + normalize(params); + } +} + /// `effect.dialog {effect, index?, item?}`: edit applied effect `index` of `item` (null: the /// object's effects; omitted: the active item's, else the object's) prefilled with its values, /// or add `effect`, first asking when that list already has it. diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 06bf617898..ef5b2a5ea4 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -150,6 +150,11 @@ fn generic_row(cx: &EffectCx, key: &str, default: &Value, relative: bool) -> Opt Param::number(key, label, n, 1.0, 2) } } + // The blend mode the effect draws in: the mode it draws a name in, Normal for one it doesn't know. + Value::String(text) if vectorcraft_effects::takes_blend_mode(id, key) => { + let mode = vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(text)); + Param::new(key, label, ParamKind::blend(crate::fields::effect_blend_modes(), Some(mode))) + } Value::String(text) => match options() { Some(list) => Param::new(key, label, ParamKind::choice(list, Some(text.clone()))), None if text.starts_with('#') => Param::new(key, label, ParamKind::color(None)), diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 6d81d18214..a8d20b7416 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -171,6 +171,13 @@ fn field_value(row: Option<&Param>, value: &Value) -> Option { }, // A pair of radio buttons over a flag (Relative / Absolute): the ids are "true" and "false". Some(ParamKind::Radio { .. }) if value.is_boolean() => value.as_bool().map(|b| FieldValue::Text(b.to_string())), + // Use the renderer's mode for each spelling, including Normal for unknown names and the effect's default for + // a legacy value that is not text. + Some(ParamKind::Blend { default, .. }) => value + .as_str() + .map(|s| vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(s))) + .or_else(|| default.clone()) + .map(FieldValue::Text), // A custom row's list, and one a key no row has carries through (an export's `artboards: [0, 1]`), stay JSON: a // list of whole numbers would read back as a grid, and one of two or three as a point or colour. Some(ParamKind::Custom(_)) | None if value.is_array() => Some(FieldValue::Json(value.clone())), diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1eeec2d52d..c45284ba5a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -213,6 +213,85 @@ fn effect_dialog_refuses_a_color_it_cannot_draw() { } } +/// Drop Shadow's, Inner Glow's and Outer Glow's Mode is a blend-mode menu of every mode the effect draws, opening on the +/// effect's default, in the dialog and in the Appearance panel's editor (the same rows over the stored values, where a +/// mode in another spelling shows as its menu entry). Picking Multiply in a glow's dialog stores `multiply`, and a mode +/// the menu lacks is refused as it is set. +#[test] +fn shadow_and_glow_dialogs_pick_mode_from_a_blend_mode_menu() { + use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, ParamKind}; + let modes: Vec = vectorcraft_doc::color::BlendMode::ALL.into_iter().map(vectorcraft_effects::blend_mode_id).collect(); + for (effect, default) in [("stylize.dropShadow", "multiply"), ("stylize.innerGlow", "screen"), ("stylize.outerGlow", "screen")] { + let mut app = app(); + for editing in [false, true] { + let cx = super::effect_params::EffectCx::new(&app, effect, editing); + let rows = super::effect_params::effect_params(&cx, &DialogFields::new()); + let row = rows.iter().find(|p| p.key == "mode").unwrap_or_else(|| panic!("{effect}: a Mode row")); + let ParamKind::Blend { modes: listed, default: shown, .. } = &row.kind else { panic!("{effect}: Mode is {:?}", row.kind) }; + let listed: Vec = listed.iter().map(|(entry, _)| entry.key.clone()).collect(); + assert_eq!(listed, modes, "{effect}"); + assert_eq!(shown.as_deref(), Some(default), "{effect}"); + let stored = serde_json::Map::from_iter([("mode".to_string(), json!("Color Burn"))]); + let fields = super::form::fields_of(&rows, &stored); + assert_eq!(fields.get("mode"), Some(&FieldValue::from("colorBurn")), "{effect}"); + } + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": effect})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(default), "{effect}"); + let (dialog, ctx) = (top(&app).0, app.ui_ctx.clone().expect("a window app")); + let refused = app.dialogs().expect("a window app").with(|h| h.set_json_field(&ctx, dialog, "mode", json!("multipy"))); + assert!(refused.is_err(), "{effect}: a mode the menu lacks"); + let want = if default == "multiply" { "colorBurn" } else { "multiply" }; + let mode = if default == "multiply" { "Color Burn" } else { "Multiply" }; + let params = match effect { + "stylize.dropShadow" => json!({"field": "mode", "value": mode}), + "stylize.innerGlow" => json!({"dialog": dialog.value(), "fields": [{"field": "mode", "value": mode}]}), + _ => json!({"dialog": dialog.value().to_string(), "fields": [{"field": "mode", "value": mode}]}), + }; + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", params); + assert_eq!(fields(&app)["mode"], json!(want)); + frame(&mut app, vec![]); + assert!(confirm(&mut app), "{effect}"); + let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert_eq!(n.appearance.effects[0].params["mode"], json!(want), "{effect}"); + } +} + +/// Confirming an untouched legacy mode keeps the file's value and does not add an undo step. +/// Choosing a different mode updates the stored value. +#[test] +fn unchanged_effect_dialog_preserves_legacy_blend_modes() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let effect = "stylize.dropShadow"; + app.run("effect.apply", json!({"ids": [id], "effect": effect, "item": null})).unwrap(); + for (old_mode, shown_mode) in [(Value::Null, "multiply"), (json!("multipy"), "normal")] { + app.session.replay("effect.setParams", &json!({"ids": [id], "index": 0, "item": null, "params": {"mode": old_mode}})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(shown_mode)); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params.get("mode"), Some(&old_mode)); + assert_eq!(state.history.undo.len(), before); + + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + let ctx = app.ui_ctx.clone().expect("a window app"); + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"field": "mode", "value": "Screen"})); + frame(&mut app, vec![]); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params["mode"], json!("screen")); + assert_eq!(state.history.undo.len(), before + 1); + } +} + /// After File › Document Color Mode, a Drop Shadow's, an Outer Glow's and a Shift to Color's dialog open on the /// converted color, and OK without editing it keeps the color. #[test] diff --git a/crates/ui-egui/src/fields.rs b/crates/ui-egui/src/fields.rs index f5eb2e33f2..a2f0e728d9 100644 --- a/crates/ui-egui/src/fields.rs +++ b/crates/ui-egui/src/fields.rs @@ -44,6 +44,15 @@ pub fn blend_entries() -> Vec> { framework_blend_entries(&entries, |entry| mode_label(entry.key)) } +/// The modes of an effect's blend-mode row. The entries use the stored IDs and translated names. +/// The framework uses each mode's key metadata to separate the existing groups. +pub fn effect_blend_modes() -> Vec<(BlendKeyEntry, Label)> { + blend_table() + .into_iter() + .map(|(mode, shortcut)| (BlendKeyEntry::new(vectorcraft_effects::blend_mode_id(mode), shortcut), mode_label(mode))) + .collect() +} + /// `mode`'s name in the interface language. fn mode_label(mode: BlendMode) -> Label { Label::from(crate::i18n::t(mode.label())) diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..570293be09 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2152,6 +2152,20 @@ one opens as before and draws it as `rgb`: → invalid parameters for `effect.setParams`: `channel` must be one of rgb, red, green, blue ``` +The `mode` of Drop Shadow, Inner Glow and Outer Glow must name one of the 16 blend modes: `normal`, `darken`, +`multiply`, `colorBurn`, `lighten`, `screen`, `colorDodge`, `overlay`, `softLight`, `hardLight`, `difference`, +`exclusion`, `hue`, `saturation`, `color` or `luminosity`. The name is read in any letter case and with any spaces, +hyphens or underscores (`Color Burn` and `color-burn` are `colorBurn`). An omitted `mode` keeps the effect's default +(`multiply` for Drop Shadow, `screen` for the glows). New `effect.apply` and `effect.setParams` calls refuse any other +value. An older document, action or journal with an unknown name still draws it as `normal`. A non-string value uses +the effect's default. The effect dialogs and the Appearance panel show `mode` as a blend-mode menu. +`ui.dialog.set` accepts the same blend-mode spellings. + +```json +{"id": "effect.setParams", "params": {"index": 0, "params": {"mode": "multipy"}}} +→ invalid parameters for `effect.setParams`: `mode` must be one of normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color, luminosity +``` + Radial Blur's Blur Center, `centerX` and `centerY`, must each be a number from 0 to 1: the share of the object's bounds across from its left edge and down from its top edge (0.5 each, the object's center, by default). The effect turns or zooms about that point, which moves and scales with the object. `effect.apply` and `effect.setParams` refuse any other From ab9f274fecc3c90c227ecab9f2c292ee5c303a7f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:10:58 -0800 Subject: [PATCH 60/63] Roll back a dialog preview when confirmation fails --- crates/ui-egui/src/dialogs/preview.rs | 50 +++++++++++++++++++++------ 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index c65dc15f45..60bf25a04a 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -54,17 +54,22 @@ impl LivePreview { if !app.session.in_interaction() { return app.run(cmd, params); } - let v = app.session.preview(cmd, ¶ms).map_err(|e| e.to_string())?; - let r = app.session.commit_interaction().map(|_| Value::Null).map_err(|e| e.to_string()); - if r.is_ok() - && let Some(w) = v.get("warning").and_then(Value::as_str) - { - app.status(w.to_string()); + let result = app.session.preview(cmd, ¶ms).and_then(|answer| { + app.session.commit_interaction()?; + Ok(answer) + }); + let answer = match result { + Ok(answer) => answer, + Err(error) => { + self.cancel(app); + return Err(error.to_string()); + } + }; + if let Some(warning) = answer.get("warning").and_then(Value::as_str) { + app.status(warning.to_string()); } - if r.is_ok() { - crate::plugin_runs::show_notice(app, cmd, &v); - } - r + crate::plugin_runs::show_notice(app, cmd, &answer); + Ok(Value::Null) } /// Cancel: rolls a shown preview back. @@ -106,6 +111,31 @@ mod tests { } } + #[test] + fn refused_confirmation_restores_the_art_and_ends_the_preview() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + let original = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + let mut preview = LivePreview::default(); + let fill = json!({"color": "#00a000"}); + assert!(matches!(preview.run(&mut app, true, "Fill Color", "paint.setFill", &fill), Some(Ok(_)))); + assert_ne!(app.session.doc().unwrap().doc, original); + assert!(preview.commit(&mut app, "paint.setFill", json!({"color": true})).is_err()); + assert!(!app.session.in_interaction(), "the refused edit left no open interaction"); + assert_eq!(app.session.doc().unwrap().doc, original); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + let mut next = LivePreview::default(); + assert!(matches!(next.run(&mut app, true, "Next Fill", "paint.setFill", &fill), Some(Ok(_)))); + next.commit(&mut app, "paint.setFill", fill).unwrap(); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Next Fill"); + } + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts /// from it; the status bar shows the warning of the typing's preview that keeping it applied. #[test] From 8a0b768626f971fbb12bde1f673b1102bb8b2143 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:12:40 -0800 Subject: [PATCH 61/63] Translate each numbered transparency grid color label as a whole --- crates/ui-egui/src/dialogs/document_setup.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 0d28e683a2..195d2759f9 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -389,7 +389,14 @@ fn grid_colors_row(setup: DocSetup) -> Param { picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + let number = (i + 1).to_string(); + let template = tl!("Grid Colors: {number}"); + let name = if template == "Grid Colors: {number}" { + // Keep the translated prefix for catalogs that have yet to add the complete label. + format!("{} {number}", tl!("Grid Colors:")) + } else { + crate::i18n::fmt(template, &[("number", &number)]) + }; let [r, g, b, _] = color.to_rgba8(1.0); let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); From cb89cd5ef39da2ddd3c547d22e6da1673cdd4cbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:09:16 -0800 Subject: [PATCH 62/63] Clear pending Type edit when the missing font prompt closes --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/canvas/tests.rs | 13 ++++++++++ crates/ui-egui/src/dialogs/confirm.rs | 36 +++++++++++++++------------ crates/ui-egui/src/lib.rs | 2 ++ 4 files changed, 36 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 89d64872e8..c083bf99a6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -232,6 +232,7 @@ impl VectorcraftApp { shortcuts_dialog: None, shortcut_overrides: Default::default(), told: Default::default(), + missing_font_edit_token: None, held: Default::default(), edit_scopes: Default::default(), command_dialog: Default::default(), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7c4cb6aebf..baee23876b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3599,7 +3599,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // Cancel: nothing is edited, and the document, its undo history and the selection stay. let (before, undo, selected) = (node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone()); + let cancelled_token = app.missing_font_edit_token.expect("the question's edit token"); answer(&mut app, false); + // A delayed approval for the cancelled question can no longer start an edit. + app.session.set_tool_option("missingFontEdit", &json!({"token": cancelled_token, "ok": true})); timed(&mut app, 1.5, vec![]); assert_eq!(app.session.tool_options()["editing"], json!(null)); assert!(!app.session.tool_wants_text()); @@ -3609,6 +3612,16 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // A new double-click asks again; OK edits with the caret where the type was clicked. double_click(&mut app, 3.0); assert!(asking(&app), "asked again"); + let replaced_token = app.missing_font_edit_token; + // A Type press sent through automation can replace the prompt before the user answers. + let view = app.view_info(); + let point = Point::new(b.x0 + b.width() * 0.25, b.center().y); + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, point.x, point.y), view); + } + assert_ne!(app.missing_font_edit_token, replaced_token); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(asking(&app), "the replacement question is open"); answer(&mut app, true); timed(&mut app, 3.5, vec![]); assert!(!asking(&app)); diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 12e13a36b3..72fb9a40a6 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -100,8 +100,7 @@ wrapped_dialog!(Question, StandardPrompt, KIND); pub(crate) struct Message(HostedAlert); wrapped_dialog!(Message, HostedAlert, MESSAGE); -/// The Type tool's question whether to edit type set in fonts that aren't available; its tag is the -/// tool's edit token. +/// The Type tool's question whether to edit type set in fonts that aren't available. pub(crate) struct MissingFontQuestion(StandardPrompt); wrapped_dialog!(MissingFontQuestion, StandardPrompt, MISSING_FONT_EDIT); @@ -215,13 +214,15 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str /// While another dialog is open (a press sent with `ui.pointer` reaches the tool then), that dialog /// stays and the Type tool forgets the edit, as Cancel would. pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { - let token = p.get("token").cloned().unwrap_or(Value::Null); + let Some(token) = p.get("token").and_then(Value::as_u64) else { + return; + }; let Some(dialogs) = app.dialogs() else { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; }; if app.any_dialog_open() && !dialogs.with(|host| host.is_open::()) { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; } let names = |k: &str| p.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::>(); @@ -234,14 +235,18 @@ pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { let prompt = StandardPrompt::custom(tl!("Edit type set in fonts that aren't available?")) .paragraph(detail) .button(PromptChoice::Proceed, tl!("OK")) - .button(PromptChoice::Cancel, tl!("Cancel")) - .tag(token); - dialogs.with(|host| host.open(MissingFontQuestion(prompt))); + .button(PromptChoice::Cancel, tl!("Cancel")); + dialogs.with(|host| { + host.open(MissingFontQuestion(prompt)); + // Replacing a prompt leaves its Cancel in the host. The tool is already waiting on the new token. + let _ = host.take::(); + }); + app.missing_font_edit_token = Some(token); } /// Give the Type tool the answer to [`ask_missing_font_edit`]'s question about the edit `token` /// names: with `ok` the edit starts at once; without, the tool forgets it. -pub(crate) fn answer_missing_font_edit(app: &mut VectorcraftApp, token: &Value, ok: bool) { +fn answer_missing_font_edit(app: &mut VectorcraftApp, token: u64, ok: bool) { app.session.set_tool_option("missingFontEdit", &json!({"token": token, "ok": ok})); if ok { let r = app.session.tool_poll(app.view_info(), false); @@ -277,13 +282,12 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { let Some(dialogs) = app.dialogs() else { return; }; - let (ok, token) = match dialogs.with(|host| host.take::()) { - None => return, - Some(DialogResult::Ok(mut answer)) => (answer.choice == PromptChoice::Proceed, answer.take_tag::()), - // PLAN: a question the host cancelled carries no tag, so the tool's token is unknown here. - Some(_) => (false, None), - }; - answer_missing_font_edit(app, &token.unwrap_or(Value::Null), ok); + if let Some(result) = dialogs.with(|host| host.take::()) + && let Some(token) = app.missing_font_edit_token.take() + { + let ok = matches!(result, DialogResult::Ok(answer) if answer.choice == PromptChoice::Proceed); + answer_missing_font_edit(app, token, ok); + } } /// The confirmation open now, if one is: its message and detail as shown, and the command OK runs. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 99d88741c1..6078ca0c07 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -266,6 +266,8 @@ pub struct VectorcraftApp { pub(crate) shortcut_overrides: Arc, /// Messages waiting for the dialog that shows them. pub(crate) told: dialogs::host::Told, + /// The Type tool's pending edit, kept even when the dialog closes without a prompt answer. + pub(crate) missing_font_edit_token: Option, /// The hosted dialogs whose OK the app answers, one record each. pub(crate) held: dialogs::host::Held, /// The undo step each value gesture in progress edits under: a scrub or a slider drag is one From 738f2373f04b2d322c96d0a4993989028938662e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 07:14:06 -0800 Subject: [PATCH 63/63] Translate the Legacy AI artboard grid accessible name --- crates/ui-egui/src/dialogs/save_options.rs | 2 +- .../ui-egui/src/dialogs/save_options/tests.rs | 20 +++++++++++-------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index 5713d3d27e..6576e17c73 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -422,7 +422,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } // PLAN: assumed TileGrid::show_items(ui, &source, &mut |key, _| tile) as the framework's stories call it; // the checks arrive as `CollectionEvent::Item(key, TilePartEvent::Check { .. })` in `response.events`. - let grid = TileGrid::new("Artboards").checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { + let grid = TileGrid::new(tl!("Artboards")).checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { let on = boards.get(*i).copied().unwrap_or(false); let mut tile = Tile::new(menus.names.get(*i).cloned().unwrap_or_default()).check(if on { ToggleState::On } else { ToggleState::Off }); if let Some(file) = files.get(*i).cloned().flatten() { diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index 8227766b4a..200b91f458 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -247,27 +247,31 @@ fn legacy_ai_saves_the_artboards_checked_in_its_picker() { assert_eq!(boards_in(&dialog(&mut app)), Some(vec![true, false, true, false])); } -/// The legacy picker's note and its count of checked artboards are in the window's accessibility tree, and the count -/// follows the checks. +/// The legacy picker's note, grid name and count are announced. The count follows the checks and +/// the grid name follows the interface language. #[test] -fn legacy_ai_names_its_note_and_artboard_count_in_the_accessibility_tree() { +fn legacy_ai_announces_its_note_grid_name_and_artboard_count() { let (mut app, _, _) = desktop("art.ai"); app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80})).unwrap(); save_as(&mut app, "file.saveAs"); set(&mut app, "aiVersion", json!("7")); - let labels = |app: &mut VectorcraftApp| -> Vec { + let labels = |app: &mut VectorcraftApp, role: Option| -> Vec { frame(app); let ctx = app.ui_ctx.clone().unwrap(); - let out = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.ui(ui)); + let out = crate::testing::app_frame(app, &ctx, egui::RawInput::default()); let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); - nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_owned).collect() + nodes.iter().filter(|(_, node)| role.is_none_or(|role| node.role() == role)).filter_map(|(_, node)| node.label()).map(str::to_owned).collect() }; - let shown = labels(&mut app); + let shown = labels(&mut app, None); assert!(shown.iter().any(|l| l.starts_with("A legacy .ai file holds one artboard")), "{shown:?}"); assert!(shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); set(&mut app, "boards", json!([true, false])); - let shown = labels(&mut app); + let shown = labels(&mut app, None); assert!(shown.iter().any(|l| l == "1 of 2 artboards") && !shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); + + app.session.prefs.interface_language = "fr".into(); + let shown = labels(&mut app, Some(egui::accesskit::Role::ListBox)); + assert!(shown.iter().any(|label| label == "Plans de travail"), "{shown:?}"); } #[test]