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 001/107] 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 002/107] 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 003/107] 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 004/107] =?UTF-8?q?Scale=20tool=20(#6324)=20docs:=20the=20?= =?UTF-8?q?22.5=C2=B0=20split=20and=20the=20level-start=20case=20are=20Vec?= =?UTF-8?q?torCraft'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 005/107] 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 6bca6cb51e55675110366e381a65e7fae20c875c Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:18:56 +0530 Subject: [PATCH 006/107] Variables panel: add row context menu --- crates/engine/src/cmd/variablecmds.rs | 8 +- crates/ui-egui/src/panels/variables.rs | 208 ++++++++++++++++++++++++- docs/gaps.md | 5 + docs/target-app-parity.md | 4 + 4 files changed, 220 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ea6647b7a4..db1a641f2f 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -23,7 +23,10 @@ use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection, use super::edit::selected_roots; use super::fileio::{absolute_path, read_file_head, write_file}; use super::textedit::set_story_text; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param}; +use super::{ + CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, checked_ids_param, cmd, has_doc, has_selection, links, + str_param, +}; mod csv; mod library; @@ -435,7 +438,8 @@ fn bind(s: &mut Session, p: &Value) -> Result { fn unbind(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.unbind"; - let ids = checked_ids_or_selection(s, p, C)?; + // Explicit bindings can include both a group and its children; retain every supplied ID. + let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { checked_ids_or_selection(s, p, C)? }; let name = defined_variable(s, p, C)?; let n = edit_variables(s, "Unbind Variable", |vars| { let mut n = 0; diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 1b6561f550..2d7e7568ac 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -94,12 +94,16 @@ fn headers(ui: &mut Ui, sort: VariableSort) -> Option { fn variable_row(ui: &mut Ui, row: &VarRow, selected: bool) -> Response { let t = Tokens::get(ui.ctx()); let h = ui.spacing().interact_size.y; - let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click()); + let (_, rect) = ui.allocate_space(vec2(ui.available_width(), h)); + let r = ui.interact(rect, ui.scope_id().with(("variable-row", &row.name)), Sense::click()); if selected { ui.painter().rect_filled(rect, 0.0, t.row_selected); } else if r.hovered() { ui.painter().rect_filled(rect, 0.0, t.hover); } + if r.has_focus() { + ui.painter().rect_stroke(rect, 0.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } // The kind's own icon, so a text variable and a visibility one read apart. let icon = match row.kind { VariableKind::Text => "type", @@ -389,6 +393,51 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if r.double_clicked() && !locked { crate::dialogs::variables::open(app, "variable.rename", Some(&row.name)); } + // Highlight without selecting the bound art: dynamic actions use the canvas selection. + let keyboard_menu = r.has_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::F10)); + if r.secondary_clicked() || keyboard_menu { + app.run("variable.highlight", json!({"variable": row.name})).ok(); + r.request_focus(); + } + let popup_id = egui::Popup::default_response_id(&r); + if keyboard_menu { + egui::Popup::open_id(ui.ctx(), popup_id); + } + let popup = egui::Popup::context_menu(&r); + // Keyboard-opened menus have no saved pointer position: anchor them to the row. + let popup = if r.context_menu_opened() && egui::Popup::position_of_id(ui.ctx(), popup_id).is_none() { popup.anchor(&r) } else { popup }; + popup.show(|ui| { + if widgets::menu_item(ui, tl!("Select Bound Object"), !row.bound.is_empty(), false) { + app.run("variable.highlight", json!({"variable": row.name})).ok(); + select_bound_object(app); + ui.close(); + } + if widgets::menu_item(ui, tl!("Variable Options…"), !locked, false) { + crate::dialogs::variables::open(app, "variable.rename", Some(&row.name)); + ui.close(); + } + if widgets::menu_item(ui, tl!("Unbind Variable"), !row.bound.is_empty() && !locked, false) { + app.run("variable.unbind", json!({"ids": row.bound, "variable": row.name})).ok(); + ui.close(); + } + ui.separator(); + for (label, command, enabled) in [ + (tl!("Make Text Dynamic"), "variable.makeTextDynamic", single_type), + (tl!("Make Visibility Dynamic"), "variable.makeVisibilityDynamic", has_selection), + (tl!("Make Image Dynamic"), "variable.makeImageDynamic", single_image), + (tl!("Make Graph Dynamic"), "variable.makeGraphDynamic", selection_graph), + ] { + if widgets::menu_item(ui, label, enabled && !locked, false) { + app.run(command, json!({})).ok(); + ui.close(); + } + } + ui.separator(); + if widgets::menu_item(ui, tl!("Delete Variable"), !locked, false) { + app.run("variable.delete", json!({"names": [row.name]})).ok(); + ui.close(); + } + }); } widgets::subheader(ui, tl!("Data Sets")); @@ -684,10 +733,14 @@ mod tests { /// Clicks the center of `node`. fn click(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node) { - use egui::{Event, Modifiers, PointerButton}; + self.click_button(app, node, egui::PointerButton::Primary); + } + + fn click_button(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node, button: egui::PointerButton) { + use egui::{Event, Modifiers}; let b = node.bounds().expect("bounds"); let pos = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); - let (button, none) = (PointerButton::Primary, Modifiers::default()); + let none = Modifiers::default(); self.frame(app, vec![Event::PointerMoved(pos), Event::PointerButton { pos, button, pressed: true, modifiers: none }]); self.frame(app, vec![Event::PointerButton { pos, button, pressed: false, modifiers: none }]); self.frame(app, vec![]); @@ -707,6 +760,155 @@ mod tests { } } + fn open_row_menu(d: &mut Driver, app: &mut VectorcraftApp, name: &str) -> Vec { + let nodes = d.nodes(app); + let row = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::ListItem && n.label() == Some(name)).expect("variable row"); + d.click_button(app, &row.1, egui::PointerButton::Secondary); + d.nodes(app).into_iter().filter(|(id, _)| !nodes.iter().any(|(before, _)| before == id)).map(|(_, n)| n).collect() + } + + fn menu_button(nodes: &[egui::accesskit::Node], label: &str) -> egui::accesskit::Node { + nodes.iter().find(|n| n.role() == egui::accesskit::Role::Button && n.label().is_some_and(|s| s.trim() == label)).expect(label).clone() + } + + #[test] + fn right_click_highlights_row_and_select_bound_object_uses_it() { + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Other", "kind": "visibility"})).unwrap(); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name · Alice"); + let st = app.session.active().unwrap(); + assert_eq!(highlighted_row(st).as_deref(), Some("Name")); + assert!(st.selection.objects.is_empty(), "right click must preserve canvas selection"); + let bound = st.doc.variables.objects_of("Name"); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + d.click(&mut app, &menu_button(&nodes, "Select Bound Object")); + assert_eq!(app.session.active().unwrap().selection.objects, bound); + } + + #[test] + fn keyboard_opens_focused_row_menu_without_changing_canvas_selection() { + use egui::{Event, Key, Modifiers}; + let mut app = app_with_data(); + let selected = app.session.active().unwrap().selection.objects.clone(); + let mut d = Driver::new(); + let nodes = d.nodes(&mut app); + let row_id = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::ListItem).unwrap().0; + let key = |key, modifiers| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + for _ in 0..20 { + if d.ctx.memory(|m| m.focused()).is_some_and(|id| id.value() == row_id.0) { + break; + } + d.frame(&mut app, vec![key(Key::Tab, Modifiers::NONE)]); + d.frame(&mut app, vec![]); + } + assert!(d.ctx.memory(|m| m.focused()).is_some_and(|id| id.value() == row_id.0), "Tab must focus the variable row"); + d.frame(&mut app, vec![key(Key::F10, Modifiers::SHIFT)]); + let nodes = d.nodes(&mut app).into_iter().map(|(_, n)| n).collect::>(); + assert!(egui::Popup::is_any_open(&d.ctx)); + assert!(!menu_button(&nodes, "Select Bound Object").is_disabled()); + assert_eq!(highlighted_row(app.session.active().unwrap()).as_deref(), Some("Name")); + assert_eq!(app.session.active().unwrap().selection.objects, selected); + d.frame(&mut app, vec![key(Key::Escape, Modifiers::NONE)]); + assert!(!egui::Popup::is_any_open(&d.ctx)); + } + + #[test] + fn context_menu_deletes_clicked_variable_in_one_undo_step() { + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Other", "kind": "visibility"})).unwrap(); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name · Alice"); + // A command can change the highlight while this row's menu remains open. + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + app.run("variable.sort", json!({"by": "name", "descending": true})).unwrap(); + d.frame(&mut app, vec![]); + d.click(&mut app, &menu_button(&nodes, "Delete Variable")); + let st = app.session.active().unwrap(); + assert!(st.doc.variables.variable("Name").is_none()); + assert!(st.doc.variables.variable("Other").is_some()); + assert_eq!(undo_steps(&app), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.variables.variable("Name").is_some()); + assert!(!app.session.active().unwrap().doc.variables.objects_of("Name").is_empty()); + } + + #[test] + fn context_menu_unbinds_only_clicked_variable() { + let mut app = app_with_data(); + let bound = app.session.active().unwrap().doc.variables.objects_of("Name"); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + app.run("variable.bind", json!({"variable": "Visible", "ids": [bound[0].0]})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name · Alice"); + d.click(&mut app, &menu_button(&nodes, "Unbind Variable")); + let st = app.session.active().unwrap(); + assert!(st.doc.variables.objects_of("Name").is_empty()); + assert_eq!(st.doc.variables.objects_of("Visible"), bound); + assert_eq!(undo_steps(&app), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Name"), bound); + } + + #[test] + fn context_menu_unbinds_both_group_and_nested_object() { + let mut app = app_with_data(); + let text = app.session.active().unwrap().doc.variables.objects_of("Name")[0]; + let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [text.0, rect]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + // Bind separately so both the group and its child have the variable. + for id in [group, text.0] { + app.run("variable.bind", json!({"variable": "Visible", "ids": [id]})).unwrap(); + } + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Visible").len(), 2); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Visible · Multiple objects"); + d.click(&mut app, &menu_button(&nodes, "Unbind Variable")); + assert!(app.session.active().unwrap().doc.variables.objects_of("Visible").is_empty()); + assert_eq!(undo_steps(&app), before + 1); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Name"), vec![text]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Visible").len(), 2); + } + + #[test] + fn context_menu_disables_edits_when_locked_and_selection_actions_when_empty() { + let mut app = app_with_data(); + app.run("variable.lock", json!({})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name · Alice"); + assert!(!menu_button(&nodes, "Select Bound Object").is_disabled()); + for label in [ + "Variable Options…", + "Unbind Variable", + "Make Text Dynamic", + "Make Visibility Dynamic", + "Make Image Dynamic", + "Make Graph Dynamic", + "Delete Variable", + ] { + assert!(menu_button(&nodes, label).is_disabled(), "{label}"); + } + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Unbound", "kind": "visibility"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let nodes = open_row_menu(&mut Driver::new(), &mut app, "Unbound"); + for label in + ["Select Bound Object", "Unbind Variable", "Make Text Dynamic", "Make Visibility Dynamic", "Make Image Dynamic", "Make Graph Dynamic"] + { + assert!(menu_button(&nodes, label).is_disabled(), "{label}"); + } + assert!(!menu_button(&nodes, "Delete Variable").is_disabled()); + } + fn set_names(app: &mut VectorcraftApp) -> Vec { let sets = app.run("dataset.list", json!({})).unwrap(); sets["datasets"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap_or_default().to_string()).collect() diff --git a/docs/gaps.md b/docs/gaps.md index 618b48ff4c..ce471c2c73 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -10,6 +10,8 @@ ## Feature submission evidence +Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. 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,6 +60,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. 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. | @@ -522,6 +525,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. 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. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..c9a3f6c22f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -30,6 +30,8 @@ ## Feature submission evidence +Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. 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. @@ -77,6 +79,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. 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. | | 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. | @@ -947,6 +950,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. - **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. - **Automation:** + - Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. - Variables: a visibility variable binds a locked layer, a locked object and objects inside a locked layer or group, and `dataset.select`, `dataset.next` and `dataset.prev` show and hide them without unlocking them; `dataset.list`, `dataset.capture` and `dataset.update` read whether they show. A text, image or graph variable refuses locked art. From c344a9a9d25812078d19d4ec6840bd82369659dd Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:24:37 +0530 Subject: [PATCH 007/107] docs: reconcile Variables panel context-menu evidence --- docs/gaps.md | 6 ++---- docs/target-app-parity.md | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index ce471c2c73..e72c583797 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 (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-20 · **Change:** minor (G12: Variables panel row context menus; 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. @@ -10,7 +10,7 @@ ## Feature submission evidence -Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. +- **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. 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. @@ -525,8 +525,6 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet -Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. 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. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c9a3f6c22f..fd0006b881 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -58,7 +58,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-20. 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. From fb591db314bbb746f7939bbfcb3a8b826ab27198 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:47:31 +0530 Subject: [PATCH 008/107] Variables panel: scope row menus and respect text bindings --- crates/ui-egui/src/panels/variables.rs | 82 ++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 2d7e7568ac..525d39b596 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -91,11 +91,11 @@ fn headers(ui: &mut Ui, sort: VariableSort) -> Option { /// Draw one variable row across the three columns: its kind's icon, its name and the object it /// drives. Each column clips its text to its own width. -fn variable_row(ui: &mut Ui, row: &VarRow, selected: bool) -> Response { +fn variable_row(ui: &mut Ui, row: &VarRow, selected: bool, doc_uid: u64) -> Response { let t = Tokens::get(ui.ctx()); let h = ui.spacing().interact_size.y; let (_, rect) = ui.allocate_space(vec2(ui.available_width(), h)); - let r = ui.interact(rect, ui.scope_id().with(("variable-row", &row.name)), Sense::click()); + let r = ui.interact(rect, ui.scope_id().with(("variable-row", doc_uid, &row.name)), Sense::click()); if selected { ui.painter().rect_filled(rect, 0.0, t.row_selected); } else if r.hovered() { @@ -282,7 +282,7 @@ struct Picked { has_selection: bool, /// Unbind needs a bound object under the selection, not just any selection. selection_bound: bool, - /// Make Text Dynamic needs exactly one type object: a text variable only drives type. + /// Make Text Dynamic needs one type object without an existing text variable. single_type: bool, /// Make Image Dynamic needs exactly one image object. single_image: bool, @@ -293,7 +293,15 @@ struct Picked { fn picked(st: &vectorcraft_engine::DocState) -> Picked { let selected: Vec = st.selection.objects.iter().map(|i| i.0).collect(); let selection_bound = selected.iter().any(|id| st.doc.variables.bindings.contains_key(&NodeId(*id))); - let single_type = matches!(selected.as_slice(), [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))); + let single_type = match selected.as_slice() { + [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) => st + .doc + .variables + .bindings + .get(&NodeId(*one)) + .is_none_or(|bound| !st.doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text && bound.contains(&v.name))), + _ => false, + }; let single_image = matches!(selected.as_slice(), [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))); let selection_graph = !selected.is_empty() && selected.iter().all(|id| st.doc.node(NodeId(*id)).is_some_and(|n| n.extras().graph.is_some())); Picked { has_selection: !selected.is_empty(), selected, selection_bound, single_type, single_image, selection_graph } @@ -337,6 +345,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Lock Variables: no variable is defined, deleted or renamed until they are unlocked. let locked = st.doc.variables.locked; let sort = st.variables_sort; + let doc_uid = st.uid; // The current data set across the top: its name in a box that renames it, the list that // chooses another, and the arrows that step through them. @@ -384,7 +393,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { widgets::dim_label(ui, tl!("None")); } for row in vars { - let r = variable_row(ui, row, highlighted.as_deref() == Some(row.name.as_str())); + let r = variable_row(ui, row, highlighted.as_deref() == Some(row.name.as_str()), doc_uid); // A click highlights the row and selects what it drives; a double click opens // Variable Options for it. if r.clicked() { @@ -879,6 +888,69 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Visible").len(), 2); } + #[test] + fn context_menu_cannot_act_on_same_named_variable_in_another_document() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + for label in ["Delete Variable", "Unbind Variable"] { + let mut app = app_with_data(); + let original = app.session.active().unwrap().doc.variables.clone(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 10, "y": 40, "text": "Alice"})).unwrap()["id"].clone(); + app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap(); + app.run("variable.bind", json!({"variable": "Name", "ids": [text]})).unwrap(); + let other = app.session.active().unwrap().doc.variables.clone(); + assert!(app.session.set_active(0)); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name · Alice"); + let action = menu_button(&nodes, label); + let target_node = d + .nodes(&mut app) + .into_iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::Button && n.label() == action.label()) + .expect("the open menu action") + .0; + assert!(app.session.set_active(1)); + assert!(!d.nodes(&mut app).iter().any(|(id, _)| *id == target_node), "{label}: the old menu carried over"); + // A queued accessibility click must not dispatch the old menu action in the new document. + d.frame( + &mut app, + vec![egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::Click, + target_node, + target_tree: TreeId::ROOT, + data: None, + })], + ); + assert_eq!(app.session.active().unwrap().doc.variables, other, "{label}: changed the second document"); + assert!(app.session.set_active(0)); + assert_eq!(app.session.active().unwrap().doc.variables, original, "{label}: changed the first document"); + } + } + + #[test] + fn context_menu_make_text_dynamic_requires_text_without_a_text_binding() { + let mut app = app_with_data(); + let text = app.session.active().unwrap().doc.variables.objects_of("Name")[0]; + app.run("select.set", json!({"ids": [text.0]})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name · Alice"); + assert!(menu_button(&nodes, "Make Text Dynamic").is_disabled()); + assert!(!menu_button(&nodes, "Make Visibility Dynamic").is_disabled()); + egui::Popup::close_all(&d.ctx); + app.run("variable.unbind", json!({"ids": [text.0], "variable": "Name"})).unwrap(); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + app.run("variable.bind", json!({"variable": "Visible", "ids": [text.0]})).unwrap(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + assert!(!menu_button(&nodes, "Make Text Dynamic").is_disabled(), "visibility bindings do not prevent a text variable"); + let before = undo_steps(&app); + d.click(&mut app, &menu_button(&nodes, "Make Text Dynamic")); + let vars = &app.session.active().unwrap().doc.variables; + let bound = vars.bindings.get(&text).unwrap(); + assert!(bound.contains("Visible")); + assert_eq!(vars.variables.iter().filter(|v| v.kind == VariableKind::Text && bound.contains(&v.name)).count(), 1); + assert_eq!(undo_steps(&app), before + 1); + } + #[test] fn context_menu_disables_edits_when_locked_and_selection_actions_when_empty() { let mut app = app_with_data(); From 0eaf435d6ab69bb73edbf54b048a3a80650e2124 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 06:08:48 -0800 Subject: [PATCH 009/107] Plug-ins: an edited grants file grants nothing, and its plug-ins ask again grants.json now holds {"version": 1, "grants": [...], "mac": "..."}, where mac is an HMAC-SHA-256 of the grants and of the plug-in folder, made with a random 32-byte key kept in the system key store: the Keychain on macOS, Credential Manager on Windows, the Secret Service on Linux and the BSDs. The MAC is compared in constant time. A file without a valid MAC for its folder (an edited or added grant, a removed or changed MAC, a file copied from another folder) grants nothing, and its plug-ins ask for approval again. This changes the default for existing files: a grants.json written by an earlier version is a plain list without a MAC, so its plug-ins ask once more, and the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only, nothing claims to persist, and the existing file is left as it is. The first key is made under a per-user lock and read back, so processes that approve their first plug-in at the same time keep one key. The web build keeps no grants file. New native-only dependencies of vectorcraft-engine: hmac, sha2, getrandom and keyring (all MIT OR Apache-2.0). --- Cargo.lock | 374 ++++++++++++++++++++-- apps/vectorcraft/src/prefs_dir.rs | 3 +- crates/engine/Cargo.toml | 7 + crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/src/store.rs | 175 ++++++++-- crates/engine/src/store/grant_keys.rs | 317 ++++++++++++++++++ crates/engine/src/tests/plugins.rs | 364 ++++++++++++++++++--- crates/engine/tests/plugin_clear_cache.rs | 1 + crates/engine/tests/plugin_fuzz.rs | 1 + crates/engine/tests/plugin_safe_mode.rs | 4 +- docs/mcp.md | 5 +- docs/plugins.md | 47 ++- docs/target-app-parity.md | 3 +- 13 files changed, 1209 insertions(+), 94 deletions(-) create mode 100644 crates/engine/src/store/grant_keys.rs diff --git a/Cargo.lock b/Cargo.lock index b8995c19ea..d687b2dd30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -123,10 +123,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", ] +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -140,6 +151,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "alloc-no-stdlib" version = "2.0.4" @@ -216,6 +236,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arboard" version = "3.7.0" @@ -550,6 +581,24 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -662,6 +711,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -724,6 +779,15 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "cc" version = "1.9.0" @@ -799,8 +863,18 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", - "inout", + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.6", ] [[package]] @@ -821,6 +895,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cmpv2" version = "0.2.0" @@ -839,7 +919,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "spki", "x509-cert", @@ -915,6 +995,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.9.4" @@ -980,6 +1066,12 @@ dependencies = [ "libm", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1363,7 +1455,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", @@ -1495,6 +1587,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1513,7 +1623,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der_derive", "flagset", "pem-rfc7468", @@ -1556,8 +1666,21 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -2614,6 +2737,33 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -2653,6 +2803,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -3027,6 +3186,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -3344,6 +3513,27 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "281c851dbae0de36d405299dd463126df4826dc32665c1314e931696b8cdee77" +dependencies = [ + "log", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -3547,7 +3737,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -3762,12 +3952,75 @@ dependencies = [ "memchr", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -4889,6 +5142,29 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-syntax" version = "0.8.11" @@ -5260,6 +5536,25 @@ dependencies = [ "tiny-skia 0.11.4", ] +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.4", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -5399,7 +5694,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -5410,7 +5705,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5464,12 +5770,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" dependencies = [ "aws-lc-rs", "base64 0.22.1", - "const-oid", + "const-oid 0.9.6", "der", - "digest", + "digest 0.10.7", "pem", "rand_core 0.10.1", - "sha2", + "sha2 0.10.9", "signature", "sigstore-types", "spki", @@ -5538,7 +5844,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand", @@ -5577,7 +5883,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -6827,12 +7133,15 @@ dependencies = [ "crc32fast", "encoding_rs", "flate2", + "getrandom 0.4.3", "hayro-ccitt", "heic-rs", + "hmac 0.12.1", "image", "jxl-color", "jxl-grid", "jxl-oxide", + "keyring", "kurbo 0.13.1", "log", "proptest", @@ -6842,6 +7151,7 @@ dependencies = [ "same-file", "serde", "serde_json", + "sha2 0.10.9", "skrifa 0.47.0", "thiserror 2.0.21", "tiff", @@ -7016,7 +7326,7 @@ dependencies = [ name = "vectorcraft-pdf" version = "0.24.1" dependencies = [ - "aes", + "aes 0.8.4", "chrono", "craft-image-codecs", "craft-pdf", @@ -7034,7 +7344,7 @@ dependencies = [ "objc2-core-graphics", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "siphasher", "skrifa 0.47.0", "smallvec", @@ -7059,7 +7369,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", @@ -7980,6 +8290,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -8317,7 +8640,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "sha1", "signature", @@ -8484,6 +8807,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 492e2ea7bf..c638086870 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) { } /// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones -/// installed from now on there. +/// installed from now on there. The key of the grants kept there is in the system's key store. pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) { if let Some(dir) = store_dir("Plug-ins") { + vectorcraft_engine::store::grant_keys::use_os_grant_keys(); session.attach_plugin_store(dir); } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 075211dc1a..4a393d890f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -84,6 +84,13 @@ same-file = "1.0.6" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true } rayon = { version = "1.12", optional = true } +# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the +# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on +# Linux. All MIT OR Apache-2.0. +hmac = "0.12.1" +sha2 = { version = "0.10", default-features = false } +getrandom = "0.4" +keyring = "4.2" [dev-dependencies] # JPEG XL files for the `.jxl` open and place tests. diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..338ecaf958 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1297,7 +1297,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 9c555d82f7..59ea6048d0 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -20,7 +20,9 @@ //! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional //! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins //! stored there that list permissions (id, module hash, permissions); a stored plug-in whose -//! permissions it doesn't grant is skipped with a log record, and stays in the folder. +//! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file +//! carries a MAC of its grants and its folder, made with a key the user's key store keeps +//! ([`grant_keys`]); a file without that MAC grants nothing. //! * **Plug-in settings and caches**: `storage/id-/` in the plug-in store, the id written as //! [`case_safe`] writes it, holds what a plug-in //! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a @@ -50,6 +52,8 @@ use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; use crate::Session; use crate::cmd::pdfcmds::{PRESET_FORMAT, PresetFile}; +pub mod grant_keys; + /// Files read from one store folder, at most (the rest are ignored). pub const MAX_STORE_FILES: usize = 1000; /// The largest PDF presets file read (a preset is a few kilobytes). @@ -721,7 +725,13 @@ impl Session { /// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's /// other grants as they are; with none left, remove the file. Entries this version can't use - /// are written back as they were, except one for `id`. A grants file that is too large, can't + /// are written back as they were, except one for `id`. The file is written with the MAC of its + /// grants for this folder ([`grant_keys`]), making the key when the key store holds none. A file + /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant + /// replaces it with a file that holds that grant alone, and removing one takes out the entry for + /// `id` and leaves the rest unsigned. When the key store can't be reached ([`Trust::Unknown`], or + /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry + /// for `id` stays. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and /// written in `turn`. → whether the store now holds what was asked (`false` without a folder, @@ -788,6 +798,21 @@ impl Session { if let Some(between) = AFTER_GRANTS_READ.take() { between(); } + match (file.trust, &grant) { + // Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for + // the session only, and one the file may still hold for `id` can't be removed. + (Trust::Unknown, Some(_)) => return false, + (Trust::Unknown, None) => return !file.names(id), + // The file grants nothing. A new grant replaces it with a signed file that holds that + // grant alone; removing one takes its entry out and leaves the rest unsigned. + (Trust::Unsigned, Some(_)) => { + log::warn!("replacing the stored plug-in grants {}: VectorCraft didn't write them for this folder", dir.join(GRANTS_FILE).display()); + file.grants.clear(); + file.other.clear(); + } + (Trust::Unsigned | Trust::Signed, _) => {} + } + let signed = file.trust == Trust::Signed || grant.is_some(); let others = file.other.len(); file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id)); let changed = match grant { @@ -802,16 +827,7 @@ impl Session { if entries.is_empty() { return take(dir, GRANTS_FILE); } - // The file is read back only up to its cap: written compactly when pretty-printed is larger, - // and not at all when that is too. - let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; - match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) { - Some(bytes) => put(dir, GRANTS_FILE, &bytes), - None => { - log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE)); - false - } - } + put_grants(dir, entries, signed) } /// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this @@ -1466,10 +1482,13 @@ impl Storage for PluginStorage { /// What the grants file of a plug-in store holds. #[derive(Default)] struct GrantsFile { - /// The grants this version can use, by plug-in id. + /// The grants this version can use, by plug-in id. They grant something only when the file is + /// [`Trust::Signed`]. grants: BTreeMap, /// The entries it can't use (a permission it doesn't know, an invalid id), as they were. other: Vec, + /// Whether VectorCraft wrote the grants for this folder. + trust: Trust, } impl GrantsFile { @@ -1479,6 +1498,103 @@ impl GrantsFile { } } +/// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]). +#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] +enum Trust { + /// There is no file, or it carries the MAC of its grants and folder made with the user's key. + #[default] + Signed, + /// It doesn't: an older version wrote it, another program wrote or changed it, it was copied + /// from another folder or machine, or the key store holds no key. It grants nothing. + Unsigned, + /// The key store can't be reached, so it is not known which. It grants nothing, and is left as + /// it is. + Unknown, +} + +/// The version of the grants file this version writes ([`SignedGrants::version`]). +const GRANTS_VERSION: u64 = 1; + +/// The grants file as this version writes it: the grants, and their MAC ([`grant_keys::sign`]) over +/// the list written as compact JSON. +#[derive(serde::Serialize, serde::Deserialize)] +struct SignedGrants { + version: u64, + grants: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + mac: Option, +} + +/// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it +/// is) with their MAC made with the key in use, as VectorCraft writes one. +#[cfg(test)] +pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec { + let entries: Vec = serde_json::from_str(grants).unwrap_or_default(); + let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}")); + let canonical = serde_json::to_vec(&entries).unwrap_or_default(); + let mac = grant_keys::sign(&key, &plugin_store_key(dir), &canonical).unwrap_or_default(); + format!(r#"{{"version":{GRANTS_VERSION},"grants":{grants},"mac":"{mac}"}}"#).into_bytes() +} + +/// Tests: the entries of the grants file `bytes`, signed or not. +#[cfg(test)] +pub(crate) fn grant_entries(bytes: &[u8]) -> Vec { + match serde_json::from_slice::(bytes) { + Ok(serde_json::Value::Array(entries)) => entries, + Ok(serde_json::Value::Object(mut file)) => match file.remove("grants") { + Some(serde_json::Value::Array(entries)) => entries, + _ => vec![], + }, + _ => vec![], + } +} + +/// Whether `signed`, read from the grants file of the plug-in store `dir`, carries the MAC of its +/// grants and of `dir` made with the user's key. +fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { + let (Some(tag), true) = (&signed.mac, signed.version == GRANTS_VERSION) else { return Trust::Unsigned }; + let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned }; + match grant_keys::current_key() { + Ok(Some(key)) if grant_keys::verify(&key, &plugin_store_key(dir), &grants, tag) => Trust::Signed, + Ok(_) => Trust::Unsigned, + Err(e) => { + log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + Trust::Unknown + } + } +} + +/// Write `entries` as the grants file of the plug-in store `dir`, with their MAC for `dir` when +/// `signed`, pretty-printed, or compact when that is larger than [`MAX_GRANTS_FILE`] → whether it went +/// there; the file is not written when the key can't be had or it is too large either way. +fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool { + let path = dir.join(GRANTS_FILE); + let file = if signed { + let key = match grant_keys::signing_key() { + Ok(key) => key, + Err(e) => { + log::warn!("not updating the stored plug-in grants {}: {e}", path.display()); + return false; + } + }; + let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &plugin_store_key(dir), &grants)); + let Some(mac) = mac else { return false }; + serde_json::to_value(SignedGrants { version: GRANTS_VERSION, grants: entries, mac: Some(mac) }) + } else { + serde_json::to_value(entries) + }; + // The file is read back only up to its cap: written compactly when pretty-printed is larger, + // and not at all when that is too. + let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; + match file.ok().and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) { + Some(bytes) => put(dir, GRANTS_FILE, &bytes), + None => { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + false + } + } +} + /// Why the grants file of a plug-in store gave no grants. struct GrantsError { /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is @@ -1489,8 +1605,10 @@ struct GrantsError { } /// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too -/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an -/// invalid id, is kept in [`GrantsFile::other`] with a log record. +/// large, can't be read or doesn't hold a list. A list without a MAC (as an older version wrote it), +/// or with one the user's key didn't make for `dir`, is [`Trust::Unsigned`] ([`trust_of`]). An +/// entry that doesn't parse as a grant, or names an invalid id, is kept in [`GrantsFile::other`] +/// with a log record. fn read_grants(dir: &Path) -> Result { let path = dir.join(GRANTS_FILE); let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) { @@ -1501,8 +1619,23 @@ fn read_grants(dir: &Path) -> Result { if bytes.len() as u64 > MAX_GRANTS_FILE { return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } - let entries = serde_json::from_slice::>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?; - let mut file = GrantsFile::default(); + let not_a_list = |why: String| GrantsError { unread: false, why }; + let (entries, trust) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { + serde_json::Value::Array(entries) => (entries, Trust::Unsigned), + serde_json::Value::Object(_) => { + let signed = serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))?; + let trust = trust_of(dir, &signed); + (signed.grants, trust) + } + _ => return Err(not_a_list("not a list of grants".into())), + }; + if trust == Trust::Unsigned { + log::warn!( + "the stored plug-in grants {} were not written by VectorCraft for this folder: the plug-ins that list permissions ask for them again", + path.display() + ); + } + let mut file = GrantsFile { trust, ..GrantsFile::default() }; let mut first_error = None; for entry in entries { let why = match serde_json::from_value::(entry.clone()) { @@ -1523,11 +1656,13 @@ fn read_grants(dir: &Path) -> Result { } /// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when -/// there is no grants file, and none, with a log record, when it is too large, can't be read or -/// doesn't hold a list. +/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked +/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a +/// list. fn stored_grants(dir: &Path) -> BTreeMap { match read_grants(dir) { - Ok(file) => file.grants, + Ok(file) if file.trust == Trust::Signed => file.grants, + Ok(_) => BTreeMap::new(), Err(e) => { log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); BTreeMap::new() diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs new file mode 100644 index 0000000000..a77cce19a7 --- /dev/null +++ b/crates/engine/src/store/grant_keys.rs @@ -0,0 +1,317 @@ +//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an +//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of +//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps +//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one +//! an older version wrote, one another program wrote or changed, one copied from another folder or +//! machine) grants nothing. +//! +//! The process uses one key store ([`set_grant_key_store`]); the apps use the system's +//! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key +//! store can't be reached: a grant holds for the session only. + +use std::path::Path; +use std::sync::{Arc, LazyLock, Mutex}; + +/// The length of a key, in bytes, and of the MAC. +pub const KEY_LEN: usize = 32; + +/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`. +#[derive(Clone, PartialEq, Eq)] +pub struct GrantKey([u8; KEY_LEN]); + +impl GrantKey { + /// The key with the bytes `bytes`. + pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self { + GrantKey(bytes) + } + + /// A new key from the system's random source. + #[cfg(not(target_arch = "wasm32"))] + pub fn random() -> Result { + let mut bytes = [0u8; KEY_LEN]; + getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?; + Ok(GrantKey(bytes)) + } + + /// The browser keeps no grants file. + #[cfg(target_arch = "wasm32")] + pub fn random() -> Result { + Err(KeyStoreError("there is no key store".into())) + } +} + +impl std::fmt::Debug for GrantKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("GrantKey(..)") + } +} + +/// Why a key store gave no key or didn't keep one. The message never holds key bytes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct KeyStoreError(pub String); + +/// Where the key of grants files is kept. +pub trait GrantKeyStore: Send + Sync { + /// The key kept, `None` when there is none; an error when the store can't be reached or read. + fn key(&self) -> Result, KeyStoreError>; + /// Keep `key` in place of any kept before. + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>; + /// The key kept, after making and keeping a new one when there is none. The key returned is the + /// one read back from the store, so a key another process kept first wins. + fn create_key(&self) -> Result { + if let Some(key) = self.key()? { + return Ok(key); + } + self.set_key(&GrantKey::random()?)?; + self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } +} + +/// A key store in memory: the key lasts as long as the store. For tests and embedders. +#[derive(Default)] +pub struct MemoryGrantKeys { + key: Mutex>, +} + +impl MemoryGrantKeys { + /// A store that holds `key`. + pub fn with_key(key: GrantKey) -> Self { + MemoryGrantKeys { key: Mutex::new(Some(key)) } + } +} + +impl GrantKeyStore for MemoryGrantKeys { + fn key(&self) -> Result, KeyStoreError> { + Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone()) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + *self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone()); + Ok(()) + } +} + +/// The key store of the process ([`set_grant_key_store`]). +static PROCESS_STORE: Mutex>> = Mutex::new(None); + +/// The one memory store of [`keep_grant_keys_in_memory`]. +static SHARED_MEMORY: LazyLock> = LazyLock::new(Arc::default); + +#[cfg(test)] +thread_local! { + /// Tests: the key store this thread uses in place of the process's. + pub(crate) static THREAD_STORE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no +/// key store, so grants hold for the session only). +pub fn set_grant_key_store(store: Option>) { + *PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store; +} + +/// Keep the key in memory for the rest of the process, one key for every caller: grants files +/// written in the process count in it, and not in another process. For tests. +pub fn keep_grant_keys_in_memory() { + let shared: Arc = SHARED_MEMORY.clone(); + set_grant_key_store(Some(shared)); +} + +/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service +/// `org.storytold.vectorcraft.plugin-grants`. +#[cfg(not(target_arch = "wasm32"))] +pub fn use_os_grant_keys() { + set_grant_key_store(Some(Arc::new(OsGrantKeys::default()))); +} + +/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory +/// store when the process set none. +fn current_store() -> Option> { + #[cfg(test)] + if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) { + return Some(store); + } + let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone(); + #[cfg(test)] + let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc)); + store +} + +/// The key kept for grants files: `None` when there is none yet, an error when there is no key +/// store or it can't be reached. +pub(crate) fn current_key() -> Result, KeyStoreError> { + current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key() +} + +/// The key to sign a grants file with: the one kept, else a new one, kept first +/// ([`GrantKeyStore::create_key`]). +pub(crate) fn signing_key() -> Result { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + match store.key()? { + Some(key) => Ok(key), + None => store.create_key(), + } +} + +/// The start of every MAC input: what it is a MAC of, and the version of the file. +#[cfg(not(target_arch = "wasm32"))] +const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0"; + +/// The MAC of `grants` (the grants list as compact JSON) in the plug-in store whose folder is +/// `folder` ([`super::plugin_store_key`]), made with `key`. +#[cfg(not(target_arch = "wasm32"))] +fn mac_of(key: &GrantKey, folder: &Path, grants: &[u8]) -> Option> { + use hmac::Mac; + let mut mac = hmac::Hmac::::new_from_slice(&key.0).ok()?; + let folder = folder.as_os_str().as_encoded_bytes(); + mac.update(DOMAIN); + mac.update(&(folder.len() as u64).to_be_bytes()); + mac.update(folder); + mac.update(grants); + Some(mac) +} + +/// The MAC of `grants` in `folder` with `key`, as 64 lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn sign(key: &GrantKey, folder: &Path, grants: &[u8]) -> Option { + use hmac::Mac; + Some(mac_of(key, folder, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Whether `tag` is the whole MAC of `grants` in `folder` with `key` ([`sign`]), compared in constant +/// time; a shorter or longer tag is not. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn verify(key: &GrantKey, folder: &Path, grants: &[u8], tag: &str) -> bool { + use hmac::Mac; + let Some(tag) = from_hex(tag) else { return false }; + mac_of(key, folder, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn sign(_: &GrantKey, _: &Path, _: &[u8]) -> Option { + None +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn verify(_: &GrantKey, _: &Path, _: &[u8], _: &str) -> bool { + false +} + +/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them; +/// `None` for anything else. +#[cfg(not(target_arch = "wasm32"))] +fn from_hex(tag: &str) -> Option> { + let digits = tag.as_bytes(); + let (pairs, rest) = digits.as_chunks::<2>(); + if !rest.is_empty() || pairs.len() > KEY_LEN { + return None; + } + let digit = |d: u8| match d { + b'0'..=b'9' => Some(d - b'0'), + b'a'..=b'f' => Some(d - b'a' + 10), + _ => None, + }; + pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect() +} + +/// The system's key store, through `keyring`. The key is read once and kept for the process. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct OsGrantKeys { + read: Mutex>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl OsGrantKeys { + const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants"; + const ACCOUNT: &str = "hmac-sha256-v1"; + + fn entry() -> Result { + keyring::Entry::new(Self::SERVICE, Self::ACCOUNT).map_err(store_error) + } + + /// The key the system's key store keeps, read from it. + fn stored(entry: &keyring::Entry) -> Result, KeyStoreError> { + match entry.get_secret() { + // A secret of another length is not a key this version made: there is none. + Ok(secret) => Ok(<[u8; KEY_LEN]>::try_from(secret.as_slice()).ok().map(GrantKey)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(store_error(e)), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl GrantKeyStore for OsGrantKeys { + fn key(&self) -> Result, KeyStoreError> { + let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(key) = read.as_ref() { + return Ok(Some(key.clone())); + } + Ok(Self::stored(&Self::entry()?)?.map(|key| read.insert(key).clone())) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); + Self::entry()?.set_secret(&key.0).map_err(store_error)?; + *read = Some(key.clone()); + Ok(()) + } + + /// Reads the key store again, not the key read before, and makes the key only while holding + /// [`creation_lock`], so that processes of this user that make the first key at the same time + /// all keep the first one made. + fn create_key(&self) -> Result { + let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); + let entry = Self::entry()?; + if let Some(key) = Self::stored(&entry)? { + return Ok(read.insert(key).clone()); + } + let _turn = creation_lock()?; + let key = match Self::stored(&entry)? { + Some(key) => key, + None => { + entry.set_secret(&GrantKey::random()?.0).map_err(store_error)?; + Self::stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))? + } + }; + *read = Some(key.clone()); + Ok(key) + } +} + +/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is +/// dropped, waiting while another process holds it: the temporary folder on Windows and macOS, +/// `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file can't be +/// locked: no key is made then. +#[cfg(not(target_arch = "wasm32"))] +fn creation_lock() -> Result { + #[cfg(any(windows, target_os = "macos"))] + let dir = Some(std::env::temp_dir()); + #[cfg(not(any(windows, target_os = "macos")))] + let dir = std::env::var_os("XDG_RUNTIME_DIR").map(std::path::PathBuf::from).filter(|dir| dir.is_absolute()); + let dir = dir.ok_or_else(|| KeyStoreError("there is no folder for the key's lock ($XDG_RUNTIME_DIR is not set)".into()))?; + let file = std::fs::File::options() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(dir.join("vectorcraft-plugin-grant-key.lock")) + .map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?; + file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?; + Ok(file) +} + +/// What a key store error says, without the secret some of them hold. +#[cfg(not(target_arch = "wasm32"))] +fn store_error(e: keyring::Error) -> KeyStoreError { + KeyStoreError(match e { + keyring::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"), + keyring::Error::PlatformFailure(e) => format!("the key store failed ({e})"), + keyring::Error::NoDefaultStore => "there is no key store".into(), + _ => "the key store can't read or keep the key".into(), + }) +} diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..13e66bda91 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2217,11 +2217,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { let other_wasm = asking(other, r#"["doc.read"]"#, &empty); let grants = folder.0.join("grants.json"); let ids = || -> Vec { - serde_json::from_slice::>(&std::fs::read(&grants).unwrap()) - .unwrap() - .iter() - .map(|e| e["id"].as_str().unwrap().to_string()) - .collect() + crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].as_str().unwrap().to_string()).collect() }; let mut s = session(); s.attach_plugin_store(folder.0.clone()); @@ -2241,7 +2237,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // A grant the store already holds for an id whose stored module lists no permissions. let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([entry, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); let mut third = session(); third.attach_plugin_store(folder.0.clone()); @@ -2251,7 +2247,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // So does an entry this version can't read, and a grant held only by the process. let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { id: id.into(), @@ -2311,8 +2307,8 @@ fn a_grant_that_cannot_be_removed_keeps_the_stored_module() { let file = s.stored_plugin_file(id).unwrap(); // An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which // makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", replace.clone()); @@ -2359,8 +2355,8 @@ fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() { run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS.set(true); @@ -2392,7 +2388,7 @@ fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]}); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); @@ -2425,8 +2421,8 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() { s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); std::fs::remove_file(&file).unwrap(); @@ -2455,13 +2451,14 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); vectorcraft_plugins::registry::remove(id); let mut next = session(); @@ -2471,12 +2468,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); assert!(refused.contains("doc.read"), "{refused}"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); next.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); // A load that can rewrite the file forgets the grant, and the store has nothing ignored again. - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); next.attach_plugin_store(folder.0.clone()); assert!(!grants.exists(), "the load removes the grant"); @@ -2486,7 +2483,7 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let mut third = session(); third.attach_plugin_store(folder.0.clone()); std::fs::remove_dir(&grants).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count"); // Attaching the same store again, with no stored module to try the removal for, keeps it out. @@ -2523,8 +2520,9 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); let mut first = session(); first.attach_plugin_store(folder.0.clone()); let inside = folder.0.join("inside"); @@ -2534,7 +2532,7 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); let file = first.stored_plugin_file(id).unwrap(); @@ -2554,13 +2552,13 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { later.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); other.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); other.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't"); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); for s in [&mut first, &mut other, &mut later] { assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); @@ -2618,7 +2616,7 @@ fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() { let mut other = session(); other.attach_plugin_store(alias); std::fs::create_dir(&dir).unwrap(); - std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(&dir, &json!([entry]).to_string())).unwrap(); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); first.ignore_stored_grant(id, first.grant_writes()); @@ -2659,11 +2657,10 @@ fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() { let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins")); for dir in [&old, &new] { std::fs::create_dir(dir).unwrap(); - std::fs::write(dir.join("grants.json"), &recorded).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(dir, &json!([entry]).to_string())).unwrap(); } std::os::unix::fs::symlink(&old, &link).unwrap(); let mut linked = session(); @@ -2730,8 +2727,8 @@ fn a_grant_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); std::fs::create_dir_all(&data).unwrap(); @@ -2789,8 +2786,8 @@ fn settings_that_cannot_be_moved_back_are_reported_and_moved_back_later() { run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); let settings = br#"{"zoom":"aGVsbG8="}"#; @@ -3031,7 +3028,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() { // A malformed hash is no wildcard, even for the module on disk. let upper = sha256_hex(&first).to_uppercase(); for hash in ["", "00", upper.as_str()] { - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); assert!(!starts(), "hash {hash:?}"); } @@ -3091,11 +3092,11 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() { // The grants file is full: the new grant, which is longer, doesn't fit. let cap = 1 << 20; - let mut entries: Vec = serde_json::from_slice(&recorded).unwrap(); + let mut entries: Vec = crate::store::grant_entries(&recorded); entries.push(json!({"id": "", "pad": ""})); - let room = cap - serde_json::to_vec(&entries).unwrap().len(); + let room = cap - crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()).len(); *entries.last_mut().unwrap() = json!({"id": "", "pad": "x".repeat(room)}); - let full = serde_json::to_vec(&entries).unwrap(); + let full = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()); assert_eq!(full.len(), cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", update.clone()); @@ -3335,7 +3336,7 @@ fn tell_when_waiting(waiting: std::sync::mpsc::Sender<&'static str>) { /// The ids `grants.json` in `dir` holds grants for, and the hash of each. fn stored_grant_hashes(dir: &std::path::Path) -> std::collections::BTreeMap { - let entries: Vec = serde_json::from_slice(&std::fs::read(dir.join("grants.json")).unwrap()).unwrap(); + let entries = crate::store::grant_entries(&std::fs::read(dir.join("grants.json")).unwrap()); entries.iter().map(|e| (e["id"].as_str().unwrap().to_string(), e["hash"].as_str().unwrap().to_string())).collect() } @@ -3637,8 +3638,8 @@ fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off( assert!(!disabled.is_empty()); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); @@ -4099,7 +4100,7 @@ fn a_grant_covers_only_the_module_it_was_given_to() { // A kept grant that records no hash, or an empty one, covers no module: the stored module isn't // installed at the next start and `plugin.inspect` asks for approval. for entry in [json!({"id": id, "permissions": ["settings", "cache"]}), json!({"id": id, "hash": "", "permissions": ["settings", "cache"]})] { - std::fs::write(folder.0.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(folder.0.join("grants.json"), crate::store::signed_grants_file(&folder.0, &json!([entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::revoke(id); let mut again = session(); @@ -4130,9 +4131,9 @@ fn grants_this_version_cant_read_are_kept() { let invalid = json!({"id": "bad id/", "hash": "00", "permissions": ["doc.read"]}); let grant = json!({"id": kept, "hash": vectorcraft_plugins::permissions::sha256_hex(&kept_wasm), "permissions": ["doc.read"]}); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([future, grant, invalid])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, grant, invalid]).to_string())).unwrap(); std::fs::write(folder.0.join("kept.wasm"), &kept_wasm).unwrap(); - let entries = || serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap(); + let entries = || crate::store::grant_entries(&std::fs::read(&grants).unwrap()); let mut s = session(); s.attach_plugin_store(folder.0.clone()); assert!(vectorcraft_plugins::registry::get(kept).is_some(), "the entries this version can't read don't drop the grant next to them"); @@ -4166,7 +4167,7 @@ fn grants_this_version_cant_read_are_kept() { // and left as it is when even compact would. let cap = 1 << 20; let many: Vec = (0..14_000).map(|i| json!({"id": format!("x.{i}"), "hash": "00", "permissions": ["ui.panel"]})).collect(); - let compact = serde_json::to_vec(&many).unwrap(); + let compact = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&many).unwrap()); assert!(compact.len() < cap && serde_json::to_vec_pretty(&many).unwrap().len() > cap); std::fs::write(&grants, &compact).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); @@ -4176,13 +4177,290 @@ fn grants_this_version_cant_read_are_kept() { let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm)})); assert_eq!(inspected["needsApproval"], json!(false), "the compact file is read back"); run(&mut s, "plugin.remove", json!({"id": added})); - let full = serde_json::to_vec(&json!([{"id": "x.full", "hash": "0".repeat(cap - 100), "permissions": ["ui.panel"]}])).unwrap(); + let full = crate::store::signed_grants_file( + &folder.0, + &json!([{"id": "x.full", "hash": "0".repeat(cap - 250), "permissions": ["ui.panel"]}]).to_string(), + ); + assert!(full.len() < cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); assert_eq!(std::fs::read(&grants).unwrap(), full, "not written past the cap"); run(&mut s, "plugin.remove", json!({"id": added})); } +/// Tests: the key store `store` on this thread until the guard is dropped. +struct ThreadKeys; + +impl ThreadKeys { + fn using(store: impl crate::store::grant_keys::GrantKeyStore + 'static) -> Self { + crate::store::grant_keys::THREAD_STORE.set(Some(std::sync::Arc::new(store))); + ThreadKeys + } +} + +impl Drop for ThreadKeys { + fn drop(&mut self) { + crate::store::grant_keys::THREAD_STORE.set(None); + } +} + +/// A key store that is locked or can't be reached. +struct UnreachableKeys; + +impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } +} + +/// Whether the stored plug-in `id` loads from the plug-in store `dir` at a new start, and whether +/// `plugin.inspect` of `data` (its module) then asks for approval. +fn starts_from(dir: &std::path::Path, id: &str, data: &str) -> (bool, bool) { + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(dir.to_path_buf()); + let asks = run(&mut next, "plugin.inspect", json!({"dataBase64": data}))["needsApproval"] == json!(true); + (vectorcraft_plugins::registry::get(id).is_some(), asks) +} + +/// The grants file as VectorCraft wrote it keeps its grants; once it is changed outside VectorCraft +/// it grants nothing, and its plug-ins ask again: a grant given more permissions, a grant added, the +/// MAC taken out or cut short, a MAC made with another key, the file cut short, and the file copied +/// into another plug-in folder. +#[test] +fn a_grants_file_changed_outside_vectorcraft_grants_nothing() { + use crate::store::grant_keys::{GrantKey, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-signed"); + let copy = crate::tests_links::Folder::new("plugin-store-signed-copy"); + let id = "test.engine.permissions.signed"; + let added = "test.engine.permissions.signedadded"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let added_wasm = asking(added, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, added_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&added_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let added_file = folder.0.join(format!("{}.wasm", crate::store::file_stem(added))); + std::fs::write(&added_file, &added_wasm).unwrap(); + let written = std::fs::read(&grants).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file as written keeps its grant"); + + let file: Value = serde_json::from_slice(&written).unwrap(); + let with = |change: &dyn Fn(&mut Value)| { + let mut file = file.clone(); + change(&mut file); + serde_json::to_vec(&file).unwrap() + }; + let other_key = { + let _other = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([7; 32]))); + crate::store::signed_grants_file(&folder.0, &file["grants"].to_string()) + }; + let tag = file["mac"].as_str().unwrap().to_string(); + let changed: [(&str, Vec); 6] = [ + ("a permission added", with(&|f| f["grants"][0]["permissions"] = json!(["doc.read", "doc.write"]))), + ( + "a grant added", + with(&|f| f["grants"].as_array_mut().unwrap().push(json!({"id": added, "hash": sha256_hex(&added_wasm), "permissions": ["doc.read"]}))), + ), + ("the MAC taken out", with(&|f| _ = f.as_object_mut().unwrap().remove("mac"))), + ("the MAC cut short", with(&|f| f["mac"] = json!(tag[..32]))), + ("a MAC made with another key", other_key), + ("the file cut short", written[..written.len() - 2].to_vec()), + ]; + for (what, bytes) in changed { + std::fs::write(&grants, &bytes).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{what}"); + assert_eq!(starts_from(&folder.0, added, &added_data), (false, true), "{what}"); + assert_eq!(std::fs::read(&grants).unwrap(), bytes, "{what}: the file is left as it is"); + } + + std::fs::write(&grants, &written).unwrap(); + std::fs::write(copy.0.join("copied.wasm"), &wasm).unwrap(); + std::fs::write(copy.0.join("grants.json"), &written).unwrap(); + assert_eq!(starts_from(©.0, id, &data), (false, true), "copied into another folder"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file left as written keeps its grant"); + std::fs::remove_file(&added_file).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grants file in the form an older version wrote, a plain list, grants nothing. Approving a +/// plug-in again replaces it with a signed file that holds that grant alone; removing a plug-in takes +/// its entry out and leaves the rest unsigned. +#[test] +fn an_unsigned_grants_file_is_replaced_by_the_next_approval() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-unsigned"); + let id = "test.engine.permissions.unsigned"; + let other = "test.engine.permissions.unsignedother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let entry = |id: &str, wasm: &[u8]| json!({"id": id, "hash": sha256_hex(wasm), "permissions": ["doc.read"]}); + let unsigned = serde_json::to_vec(&json!([entry(id, &wasm), entry(other, &other_wasm)])).unwrap(); + std::fs::write(&grants, &unsigned).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "an unsigned list grants nothing"); + assert_eq!(std::fs::read(&grants).unwrap(), unsigned, "and is left as it is"); + + // `other` isn't installed, so the removal reports it as not found after removing its entry. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.execute("plugin.remove", &json!({"id": other})).is_err()); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "the removal takes its entry out"); + assert!(std::fs::read(&grants).unwrap().starts_with(b"["), "and leaves the rest unsigned"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true)); + + std::fs::write(&grants, &unsigned).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the approval counts at the next start"); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); +} + +/// With no key in the key store, a signed grants file grants nothing; the next approval makes a key +/// and signs a file that holds that grant alone. +#[test] +fn a_grants_file_without_its_key_is_replaced_by_the_next_approval() { + use crate::store::grant_keys::{GrantKey, GrantKeyStore, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-no-key"); + let id = "test.engine.permissions.nokey"; + let other = "test.engine.permissions.nokeyother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let list = json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}, {"id": other, "hash": "0".repeat(64), "permissions": ["doc.read"]}]); + let signed = { + let _old = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([3; 32]))); + crate::store::signed_grants_file(&folder.0, &list.to_string()) + }; + std::fs::write(&grants, &signed).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + let keys = std::sync::Arc::new(MemoryGrantKeys::default()); + struct Shared(std::sync::Arc); + impl GrantKeyStore for Shared { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + self.0.key() + } + fn set_key(&self, key: &GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + self.0.set_key(key) + } + } + let _keys = ThreadKeys::using(Shared(keys.clone())); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "no key, no grant"); + assert!(keys.key().unwrap().is_none(), "reading makes no key"); + assert_eq!(std::fs::read(&grants).unwrap(), signed, "the file is left as it is"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert!(keys.key().unwrap().is_some(), "the approval makes a key"); + let ids: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect(); + assert_eq!(ids, vec![json!(id)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// When the key store can't be reached, no grants file grants anything and none is written: an +/// approval holds for the session only, the stored module isn't replaced, and a grant the file may +/// hold can't be removed. +#[test] +fn an_unreachable_key_store_keeps_approvals_in_the_session() { + let folder = crate::tests_links::Folder::new("plugin-store-unreachable-keys"); + let id = "test.engine.permissions.unreachable"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let written = std::fs::read(&grants).unwrap(); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + + let locked = ThreadKeys::using(UnreachableKeys); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the stored grant can't be checked"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let changed = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null})); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read"], "replace": true})); + assert_eq!( + vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), + Some(vectorcraft_plugins::permissions::sha256_hex(&changed)), + "it runs in this session" + ); + assert_eq!(std::fs::read(&grants).unwrap(), written, "the grants file is left as it is"); + assert_eq!(std::fs::read(&module).unwrap(), wasm, "the store keeps the module its grant covers"); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}"); + assert_eq!(std::fs::read(&grants).unwrap(), written); + + drop(locked); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the grant counts once the key store can be reached"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); +} + +/// A MAC is made over the grants and the folder, and only the whole MAC of the same key, grants and +/// folder verifies. A key's bytes are never printed. +#[test] +fn a_grants_mac_verifies_only_for_its_key_grants_and_folder() { + use crate::store::grant_keys::{GrantKey, sign, verify}; + let (key, other) = (GrantKey::from_bytes([1; 32]), GrantKey::from_bytes([2; 32])); + let folder = std::path::Path::new("/plug-ins"); + let tag = sign(&key, folder, b"[]").unwrap(); + assert_eq!(tag.len(), 64); + assert!(verify(&key, folder, b"[]", &tag)); + assert!(!verify(&other, folder, b"[]", &tag), "another key"); + assert!(!verify(&key, std::path::Path::new("/other"), b"[]", &tag), "another folder"); + assert!(!verify(&key, folder, b"[ ]", &tag), "other grants"); + assert!(!verify(&key, folder, b"[]", &tag[..62]), "a MAC cut short"); + assert!(!verify(&key, folder, b"[]", &tag.to_uppercase()), "upper case"); + assert!(!verify(&key, folder, b"[]", "")); + assert_eq!(format!("{key:?}"), "GrantKey(..)"); +} + +/// A key store where another process keeps its key between this one's read and its write, and +/// that write does not replace it. +struct KeptFirstElsewhere { + reads: std::sync::Mutex, +} + +impl crate::store::grant_keys::GrantKeyStore for KeptFirstElsewhere { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + let mut reads = self.reads.lock().unwrap(); + *reads += 1; + // signing_key and create_key each read once before the write. + Ok((*reads > 2).then(|| crate::store::grant_keys::GrantKey::from_bytes([7; 32]))) + } + + fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } +} + +#[test] +fn a_new_grants_key_is_the_one_the_key_store_kept() { + use crate::store::grant_keys::{GrantKey, sign, verify}; + let _keys = ThreadKeys::using(KeptFirstElsewhere { reads: std::sync::Mutex::new(0) }); + let key = crate::store::grant_keys::signing_key().unwrap(); + assert_eq!(key, GrantKey::from_bytes([7; 32]), "the key kept first signs"); + let folder = std::path::Path::new("/plug-ins"); + assert!(verify(&GrantKey::from_bytes([7; 32]), folder, b"[]", &sign(&key, folder, b"[]").unwrap())); +} + /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next /// start without asking, with its budget. #[test] diff --git a/crates/engine/tests/plugin_clear_cache.rs b/crates/engine/tests/plugin_clear_cache.rs index 7a323390c9..488c094c63 100644 --- a/crates/engine/tests/plugin_clear_cache.rs +++ b/crates/engine/tests/plugin_clear_cache.rs @@ -39,6 +39,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() { let _ = std::fs::remove_dir_all(&folder); std::fs::create_dir_all(&folder).unwrap(); let ids = ["test.clearcache.a", "test.clearcache.b"]; + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 20546835c1..59091858cb 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -914,6 +914,7 @@ proptest! { let store = Store(std::env::temp_dir().join(format!("vectorcraft-plugin-fuzz-storage-{}", std::process::id()))); let _ = std::fs::remove_dir_all(&store.0); let folder = store.0.clone(); + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.attach_plugin_store(folder.clone()); diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index a469e68f20..d9448e23a2 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -59,11 +59,13 @@ fn installed(id: &str) -> bool { vectorcraft_plugins::registry::get(id).is_some() } -/// A new launch: nothing installed, the plug-in folder `dir` attached. +/// A new launch: nothing installed, the plug-in folder `dir` attached, its grants' key kept in +/// memory. fn launch(dir: &std::path::Path) -> Session { for p in vectorcraft_plugins::registry::list() { vectorcraft_plugins::registry::remove(p.id()); } + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.attach_plugin_store(dir.to_path_buf()); s diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..812e3b9446 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13223,7 +13223,10 @@ naming the permissions needed. With `VECTORCRAFT_NO_PREFS` set there is no store flag lasts for that session only. In other sessions the approval, or a `grant` accepted under the flag, is kept with the module's hash, counts as approved in later sessions and in the desktop app, and covers only that module: the same bytes install again without one, also from a headless session that reads the same `grants.json`, and a module -with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. `plugin.remove` +with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. A +`grants.json` that does not carry VectorCraft's MAC for its folder (see [plug-ins](plugins.md#grants-file-integrity)) +grants nothing, and its plug-ins have `needsApproval: true` again. When the system key store can't be reached, an +approval lasts for that session only and the file is left as it is. `plugin.remove` forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When diff --git a/docs/plugins.md b/docs/plugins.md index 7e6dd26185..a2571e1ff3 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -261,8 +261,10 @@ capability model proposed for PhotoCraft plug-ins `grants.json`, and installs a module that lists permissions only under a grant recorded for this very module, also when it loads the Additional Plug-ins Folder. The approval does not protect against native code linked into VectorCraft or against another program running as the same user, which can change the files in the `Plug-ins` - folder. `grants.json` is not signed, so such a program can add a grant to it. `--allow-plugin-grants` is a choice - the person starting a headless session makes. + folder. `grants.json` carries a MAC made with a key kept in the system key store ([grants file + integrity](#grants-file-integrity)), so a program that only edits the file can't add a grant to it; one running as + the same user can still read the key or change VectorCraft. `--allow-plugin-grants` is a choice the person starting + a headless session makes. - **Replacing asks first.** When the file is another module than the plug-in installed with its id, or, with none installed, its id has settings and a cache in the `Plug-ins` folder, Install Plug-in… and File › Open show its id and SHA-256 and ask whether to install it in place of that plug-in, which gives it the settings and cache kept for @@ -300,8 +302,8 @@ capability model proposed for PhotoCraft plug-ins it held and `grants.json` keeps the grant. The new module runs until the session ends. When the grant can't be removed and the module already stored can't be read back or written back, the new module stays in the folder, and the grant stops counting. The grant also stops counting when the folder held no module for that id. A - `grants.json` larger than 1 MiB, or one that is not a JSON list, grants nothing: the new module stays in the folder, - and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be + `grants.json` larger than 1 MiB, or one that is neither a grants object nor a JSON list, grants nothing: the new + module stays in the folder, and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be removed. When VectorCraft loads the `Plug-ins` folder, it forgets any grant for an id whose stored module lists no permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant stops counting, including for the next load, which tries the removal again. A grant that stops counting in either of these cases @@ -315,8 +317,8 @@ capability model proposed for PhotoCraft plug-ins covers. An entry of `grants.json` that this version can't use (a permission it doesn't know, an invalid id) is skipped and stays in the file until its plug-in is granted again, replaced by a module that lists no permissions, or removed. When such an entry can't be removed from the file, `plugin.install` and `plugin.remove` treat it as a grant - that can't be removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written - larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for + that can't be removed. A `grants.json` that is neither a grants object nor a JSON list is never overwritten, and + the file is never written larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for `plugin.install`, `plugin.inspect`, `plugin.reload` and the Additional Plug-ins Folder. At startup, a stored plug-in is skipped when no grant covers its bytes and the permissions it lists. The Additional Plug-ins Folder and `plugin.reload` install only plug-ins that such a grant covers, and report the others. A module without a @@ -354,6 +356,39 @@ geometry, fill rule, reference box and the paints the effect is given: a plug-in changes. Failures are cached too. The swatches and patterns a painted result names are checked against the document each time it is drawn, and a paint linked to a global swatch is drawn in that swatch's current color at its own tint. +#### Grants file integrity + +`grants.json` holds the grants in a JSON object, `{"version": 1, "grants": [...], "mac": "..."}`. `mac` is an +HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the `grants` list +written as compact JSON and of the folder the file is in. The key is 32 random bytes that VectorCraft makes when it +records the first grant. VectorCraft keeps the key in the system key store, as the secret of the account +`hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, and never in a file: + +- On macOS the key is in the user's Keychain. +- On Windows the key is a generic credential in Credential Manager. +- On Linux and the BSDs the key is in the Secret Service, for example GNOME Keyring. When its collection is locked, + the desktop may ask to unlock it. + +VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in the temporary folder on Windows and +macOS, and in `$XDG_RUNTIME_DIR` elsewhere. When that file can't be locked, or `$XDG_RUNTIME_DIR` is not set, no key +is made, and approvals last for the session only, as when the key store can't be reached. + +VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its grants and its folder grants +nothing, and each plug-in it names that lists permissions asks for approval again. This covers a file that an earlier +version wrote (a plain JSON list), a grant that another program edited or added, a file whose `mac` was removed or +changed, a file copied from another `Plug-ins` folder or another computer, and a file whose key is no longer in the key +store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when +the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists +no permissions under that id, or a folder load that forgets the grant), VectorCraft takes that entry out of such a file +and leaves the rest unsigned. + +When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no +`grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored +for the id is not replaced, and `plugin.remove` of a plug-in that the file names returns an error, as for a grant that +can't be removed. With `VECTORCRAFT_NO_PREFS` set there is no plug-in store, and the web build keeps no grants file. The +MAC does not protect against another program running as the same user, which can read the key from the key store or +change VectorCraft itself. + ## ABI v1 A plug-in is a core WebAssembly module (MVP + these post-MVP features: mutable globals, sign extension, saturating diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..c8eff38c84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2653,13 +2653,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. -- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval waits before OK (G17):** the approval dialog's OK stays disabled until its question has been on screen in the focused window for half a second, VectorCraft's own value; a click, Enter, Space, or a press begun before then installs nothing, and the dialog stays open. The wait starts over for every new question, even one that reads the same, and when the window gets the focus back, so a question swapped in just before a click is not approved by it. Cancel works at once. Regressions: `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **An edited grants file grants nothing (G17):** `grants.json` carries an HMAC-SHA-256 of its grants and its folder, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time. A file without that MAC (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. From 22c0da7476e42ad82cb0f3cc0f3617a62ec92891 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:28:04 -0800 Subject: [PATCH 010/107] Plug-ins: an earlier copy of the grants file grants nothing The key store now keeps a generation for each plug-in folder next to the grants key, and grants.json carries its generation inside the MAC. Every signed write puts the file at the next generation and then keeps it; removing the file, or taking an entry out of a file VectorCraft didn't sign, raises the generation first. A file at any other generation grants nothing, so a signed copy put back after a grant was revoked no longer brings the grant back, and a write whose generation the key store couldn't keep leaves the file granting nothing. A key store that holds a key and no generation counts as generation 0. --- crates/engine/src/store.rs | 133 ++++++++++--- crates/engine/src/store/grant_keys.rs | 92 +++++++-- crates/engine/src/tests/plugins.rs | 270 ++++++++++++++++++++++++-- docs/mcp.md | 5 +- docs/plugins.md | 33 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 454 insertions(+), 81 deletions(-) diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 59ea6048d0..09c0b63204 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -21,8 +21,9 @@ //! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins //! stored there that list permissions (id, module hash, permissions); a stored plug-in whose //! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file -//! carries a MAC of its grants and its folder, made with a key the user's key store keeps -//! ([`grant_keys`]); a file without that MAC grants nothing. +//! carries a generation and a MAC of its generation, grants and folder, made with a key the user's +//! key store keeps ([`grant_keys`]); a file without that MAC, or at another generation than the +//! one the key store keeps for the folder, grants nothing. //! * **Plug-in settings and caches**: `storage/id-/` in the plug-in store, the id written as //! [`case_safe`] writes it, holds what a plug-in //! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a @@ -725,11 +726,13 @@ impl Session { /// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's /// other grants as they are; with none left, remove the file. Entries this version can't use - /// are written back as they were, except one for `id`. The file is written with the MAC of its - /// grants for this folder ([`grant_keys`]), making the key when the key store holds none. A file + /// are written back as they were, except one for `id`. The file is written at the folder's next + /// generation with the MAC of its grants for this folder ([`grant_keys`]), making the key when + /// the key store holds none, and the key store then keeps that generation ([`put_grants`]); a + /// signed file left empty is removed after raising the generation ([`take_signed_grants`]). A file /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant - /// replaces it with a file that holds that grant alone, and removing one takes out the entry for - /// `id` and leaves the rest unsigned. When the key store can't be reached ([`Trust::Unknown`], or + /// replaces it with a file that holds that grant alone, and removing one raises the generation + /// ([`raise_generation`]), then takes out the entry for `id` and leaves the rest unsigned. When the key store can't be reached ([`Trust::Unknown`], or /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry /// for `id` stays. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; @@ -824,10 +827,15 @@ impl Session { } let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); - if entries.is_empty() { - return take(dir, GRANTS_FILE); + if signed { + return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) }; } - put_grants(dir, entries, signed) + // An unsigned file loses an entry: the generation is raised first, so that no signed copy + // made before brings the entry back. + if raise_generation(dir).is_none() { + return false; + } + if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) } } /// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this @@ -1501,11 +1509,14 @@ impl GrantsFile { /// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]). #[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] enum Trust { - /// There is no file, or it carries the MAC of its grants and folder made with the user's key. + /// There is no file, or it is at the generation kept for its folder and carries the MAC of that + /// generation, its grants and its folder made with the user's key. #[default] Signed, /// It doesn't: an older version wrote it, another program wrote or changed it, it was copied - /// from another folder or machine, or the key store holds no key. It grants nothing. + /// from another folder or machine, it is an earlier copy or a write whose generation wasn't kept + /// (its generation is not the one the key store keeps), or the key store holds no key. It grants + /// nothing. Unsigned, /// The key store can't be reached, so it is not known which. It grants nothing, and is left as /// it is. @@ -1515,25 +1526,31 @@ enum Trust { /// The version of the grants file this version writes ([`SignedGrants::version`]). const GRANTS_VERSION: u64 = 1; -/// The grants file as this version writes it: the grants, and their MAC ([`grant_keys::sign`]) over -/// the list written as compact JSON. +/// The grants file as this version writes it: its generation ([`grant_keys::current_generation`]), +/// the grants, and their MAC ([`grant_keys::sign`]) over the generation and the list written as +/// compact JSON. #[derive(serde::Serialize, serde::Deserialize)] struct SignedGrants { version: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + generation: Option, grants: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] mac: Option, } /// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it -/// is) with their MAC made with the key in use, as VectorCraft writes one. +/// is) at the generation kept for `dir`, with their MAC made with the key in use, as VectorCraft +/// writes one. #[cfg(test)] pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec { let entries: Vec = serde_json::from_str(grants).unwrap_or_default(); let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}")); + let folder = plugin_store_key(dir); + let generation = grant_keys::current_generation(&folder).unwrap_or_else(|e| panic!("no generation: {e}")); let canonical = serde_json::to_vec(&entries).unwrap_or_default(); - let mac = grant_keys::sign(&key, &plugin_store_key(dir), &canonical).unwrap_or_default(); - format!(r#"{{"version":{GRANTS_VERSION},"grants":{grants},"mac":"{mac}"}}"#).into_bytes() + let mac = grant_keys::sign(&key, &folder, generation, &canonical).unwrap_or_default(); + format!(r#"{{"version":{GRANTS_VERSION},"generation":{generation},"grants":{grants},"mac":"{mac}"}}"#).into_bytes() } /// Tests: the entries of the grants file `bytes`, signed or not. @@ -1549,13 +1566,17 @@ pub(crate) fn grant_entries(bytes: &[u8]) -> Vec { } } -/// Whether `signed`, read from the grants file of the plug-in store `dir`, carries the MAC of its -/// grants and of `dir` made with the user's key. +/// Whether `signed`, read from the grants file of the plug-in store `dir`, is at the generation kept +/// for `dir` and carries the MAC of that generation, its grants and `dir` made with the user's key. +/// A file at another generation, one behind or one ahead of the kept one included, is +/// [`Trust::Unsigned`]. fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { - let (Some(tag), true) = (&signed.mac, signed.version == GRANTS_VERSION) else { return Trust::Unsigned }; + let (Some(tag), Some(generation), true) = (&signed.mac, signed.generation, signed.version == GRANTS_VERSION) else { return Trust::Unsigned }; let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned }; - match grant_keys::current_key() { - Ok(Some(key)) if grant_keys::verify(&key, &plugin_store_key(dir), &grants, tag) => Trust::Signed, + let folder = plugin_store_key(dir); + let kept = grant_keys::current_key().and_then(|key| key.map(|key| Ok((key, grant_keys::current_generation(&folder)?))).transpose()); + match kept { + Ok(Some((key, kept))) if generation == kept && grant_keys::verify(&key, &folder, generation, &grants, tag) => Trust::Signed, Ok(_) => Trust::Unsigned, Err(e) => { log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); @@ -1564,30 +1585,36 @@ fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { } } -/// Write `entries` as the grants file of the plug-in store `dir`, with their MAC for `dir` when -/// `signed`, pretty-printed, or compact when that is larger than [`MAX_GRANTS_FILE`] → whether it went -/// there; the file is not written when the key can't be had or it is too large either way. +/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when +/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the +/// key or the generation can't be had or it is too large either way. When `signed`, the file is at +/// the next generation for `dir` with its MAC, and that generation is kept after the file is written; +/// when it can't be kept, the file is at a generation the key store doesn't hold, so it grants +/// nothing, and the write reports a failure. Call it in the store's turn ([`StoreTurn`]). fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool { let path = dir.join(GRANTS_FILE); - let file = if signed { - let key = match grant_keys::signing_key() { - Ok(key) => key, + let folder = plugin_store_key(dir); + let (file, next) = if signed { + let signing = grant_keys::signing_key().and_then(|key| Ok((key, grant_keys::current_generation(&folder)?))); + let (key, generation) = match signing { + Ok(signing) => signing, Err(e) => { log::warn!("not updating the stored plug-in grants {}: {e}", path.display()); return false; } }; - let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &plugin_store_key(dir), &grants)); + let Some(next) = generation.checked_add(1) else { return false }; + let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); let Some(mac) = mac else { return false }; - serde_json::to_value(SignedGrants { version: GRANTS_VERSION, grants: entries, mac: Some(mac) }) + (serde_json::to_value(SignedGrants { version: GRANTS_VERSION, generation: Some(next), grants: entries, mac: Some(mac) }), Some(next)) } else { - serde_json::to_value(entries) + (serde_json::to_value(entries), None) }; // The file is read back only up to its cap: written compactly when pretty-printed is larger, // and not at all when that is too. let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; match file.ok().and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) { - Some(bytes) => put(dir, GRANTS_FILE, &bytes), + Some(bytes) => put(dir, GRANTS_FILE, &bytes) && next.is_none_or(|next| keep_generation(dir, &folder, next)), None => { log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); false @@ -1595,6 +1622,50 @@ fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool } } +/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) → +/// whether the key store kept it; a failure is logged. +fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { + match grant_keys::set_current_generation(folder, generation) { + Ok(()) => true, + Err(e) => { + log::warn!("the stored plug-in grants {} grant nothing: their generation wasn't kept ({e})", dir.join(GRANTS_FILE).display()); + false + } + } +} + +/// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is +/// raised first, so that no copy of the file grants anything once it is gone; when the file can't be +/// removed, the generation is put back, so the file keeps its grants, and when that can't be put back +/// either, the file grants nothing. The file holds no grant but the one being removed. Nothing is +/// removed when the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). +fn take_signed_grants(dir: &Path) -> bool { + let Some(generation) = raise_generation(dir) else { return false }; + if take(dir, GRANTS_FILE) { + return true; + } + keep_generation(dir, &plugin_store_key(dir), generation); + false +} + +/// Keep the next generation for the grants file of the plug-in store `dir`, so that no signed copy +/// of the file made before grants anything → the generation kept before; `None`, with a log record, +/// when the key store can't read or keep it. +fn raise_generation(dir: &Path) -> Option { + let folder = plugin_store_key(dir); + let raised = grant_keys::current_generation(&folder).and_then(|generation| { + let next = generation.checked_add(1).ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; + grant_keys::set_current_generation(&folder, next).map(|()| generation) + }); + match raised { + Ok(generation) => Some(generation), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + None + } + } +} + /// Why the grants file of a plug-in store gave no grants. struct GrantsError { /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs index a77cce19a7..2ae59dc825 100644 --- a/crates/engine/src/store/grant_keys.rs +++ b/crates/engine/src/store/grant_keys.rs @@ -5,11 +5,17 @@ //! an older version wrote, one another program wrote or changed, one copied from another folder or //! machine) grants nothing. //! +//! The key store also keeps a generation for each plug-in folder, raised on every signed write of +//! its grants file, and the file carries its generation inside the MAC. A file whose generation is +//! not the one kept (an earlier copy put back over the current file, or a write whose generation +//! the key store didn't keep) grants nothing either. +//! //! The process uses one key store ([`set_grant_key_store`]); the apps use the system's //! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key //! store can't be reached: a grant holds for the session only. -use std::path::Path; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; use std::sync::{Arc, LazyLock, Mutex}; /// The length of a key, in bytes, and of the MAC. @@ -66,18 +72,25 @@ pub trait GrantKeyStore: Send + Sync { self.set_key(&GrantKey::random()?)?; self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) } + /// The generation kept for the grants file of the plug-in store whose folder is `folder` + /// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept. + fn generation(&self, folder: &Path) -> Result, KeyStoreError>; + /// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>; } -/// A key store in memory: the key lasts as long as the store. For tests and embedders. +/// A key store in memory: the key and the generations last as long as the store. For tests and +/// embedders. #[derive(Default)] pub struct MemoryGrantKeys { key: Mutex>, + generations: Mutex>, } impl MemoryGrantKeys { /// A store that holds `key`. pub fn with_key(key: GrantKey) -> Self { - MemoryGrantKeys { key: Mutex::new(Some(key)) } + MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() } } } @@ -90,6 +103,15 @@ impl GrantKeyStore for MemoryGrantKeys { *self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone()); Ok(()) } + + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied()) + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation); + Ok(()) + } } /// The key store of the process ([`set_grant_key_store`]). @@ -154,49 +176,64 @@ pub(crate) fn signing_key() -> Result { } } +/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when +/// none is kept yet, an error when there is no key store or it can't be reached. +pub(crate) fn current_generation(folder: &Path) -> Result { + Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0)) +} + +/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. +pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.set_generation(folder, generation) +} + /// The start of every MAC input: what it is a MAC of, and the version of the file. #[cfg(not(target_arch = "wasm32"))] const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0"; -/// The MAC of `grants` (the grants list as compact JSON) in the plug-in store whose folder is -/// `folder` ([`super::plugin_store_key`]), made with `key`. +/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose +/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation +/// go in with their lengths first. #[cfg(not(target_arch = "wasm32"))] -fn mac_of(key: &GrantKey, folder: &Path, grants: &[u8]) -> Option> { +fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option> { use hmac::Mac; let mut mac = hmac::Hmac::::new_from_slice(&key.0).ok()?; let folder = folder.as_os_str().as_encoded_bytes(); + let generation = generation.to_be_bytes(); mac.update(DOMAIN); mac.update(&(folder.len() as u64).to_be_bytes()); mac.update(folder); + mac.update(&(generation.len() as u64).to_be_bytes()); + mac.update(&generation); mac.update(grants); Some(mac) } -/// The MAC of `grants` in `folder` with `key`, as 64 lower-case hexadecimal digits. +/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn sign(key: &GrantKey, folder: &Path, grants: &[u8]) -> Option { +pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option { use hmac::Mac; - Some(mac_of(key, folder, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) + Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) } -/// Whether `tag` is the whole MAC of `grants` in `folder` with `key` ([`sign`]), compared in constant -/// time; a shorter or longer tag is not. +/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]), +/// compared in constant time; a shorter or longer tag is not. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn verify(key: &GrantKey, folder: &Path, grants: &[u8], tag: &str) -> bool { +pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool { use hmac::Mac; let Some(tag) = from_hex(tag) else { return false }; - mac_of(key, folder, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) + mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) } /// The browser keeps no grants file. #[cfg(target_arch = "wasm32")] -pub(crate) fn sign(_: &GrantKey, _: &Path, _: &[u8]) -> Option { +pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option { None } /// The browser keeps no grants file. #[cfg(target_arch = "wasm32")] -pub(crate) fn verify(_: &GrantKey, _: &Path, _: &[u8], _: &str) -> bool { +pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool { false } @@ -242,6 +279,15 @@ impl OsGrantKeys { Err(e) => Err(store_error(e)), } } + + /// The entry of the generation of the plug-in store whose folder is `folder`: the account + /// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits. + fn generation_entry(folder: &Path) -> Result { + use sha2::Digest; + let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes()); + let account: String = digest.iter().map(|b| format!("{b:02x}")).collect(); + keyring::Entry::new(Self::SERVICE, &format!("generation-v1-{account}")).map_err(store_error) + } } #[cfg(not(target_arch = "wasm32"))] @@ -281,6 +327,22 @@ impl GrantKeyStore for OsGrantKeys { *read = Some(key.clone()); Ok(key) } + + /// Read from the key store each time, since another process on the folder may have raised it. + /// A kept value that is not 8 bytes is an error, so that nothing counts as signed with it. + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + match Self::generation_entry(folder)?.get_secret() { + Ok(secret) => <[u8; 8]>::try_from(secret.as_slice()) + .map(|bytes| Some(u64::from_be_bytes(bytes))) + .map_err(|_| KeyStoreError("the key store holds a generation of another length".into())), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(store_error(e)), + } + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + Self::generation_entry(folder)?.set_secret(&generation.to_be_bytes()).map_err(store_error) + } } /// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 13e66bda91..2061465570 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4215,6 +4215,58 @@ impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys { fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } +} + +/// A memory key store the test keeps a handle on; it fails to keep a generation while +/// `generation_writes_fail` is set. +struct SharedKeys { + keys: std::sync::Arc, + generation_writes_fail: std::sync::Arc, +} + +impl SharedKeys { + fn new(keys: &std::sync::Arc) -> Self { + SharedKeys { keys: keys.clone(), generation_writes_fail: std::sync::Arc::default() } + } +} + +impl crate::store::grant_keys::GrantKeyStore for SharedKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::key(self.keys.as_ref()) + } + + fn set_key(&self, key: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::set_key(self.keys.as_ref(), key) + } + + fn generation(&self, folder: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::generation(self.keys.as_ref(), folder) + } + + fn set_generation(&self, folder: &std::path::Path, generation: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + if self.generation_writes_fail.load(std::sync::atomic::Ordering::SeqCst) { + return Err(crate::store::grant_keys::KeyStoreError("the key store can't keep it".into())); + } + crate::store::grant_keys::GrantKeyStore::set_generation(self.keys.as_ref(), folder, generation) + } +} + +/// The generation the grants file `bytes` is at. +fn generation_of(bytes: &[u8]) -> Option { + serde_json::from_slice::(bytes).ok()?["generation"].as_u64() +} + +/// The generation `keys` keeps for the plug-in store `dir`. +fn kept_generation(keys: &crate::store::grant_keys::MemoryGrantKeys, dir: &std::path::Path) -> Option { + crate::store::grant_keys::GrantKeyStore::generation(keys, &crate::store::plugin_store_key(dir)).unwrap() } /// Whether the stored plug-in `id` loads from the plug-in store `dir` at a new start, and whether @@ -4348,16 +4400,7 @@ fn a_grants_file_without_its_key_is_replaced_by_the_next_approval() { std::fs::write(&grants, &signed).unwrap(); std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); let keys = std::sync::Arc::new(MemoryGrantKeys::default()); - struct Shared(std::sync::Arc); - impl GrantKeyStore for Shared { - fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { - self.0.key() - } - fn set_key(&self, key: &GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { - self.0.set_key(key) - } - } - let _keys = ThreadKeys::using(Shared(keys.clone())); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "no key, no grant"); assert!(keys.key().unwrap().is_none(), "reading makes no key"); assert_eq!(std::fs::read(&grants).unwrap(), signed, "the file is left as it is"); @@ -4413,22 +4456,23 @@ fn an_unreachable_key_store_keeps_approvals_in_the_session() { assert!(!grants.exists()); } -/// A MAC is made over the grants and the folder, and only the whole MAC of the same key, grants and -/// folder verifies. A key's bytes are never printed. +/// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same +/// key, generation, grants and folder verifies. A key's bytes are never printed. #[test] fn a_grants_mac_verifies_only_for_its_key_grants_and_folder() { use crate::store::grant_keys::{GrantKey, sign, verify}; let (key, other) = (GrantKey::from_bytes([1; 32]), GrantKey::from_bytes([2; 32])); let folder = std::path::Path::new("/plug-ins"); - let tag = sign(&key, folder, b"[]").unwrap(); + let tag = sign(&key, folder, 4, b"[]").unwrap(); assert_eq!(tag.len(), 64); - assert!(verify(&key, folder, b"[]", &tag)); - assert!(!verify(&other, folder, b"[]", &tag), "another key"); - assert!(!verify(&key, std::path::Path::new("/other"), b"[]", &tag), "another folder"); - assert!(!verify(&key, folder, b"[ ]", &tag), "other grants"); - assert!(!verify(&key, folder, b"[]", &tag[..62]), "a MAC cut short"); - assert!(!verify(&key, folder, b"[]", &tag.to_uppercase()), "upper case"); - assert!(!verify(&key, folder, b"[]", "")); + assert!(verify(&key, folder, 4, b"[]", &tag)); + assert!(!verify(&other, folder, 4, b"[]", &tag), "another key"); + assert!(!verify(&key, std::path::Path::new("/other"), 4, b"[]", &tag), "another folder"); + assert!(!verify(&key, folder, 3, b"[]", &tag), "another generation"); + assert!(!verify(&key, folder, 4, b"[ ]", &tag), "other grants"); + assert!(!verify(&key, folder, 4, b"[]", &tag[..62]), "a MAC cut short"); + assert!(!verify(&key, folder, 4, b"[]", &tag.to_uppercase()), "upper case"); + assert!(!verify(&key, folder, 4, b"[]", "")); assert_eq!(format!("{key:?}"), "GrantKey(..)"); } @@ -4449,6 +4493,14 @@ impl crate::store::grant_keys::GrantKeyStore for KeptFirstElsewhere { fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { Ok(()) } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Ok(None) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } } #[test] @@ -4458,7 +4510,183 @@ fn a_new_grants_key_is_the_one_the_key_store_kept() { let key = crate::store::grant_keys::signing_key().unwrap(); assert_eq!(key, GrantKey::from_bytes([7; 32]), "the key kept first signs"); let folder = std::path::Path::new("/plug-ins"); - assert!(verify(&GrantKey::from_bytes([7; 32]), folder, b"[]", &sign(&key, folder, b"[]").unwrap())); + assert!(verify(&GrantKey::from_bytes([7; 32]), folder, 1, b"[]", &sign(&key, folder, 1, b"[]").unwrap())); +} + +/// An earlier copy of the grants file put back over the current one grants nothing: after one +/// plug-in's grant is revoked while another's stays, and after the last grant is revoked and the +/// file removed. +#[test] +fn an_earlier_grants_file_put_back_grants_nothing() { + let folder = crate::tests_links::Folder::new("plugin-store-earlier-copy"); + let id = "test.engine.permissions.earlier"; + let other = "test.engine.permissions.earlierother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + let both = std::fs::read(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": other})); + let one = std::fs::read(&grants).unwrap(); + + std::fs::write(&grants, &both).unwrap(); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier copy grants nothing"); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the current file keeps its grant"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the last revoked grant doesn't come back"); + + // A grant revoked from a file edited outside VectorCraft doesn't come back with a signed copy + // made before the edit either. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + let mut edited: Value = serde_json::from_slice(&signed).unwrap(); + edited["mac"] = json!("0".repeat(64)); + std::fs::write(&grants, serde_json::to_vec(&edited).unwrap()).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked from the edited file doesn't come back"); +} + +/// Every signed write of the grants file is at the next generation, which the key store then keeps, +/// and the file stays signed; removing the last grant raises the generation too. +#[test] +fn a_signed_grants_write_raises_the_generation_and_stays_signed() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-generation"); + let id = "test.engine.permissions.generation"; + let other = "test.engine.permissions.generationother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(1), Some(1))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(2), Some(2))); + run(&mut s, "plugin.remove", json!({"id": other})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file stays signed"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + assert_eq!(kept(&folder.0), Some(4), "removing the file raises the generation"); +} + +/// Each plug-in folder has a generation of its own. +#[test] +fn two_plugin_folders_keep_their_own_generations() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let first = crate::tests_links::Folder::new("plugin-store-generation-a"); + let second = crate::tests_links::Folder::new("plugin-store-generation-b"); + let ids = ["test.engine.permissions.foldera", "test.engine.permissions.folderaother", "test.engine.permissions.folderb"]; + let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect(); + let mut a = session(); + a.attach_plugin_store(first.0.clone()); + run(&mut a, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]})); + run(&mut a, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]})); + let mut b = session(); + b.attach_plugin_store(second.0.clone()); + run(&mut b, "plugin.install", json!({"dataBase64": data[2], "grant": ["doc.read"]})); + assert_eq!((kept(&first.0), kept(&second.0)), (Some(2), Some(1))); + assert_eq!(starts_from(&first.0, ids[0], &data[0]), (true, false)); + assert_eq!(starts_from(&second.0, ids[2], &data[2]), (true, false)); + let (mut a, mut b) = (session(), session()); + a.attach_plugin_store(first.0.clone()); + b.attach_plugin_store(second.0.clone()); + run(&mut a, "plugin.remove", json!({"id": ids[0]})); + run(&mut a, "plugin.remove", json!({"id": ids[1]})); + run(&mut b, "plugin.remove", json!({"id": ids[2]})); +} + +/// A key store that holds a key and no generation for the folder, as one does the first time this +/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 1. +#[test] +fn a_key_without_a_generation_reads_generation_zero() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero"); + let id = "test.engine.permissions.generationzero"; + let other = "test.engine.permissions.generationzeroother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + assert_eq!(crate::store::grant_keys::current_generation(&crate::store::plugin_store_key(&folder.0)), Ok(0)); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(&grants, &file).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at generation 0 keeps its grant"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(1)); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": other})); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// When the key store can't keep the generation of a write, the file written is one generation ahead +/// of the kept one and grants nothing, so its plug-ins ask again; so does a file one generation +/// behind the kept one, as a write that kept its generation and then failed to write the file would +/// leave it. +#[test] +fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.generation_writes_fail.clone(); + let _keys = ThreadKeys::using(shared); + let folder = crate::tests_links::Folder::new("plugin-store-generation-unkept"); + let store = crate::store::plugin_store_key(&folder.0); + let id = "test.engine.permissions.generationunkept"; + let other = "test.engine.permissions.generationunkeptother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let written = std::fs::read(&grants).unwrap(); + + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + let kept = crate::store::grant_keys::GrantKeyStore::generation(keys.as_ref(), &store).unwrap(); + assert_eq!((generation_of(&ahead), kept), (Some(2), Some(1)), "the file is one generation ahead"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "and grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); + + std::fs::write(&grants, &written).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at the kept generation keeps its grant"); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 2).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing"); } /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next diff --git a/docs/mcp.md b/docs/mcp.md index 812e3b9446..7fc070afcc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13224,8 +13224,9 @@ flag lasts for that session only. In other sessions the approval, or a `grant` a hash, counts as approved in later sessions and in the desktop app, and covers only that module: the same bytes install again without one, also from a headless session that reads the same `grants.json`, and a module with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. A -`grants.json` that does not carry VectorCraft's MAC for its folder (see [plug-ins](plugins.md#grants-file-integrity)) -grants nothing, and its plug-ins have `needsApproval: true` again. When the system key store can't be reached, an +`grants.json` that does not carry VectorCraft's MAC for its folder, or is at another generation than the one the key +store keeps for the folder, such as an earlier copy put back (see [plug-ins](plugins.md#grants-file-integrity)), grants +nothing, and its plug-ins have `needsApproval: true` again. When the system key store can't be reached, an approval lasts for that session only and the file is left as it is. `plugin.remove` forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the diff --git a/docs/plugins.md b/docs/plugins.md index a2571e1ff3..972590bb2a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -358,11 +358,11 @@ each time it is drawn, and a paint linked to a global swatch is drawn in that sw #### Grants file integrity -`grants.json` holds the grants in a JSON object, `{"version": 1, "grants": [...], "mac": "..."}`. `mac` is an -HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the `grants` list -written as compact JSON and of the folder the file is in. The key is 32 random bytes that VectorCraft makes when it -records the first grant. VectorCraft keeps the key in the system key store, as the secret of the account -`hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, and never in a file: +`grants.json` holds the grants in a JSON object, `{"version": 1, "generation": 3, "grants": [...], "mac": "..."}`. +`mac` is an HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the +folder the file is in, the `generation` and the `grants` list written as compact JSON. The key is 32 random bytes that +VectorCraft makes when it records the first grant. VectorCraft keeps the key in the system key store, as the secret of +the account `hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, and never in a file: - On macOS the key is in the user's Keychain. - On Windows the key is a generic credential in Credential Manager. @@ -373,14 +373,25 @@ VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in macOS, and in `$XDG_RUNTIME_DIR` elsewhere. When that file can't be locked, or `$XDG_RUNTIME_DIR` is not set, no key is made, and approvals last for the session only, as when the key store can't be reached. -VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its grants and its folder grants -nothing, and each plug-in it names that lists permissions asks for approval again. This covers a file that an earlier -version wrote (a plain JSON list), a grant that another program edited or added, a file whose `mac` was removed or -changed, a file copied from another `Plug-ins` folder or another computer, and a file whose key is no longer in the key +The key store also keeps a generation for each `Plug-ins` folder, as an 8-byte secret of the account `generation-v1-` +followed by the SHA-256 of the folder's resolved path in hexadecimal, in the same service. A key store that holds no +generation for a folder counts as generation 0. Each time VectorCraft writes a signed `grants.json`, in the folder's +turn (`disabled.lock`), it writes the file at the next generation and then keeps that generation. When it removes a +signed `grants.json`, it keeps the next generation first, and puts the earlier one back when the file can't be removed; +when the key store can't put it back either, the file grants nothing. +When the key store can't keep the generation of a write, the file just written grants nothing, and the write reports a +failure. + +VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its generation, its grants and its +folder, or at another generation than the one the key store keeps for the folder, grants nothing, and each plug-in it +names that lists permissions asks for approval again. This covers a file that an earlier version wrote (a plain JSON +list), a grant that another program edited or added, a file whose `mac` was removed or changed, a file copied from +another `Plug-ins` folder or another computer, an earlier copy of the file put back after a grant was revoked or the +file was removed, a write whose generation the key store didn't keep, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists -no permissions under that id, or a folder load that forgets the grant), VectorCraft takes that entry out of such a file -and leaves the rest unsigned. +no permissions under that id, or a folder load that forgets the grant), VectorCraft keeps the next generation, then +takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no `grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c8eff38c84..686e392e49 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2660,7 +2660,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. -- **An edited grants file grants nothing (G17):** `grants.json` carries an HMAC-SHA-256 of its grants and its folder, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time. A file without that MAC (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. From 24c2d57b209c30121b13d53bafcc1b1f2c139776 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:09:39 -0800 Subject: [PATCH 011/107] Plug-ins: a grant revoked without a signed grants file stays revoked Revoking a grant while grants.json was missing, or while a file that grants nothing (no valid MAC, too large, or not a list) was in its place and had no entry for the plug-in, left the folder's generation as it was. The last signed copy, still at the kept generation, then granted the plug-in again once it was put back. Such a revoke now raises the generation whenever the key store holds a key. Every raise also goes past the generation the file in place carries, so a signed write whose generation was not kept does not start to grant when the generation catches up with it. --- crates/engine/src/store.rs | 63 +++++++++++++--- crates/engine/src/tests/plugins.rs | 114 +++++++++++++++++++++++++++++ docs/plugins.md | 7 +- 3 files changed, 171 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 09c0b63204..d13af0a6ce 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -732,7 +732,11 @@ impl Session { /// signed file left empty is removed after raising the generation ([`take_signed_grants`]). A file /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant /// replaces it with a file that holds that grant alone, and removing one raises the generation - /// ([`raise_generation`]), then takes out the entry for `id` and leaves the rest unsigned. When the key store can't be reached ([`Trust::Unknown`], or + /// ([`raise_generation`]), then takes out the entry for `id` and leaves the rest unsigned. Removing + /// a grant when there is no file, or when the file grants nothing (unsigned, too large or not a + /// list) and has no entry to take out, also raises the generation when the key store holds a key + /// ([`retire_signed_copies`]), so that a signed copy put back doesn't grant it again; when the + /// generation can't be raised, nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry /// for `id` stays. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; @@ -794,6 +798,11 @@ impl Session { Ok(file) => file, Err(e) => { log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); + // A file that is too large or doesn't hold a list grants nothing and is left as it + // is, but a signed copy made before it must not grant `id` again once it is put back. + if grant.is_none() && !e.unread { + retire_signed_copies(dir, None); + } return false; } }; @@ -816,6 +825,7 @@ impl Session { (Trust::Unsigned | Trust::Signed, _) => {} } let signed = file.trust == Trust::Signed || grant.is_some(); + let removing = grant.is_none(); let others = file.other.len(); file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id)); let changed = match grant { @@ -823,7 +833,12 @@ impl Session { None => file.grants.remove(id).is_some(), } || file.other.len() != others; if !changed { - return true; + // Without a file, or with one that grants nothing, the last signed file may still be + // around as a copy at the kept generation: a removal raises the generation so that the + // copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id` + // is the latest, so every copy that does is at an earlier generation already. The new + // generation is past the one the file carries, so the file left in place grants nothing. + return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir, file.generation); } let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); @@ -831,8 +846,8 @@ impl Session { return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) }; } // An unsigned file loses an entry: the generation is raised first, so that no signed copy - // made before brings the entry back. - if raise_generation(dir).is_none() { + // made before brings the entry back, nor the file itself when it can't be rewritten. + if raise_generation(dir, file.generation).is_none() { return false; } if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) } @@ -1497,6 +1512,11 @@ struct GrantsFile { other: Vec, /// Whether VectorCraft wrote the grants for this folder. trust: Trust, + /// Whether there is a grants file: `false` when there is none, and the file is then empty and + /// [`Trust::Signed`]. + present: bool, + /// The generation the file carries, as this version writes it ([`SignedGrants::generation`]). + generation: Option, } impl GrantsFile { @@ -1640,7 +1660,7 @@ fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { /// either, the file grants nothing. The file holds no grant but the one being removed. Nothing is /// removed when the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). fn take_signed_grants(dir: &Path) -> bool { - let Some(generation) = raise_generation(dir) else { return false }; + let Some(generation) = raise_generation(dir, None) else { return false }; if take(dir, GRANTS_FILE) { return true; } @@ -1650,11 +1670,14 @@ fn take_signed_grants(dir: &Path) -> bool { /// Keep the next generation for the grants file of the plug-in store `dir`, so that no signed copy /// of the file made before grants anything → the generation kept before; `None`, with a log record, -/// when the key store can't read or keep it. -fn raise_generation(dir: &Path) -> Option { +/// when the key store can't read or keep it. `carried` is the generation the file in `dir` carries +/// when it grants nothing ([`GrantsFile::generation`]): the new generation is past it too, so that a +/// signed write whose generation wasn't kept doesn't start to grant when the file stays. +fn raise_generation(dir: &Path, carried: Option) -> Option { let folder = plugin_store_key(dir); let raised = grant_keys::current_generation(&folder).and_then(|generation| { - let next = generation.checked_add(1).ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; + let next = generation.max(carried.unwrap_or(0)).checked_add(1); + let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; grant_keys::set_current_generation(&folder, next).map(|()| generation) }); match raised { @@ -1666,6 +1689,22 @@ fn raise_generation(dir: &Path) -> Option { } } +/// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything → +/// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key, +/// and left as it is when it holds none, since no file is then signed. `carried` is as for +/// [`raise_generation`]. `false`, with a log record, when the key store can't read or keep it. Call +/// it in the store's turn ([`StoreTurn`]). +fn retire_signed_copies(dir: &Path, carried: Option) -> bool { + match grant_keys::current_key() { + Ok(None) => true, + Ok(Some(_)) => raise_generation(dir, carried).is_some(), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + false + } + } +} + /// Why the grants file of a plug-in store gave no grants. struct GrantsError { /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is @@ -1691,12 +1730,12 @@ fn read_grants(dir: &Path) -> Result { return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } let not_a_list = |why: String| GrantsError { unread: false, why }; - let (entries, trust) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { - serde_json::Value::Array(entries) => (entries, Trust::Unsigned), + let (entries, trust, generation) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { + serde_json::Value::Array(entries) => (entries, Trust::Unsigned, None), serde_json::Value::Object(_) => { let signed = serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))?; let trust = trust_of(dir, &signed); - (signed.grants, trust) + (signed.grants, trust, signed.generation) } _ => return Err(not_a_list("not a list of grants".into())), }; @@ -1706,7 +1745,7 @@ fn read_grants(dir: &Path) -> Result { path.display() ); } - let mut file = GrantsFile { trust, ..GrantsFile::default() }; + let mut file = GrantsFile { trust, present: true, generation, ..GrantsFile::default() }; let mut first_error = None; for entry in entries { let why = match serde_json::from_value::(entry.clone()) { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 2061465570..d6c0218072 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4561,6 +4561,64 @@ fn an_earlier_grants_file_put_back_grants_nothing() { assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked from the edited file doesn't come back"); } +/// A grant revoked while the grants file is gone, or while another file that grants nothing (one +/// without a MAC, or one that doesn't hold a list) is in its place, doesn't come back with the last +/// signed file put back: the revoke raises the generation. A revoke that a signed file without an +/// entry for the plug-in already covers, or one while the key store holds no key, leaves the +/// generation as it is. +#[test] +fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-without-file"); + let id = "test.engine.permissions.revokedgone"; + let other = "test.engine.permissions.revokedgoneother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(other, None), "nothing to revoke in an empty folder"); + assert_eq!(kept(&folder.0), None, "without a key nothing is signed, so no generation is kept"); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + assert_eq!(kept(&folder.0), Some(1)); + assert!(s.store_grant(other, None)); + assert_eq!(kept(&folder.0), Some(1), "the signed file names no grant for it, so nothing is raised"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + + // The file is gone when the grant is revoked. + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept(&folder.0), Some(2)); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked while the file was gone doesn't come back"); + + // A file without a MAC that names no grant for it is in place. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, b"[]").unwrap(); + assert!(s.store_grant(id, None)); + assert_eq!(std::fs::read(&grants).unwrap(), b"[]", "the unsigned file is left as it is"); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over an unsigned file doesn't come back"); + + // A file that doesn't hold a list is in place: the revoke isn't recorded, and still raises the + // generation. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, br#""not a list""#).unwrap(); + assert!(!s.store_grant(id, None)); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over a file without a list doesn't come back"); +} + /// Every signed write of the grants file is at the next generation, which the key store then keeps, /// and the file stays signed; removing the last grant raises the generation too. #[test] @@ -4652,6 +4710,29 @@ fn a_key_without_a_generation_reads_generation_zero() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A grant revoked while the file signed at generation 0 is gone doesn't come back with that file +/// put back: with a key kept, the revoke raises the generation from 0. +#[test] +fn a_grant_revoked_while_a_generation_zero_file_is_gone_doesnt_come_back() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([6; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero-revoke"); + let id = "test.engine.permissions.generationzerorevoke"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept_generation(&keys, &folder.0), Some(1)); + std::fs::write(&grants, &file).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file at generation 0 grants nothing"); +} + /// When the key store can't keep the generation of a write, the file written is one generation ahead /// of the kept one and grants nothing, so its plug-ins ask again; so does a file one generation /// behind the kept one, as a write that kept its generation and then failed to write the file would @@ -4689,6 +4770,39 @@ fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing"); } +/// A revoke over a signed file whose generation wasn't kept raises the generation past the file's, +/// so the file left in place still grants nothing. +#[test] +fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.generation_writes_fail.clone(); + let _keys = ThreadKeys::using(shared); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-ahead"); + let id = "test.engine.permissions.revokeahead"; + let other = "test.engine.permissions.revokeaheadother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(2), Some(1))); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant("test.engine.permissions.revokeaheadnone", None)); + assert_eq!(std::fs::read(&grants).unwrap(), ahead, "the file is left as it is"); + assert_eq!(kept(&folder.0), Some(3), "the generation is past the file's"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file still grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); +} + /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next /// start without asking, with its budget. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 972590bb2a..1af038597e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -391,7 +391,12 @@ file was removed, a write whose generation the key store didn't keep, and a file store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists no permissions under that id, or a folder load that forgets the grant), VectorCraft keeps the next generation, then -takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. +takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. It +also keeps the next generation when a grant is forgotten while there is no `grants.json`, or while the file in its place +grants nothing (no valid MAC, too large, or neither a grants object nor a JSON list) and has no entry to take out, +whenever the key store holds a key. Each time it keeps the next generation for a file that grants nothing and +stays in place, the new generation is also past the one that file carries. When the key store can't keep that +generation, VectorCraft logs a warning. When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no `grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored From d73ffbc27112ac1defcd4cf3176813250fbb27e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:33:41 -0800 Subject: [PATCH 012/107] Plug-ins: grant generations come from the key store only A revoke raised the kept generation past the one the grants file carried. The file can be edited, so a file carrying the largest generation made every revoke fail, and one just below it left the kept generation at the limit, so later grants could not be kept. The generation is now read from the key store only. A raise went to the generation after the kept one, which is the generation a signed write whose keep failed had used, so a copy of that write put back after a revoke granted again. A raise now goes two past the kept generation, and each signed write raises first and is written at the generation after the raised one. Every signed write is at a generation no file was signed at before. When the file can't be written, the earlier generation is put back. When the generation can't be raised without passing the largest 64-bit value, the change is refused with a log record. --- crates/engine/src/store.rs | 148 ++++++++++++---------- crates/engine/src/tests/plugins.rs | 189 ++++++++++++++++++++++++----- docs/plugins.md | 22 ++-- 3 files changed, 258 insertions(+), 101 deletions(-) diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index d13af0a6ce..c40afe37b5 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -726,17 +726,18 @@ impl Session { /// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's /// other grants as they are; with none left, remove the file. Entries this version can't use - /// are written back as they were, except one for `id`. The file is written at the folder's next - /// generation with the MAC of its grants for this folder ([`grant_keys`]), making the key when - /// the key store holds none, and the key store then keeps that generation ([`put_grants`]); a - /// signed file left empty is removed after raising the generation ([`take_signed_grants`]). A file - /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant - /// replaces it with a file that holds that grant alone, and removing one raises the generation - /// ([`raise_generation`]), then takes out the entry for `id` and leaves the rest unsigned. Removing - /// a grant when there is no file, or when the file grants nothing (unsigned, too large or not a - /// list) and has no entry to take out, also raises the generation when the key store holds a key - /// ([`retire_signed_copies`]), so that a signed copy put back doesn't grant it again; when the - /// generation can't be raised, nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or + /// are written back as they were, except one for `id`. The generation is raised, and the file is + /// written at the generation after the raised one with the MAC of its grants for this folder + /// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that + /// generation ([`put_grants`]). A signed file left empty is removed after raising the generation + /// ([`take_signed_grants`]). A file VectorCraft didn't write for this folder ([`Trust::Unsigned`]) + /// grants nothing: a grant replaces it with a file that holds that grant alone, and removing one + /// raises the generation ([`raise_generation`]), then takes out the entry for `id` and leaves the + /// rest unsigned. Removing a grant when there is no file, or when the file grants nothing + /// (unsigned, too large or not a list) and has no entry to take out, also raises the generation + /// when the key store holds a key ([`retire_signed_copies`]), so that a signed copy put back + /// doesn't grant it again. The generation is never read from the file; when it can't be raised, + /// nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry /// for `id` stays. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; @@ -801,7 +802,7 @@ impl Session { // A file that is too large or doesn't hold a list grants nothing and is left as it // is, but a signed copy made before it must not grant `id` again once it is put back. if grant.is_none() && !e.unread { - retire_signed_copies(dir, None); + retire_signed_copies(dir); } return false; } @@ -837,8 +838,9 @@ impl Session { // around as a copy at the kept generation: a removal raises the generation so that the // copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id` // is the latest, so every copy that does is at an earlier generation already. The new - // generation is past the one the file carries, so the file left in place grants nothing. - return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir, file.generation); + // generation is past every one a file was signed at, so the file left in place grants + // nothing either. + return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir); } let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); @@ -847,7 +849,7 @@ impl Session { } // An unsigned file loses an entry: the generation is raised first, so that no signed copy // made before brings the entry back, nor the file itself when it can't be rewritten. - if raise_generation(dir, file.generation).is_none() { + if raise_generation(dir).is_none() { return false; } if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) } @@ -1515,8 +1517,6 @@ struct GrantsFile { /// Whether there is a grants file: `false` when there is none, and the file is then empty and /// [`Trust::Signed`]. present: bool, - /// The generation the file carries, as this version writes it ([`SignedGrants::generation`]). - generation: Option, } impl GrantsFile { @@ -1607,39 +1607,59 @@ fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { /// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when /// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the -/// key or the generation can't be had or it is too large either way. When `signed`, the file is at -/// the next generation for `dir` with its MAC, and that generation is kept after the file is written; -/// when it can't be kept, the file is at a generation the key store doesn't hold, so it grants -/// nothing, and the write reports a failure. Call it in the store's turn ([`StoreTurn`]). +/// key or the generation can't be had or it is too large either way. When `signed`, the generation +/// is raised first ([`raise_generation`]), the file is written at the generation after the raised one +/// with its MAC, and the key store keeps that generation once the file is written. Every signed write +/// is then at a generation no file was signed at before, a write whose generation wasn't kept +/// included, since that one is at most one past the generation the key store kept. When the file +/// isn't written, the generation kept before is put back. When the file's generation can't be kept, +/// the file is at a generation the key store doesn't hold, so it grants nothing, and the write +/// reports a failure. Call it in the store's turn ([`StoreTurn`]). fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool { let path = dir.join(GRANTS_FILE); let folder = plugin_store_key(dir); - let (file, next) = if signed { - let signing = grant_keys::signing_key().and_then(|key| Ok((key, grant_keys::current_generation(&folder)?))); - let (key, generation) = match signing { - Ok(signing) => signing, - Err(e) => { - log::warn!("not updating the stored plug-in grants {}: {e}", path.display()); - return false; + if !signed { + return match grants_bytes(serde_json::to_value(entries).ok()) { + Some(bytes) => put(dir, GRANTS_FILE, &bytes), + None => { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + false } }; - let Some(next) = generation.checked_add(1) else { return false }; - let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); - let Some(mac) = mac else { return false }; - (serde_json::to_value(SignedGrants { version: GRANTS_VERSION, generation: Some(next), grants: entries, mac: Some(mac) }), Some(next)) - } else { - (serde_json::to_value(entries), None) - }; - // The file is read back only up to its cap: written compactly when pretty-printed is larger, - // and not at all when that is too. - let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; - match file.ok().and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) { - Some(bytes) => put(dir, GRANTS_FILE, &bytes) && next.is_none_or(|next| keep_generation(dir, &folder, next)), - None => { - log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); - false - } } + let key = match grant_keys::signing_key() { + Ok(key) => key, + Err(e) => { + log::warn!("not updating the stored plug-in grants {}: {e}", path.display()); + return false; + } + }; + let Some((before, raised)) = raise_generation(dir) else { return false }; + let Some(next) = raised.checked_add(1) else { + log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display()); + keep_generation(dir, &folder, before); + return false; + }; + let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); + let file = mac + .and_then(|mac| serde_json::to_value(SignedGrants { version: GRANTS_VERSION, generation: Some(next), grants: entries, mac: Some(mac) }).ok()); + let Some(bytes) = grants_bytes(file) else { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + keep_generation(dir, &folder, before); + return false; + }; + if !put(dir, GRANTS_FILE, &bytes) { + keep_generation(dir, &folder, before); + return false; + } + keep_generation(dir, &folder, next) +} + +/// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than +/// [`MAX_GRANTS_FILE`]; `None` when that is too, since the file is read back only up to its cap. +fn grants_bytes(file: Option) -> Option> { + let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; + file.and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) } /// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) → @@ -1660,28 +1680,29 @@ fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { /// either, the file grants nothing. The file holds no grant but the one being removed. Nothing is /// removed when the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). fn take_signed_grants(dir: &Path) -> bool { - let Some(generation) = raise_generation(dir, None) else { return false }; + let Some((before, _)) = raise_generation(dir) else { return false }; if take(dir, GRANTS_FILE) { return true; } - keep_generation(dir, &plugin_store_key(dir), generation); + keep_generation(dir, &plugin_store_key(dir), before); false } -/// Keep the next generation for the grants file of the plug-in store `dir`, so that no signed copy -/// of the file made before grants anything → the generation kept before; `None`, with a log record, -/// when the key store can't read or keep it. `carried` is the generation the file in `dir` carries -/// when it grants nothing ([`GrantsFile::generation`]): the new generation is past it too, so that a -/// signed write whose generation wasn't kept doesn't start to grant when the file stays. -fn raise_generation(dir: &Path, carried: Option) -> Option { +/// Keep a generation two past the one kept for the grants file of the plug-in store `dir`, so that +/// no signed copy of the file made before grants anything → the generation kept before and the one +/// kept now; `None`, with a log record, when the key store can't read or keep it or the generation +/// is too large to raise. A signed write whose generation wasn't kept is at the generation after the +/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the key +/// store alone, never from a file, which anyone can edit. +fn raise_generation(dir: &Path) -> Option<(u64, u64)> { let folder = plugin_store_key(dir); let raised = grant_keys::current_generation(&folder).and_then(|generation| { - let next = generation.max(carried.unwrap_or(0)).checked_add(1); + let next = generation.checked_add(2); let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; - grant_keys::set_current_generation(&folder, next).map(|()| generation) + grant_keys::set_current_generation(&folder, next).map(|()| (generation, next)) }); match raised { - Ok(generation) => Some(generation), + Ok(generations) => Some(generations), Err(e) => { log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); None @@ -1691,13 +1712,12 @@ fn raise_generation(dir: &Path, carried: Option) -> Option { /// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything → /// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key, -/// and left as it is when it holds none, since no file is then signed. `carried` is as for -/// [`raise_generation`]. `false`, with a log record, when the key store can't read or keep it. Call -/// it in the store's turn ([`StoreTurn`]). -fn retire_signed_copies(dir: &Path, carried: Option) -> bool { +/// and left as it is when it holds none, since no file is then signed. `false`, with a log record, +/// when the key store can't read or keep it. Call it in the store's turn ([`StoreTurn`]). +fn retire_signed_copies(dir: &Path) -> bool { match grant_keys::current_key() { Ok(None) => true, - Ok(Some(_)) => raise_generation(dir, carried).is_some(), + Ok(Some(_)) => raise_generation(dir).is_some(), Err(e) => { log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); false @@ -1730,12 +1750,12 @@ fn read_grants(dir: &Path) -> Result { return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } let not_a_list = |why: String| GrantsError { unread: false, why }; - let (entries, trust, generation) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { - serde_json::Value::Array(entries) => (entries, Trust::Unsigned, None), + let (entries, trust) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { + serde_json::Value::Array(entries) => (entries, Trust::Unsigned), serde_json::Value::Object(_) => { let signed = serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))?; let trust = trust_of(dir, &signed); - (signed.grants, trust, signed.generation) + (signed.grants, trust) } _ => return Err(not_a_list("not a list of grants".into())), }; @@ -1745,7 +1765,7 @@ fn read_grants(dir: &Path) -> Result { path.display() ); } - let mut file = GrantsFile { trust, present: true, generation, ..GrantsFile::default() }; + let mut file = GrantsFile { trust, present: true, ..GrantsFile::default() }; let mut first_error = None; for entry in entries { let why = match serde_json::from_value::(entry.clone()) { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index d6c0218072..ea7a1a48f2 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4225,16 +4225,16 @@ impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys { } } -/// A memory key store the test keeps a handle on; it fails to keep a generation while -/// `generation_writes_fail` is set. +/// A memory key store the test keeps a handle on. While `file_generations_fail` is set, it fails to +/// keep the generation that the grants file in the folder is at, and keeps every other one. struct SharedKeys { keys: std::sync::Arc, - generation_writes_fail: std::sync::Arc, + file_generations_fail: std::sync::Arc, } impl SharedKeys { fn new(keys: &std::sync::Arc) -> Self { - SharedKeys { keys: keys.clone(), generation_writes_fail: std::sync::Arc::default() } + SharedKeys { keys: keys.clone(), file_generations_fail: std::sync::Arc::default() } } } @@ -4252,7 +4252,9 @@ impl crate::store::grant_keys::GrantKeyStore for SharedKeys { } fn set_generation(&self, folder: &std::path::Path, generation: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { - if self.generation_writes_fail.load(std::sync::atomic::Ordering::SeqCst) { + if self.file_generations_fail.load(std::sync::atomic::Ordering::SeqCst) + && std::fs::read(folder.join("grants.json")).ok().and_then(|bytes| generation_of(&bytes)) == Some(generation) + { return Err(crate::store::grant_keys::KeyStoreError("the key store can't keep it".into())); } crate::store::grant_keys::GrantKeyStore::set_generation(self.keys.as_ref(), folder, generation) @@ -4582,9 +4584,9 @@ fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { assert_eq!(kept(&folder.0), None, "without a key nothing is signed, so no generation is kept"); run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); let signed = std::fs::read(&grants).unwrap(); - assert_eq!(kept(&folder.0), Some(1)); + assert_eq!(kept(&folder.0), Some(3)); assert!(s.store_grant(other, None)); - assert_eq!(kept(&folder.0), Some(1), "the signed file names no grant for it, so nothing is raised"); + assert_eq!(kept(&folder.0), Some(3), "the signed file names no grant for it, so nothing is raised"); assert_eq!(starts_from(&folder.0, id, &data), (true, false)); // The file is gone when the grant is revoked. @@ -4592,7 +4594,7 @@ fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { let mut s = session(); s.attach_plugin_store(folder.0.clone()); assert!(s.store_grant(id, None)); - assert_eq!(kept(&folder.0), Some(2)); + assert_eq!(kept(&folder.0), Some(5)); std::fs::write(&grants, &signed).unwrap(); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked while the file was gone doesn't come back"); @@ -4619,8 +4621,9 @@ fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over a file without a list doesn't come back"); } -/// Every signed write of the grants file is at the next generation, which the key store then keeps, -/// and the file stays signed; removing the last grant raises the generation too. +/// Every signed write of the grants file raises the generation by two and is at the generation after +/// that, which the key store then keeps, and the file stays signed; removing the last grant raises +/// the generation too. #[test] fn a_signed_grants_write_raises_the_generation_and_stays_signed() { let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); @@ -4635,20 +4638,20 @@ fn a_signed_grants_write_raises_the_generation_and_stays_signed() { let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); - assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(1), Some(1))); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3))); assert_eq!(starts_from(&folder.0, id, &data), (true, false)); let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); - assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(2), Some(2))); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(6), Some(6))); run(&mut s, "plugin.remove", json!({"id": other})); - assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3))); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(9), Some(9))); assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file stays signed"); let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.remove", json!({"id": id})); assert!(!grants.exists()); - assert_eq!(kept(&folder.0), Some(4), "removing the file raises the generation"); + assert_eq!(kept(&folder.0), Some(11), "removing the file raises the generation"); } /// Each plug-in folder has a generation of its own. @@ -4668,7 +4671,7 @@ fn two_plugin_folders_keep_their_own_generations() { let mut b = session(); b.attach_plugin_store(second.0.clone()); run(&mut b, "plugin.install", json!({"dataBase64": data[2], "grant": ["doc.read"]})); - assert_eq!((kept(&first.0), kept(&second.0)), (Some(2), Some(1))); + assert_eq!((kept(&first.0), kept(&second.0)), (Some(6), Some(3))); assert_eq!(starts_from(&first.0, ids[0], &data[0]), (true, false)); assert_eq!(starts_from(&second.0, ids[2], &data[2]), (true, false)); let (mut a, mut b) = (session(), session()); @@ -4680,7 +4683,7 @@ fn two_plugin_folders_keep_their_own_generations() { } /// A key store that holds a key and no generation for the folder, as one does the first time this -/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 1. +/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 3. #[test] fn a_key_without_a_generation_reads_generation_zero() { use vectorcraft_plugins::permissions::sha256_hex; @@ -4702,7 +4705,7 @@ fn a_key_without_a_generation_reads_generation_zero() { s.attach_plugin_store(folder.0.clone()); let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); - assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(1)); + assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(3)); assert_eq!(starts_from(&folder.0, id, &data), (true, false)); let mut s = session(); s.attach_plugin_store(folder.0.clone()); @@ -4728,20 +4731,19 @@ fn a_grant_revoked_while_a_generation_zero_file_is_gone_doesnt_come_back() { let mut s = session(); s.attach_plugin_store(folder.0.clone()); assert!(s.store_grant(id, None)); - assert_eq!(kept_generation(&keys, &folder.0), Some(1)); + assert_eq!(kept_generation(&keys, &folder.0), Some(2)); std::fs::write(&grants, &file).unwrap(); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file at generation 0 grants nothing"); } /// When the key store can't keep the generation of a write, the file written is one generation ahead -/// of the kept one and grants nothing, so its plug-ins ask again; so does a file one generation -/// behind the kept one, as a write that kept its generation and then failed to write the file would -/// leave it. +/// of the kept one and grants nothing, so its plug-ins ask again; so does the earlier file, since +/// the generation was raised past it before the write, and a file behind the kept generation. #[test] fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); let shared = SharedKeys::new(&keys); - let fail = shared.generation_writes_fail.clone(); + let fail = shared.file_generations_fail.clone(); let _keys = ThreadKeys::using(shared); let folder = crate::tests_links::Folder::new("plugin-store-generation-unkept"); let store = crate::store::plugin_store_key(&folder.0); @@ -4760,13 +4762,15 @@ fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { fail.store(false, std::sync::atomic::Ordering::SeqCst); let ahead = std::fs::read(&grants).unwrap(); let kept = crate::store::grant_keys::GrantKeyStore::generation(keys.as_ref(), &store).unwrap(); - assert_eq!((generation_of(&ahead), kept), (Some(2), Some(1)), "the file is one generation ahead"); + assert_eq!((generation_of(&ahead), kept), (Some(6), Some(5)), "the file is one generation ahead"); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "and grants nothing"); assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); std::fs::write(&grants, &written).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier file grants nothing"); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 3).unwrap(); assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at the kept generation keeps its grant"); - crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 2).unwrap(); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 4).unwrap(); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing"); } @@ -4776,7 +4780,7 @@ fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() { let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); let shared = SharedKeys::new(&keys); - let fail = shared.generation_writes_fail.clone(); + let fail = shared.file_generations_fail.clone(); let _keys = ThreadKeys::using(shared); let kept = |dir: &std::path::Path| kept_generation(&keys, dir); let folder = crate::tests_links::Folder::new("plugin-store-revoke-ahead"); @@ -4792,17 +4796,148 @@ fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() { _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); fail.store(false, std::sync::atomic::Ordering::SeqCst); let ahead = std::fs::read(&grants).unwrap(); - assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(2), Some(1))); + assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(6), Some(5))); let mut s = session(); s.attach_plugin_store(folder.0.clone()); assert!(s.store_grant("test.engine.permissions.revokeaheadnone", None)); assert_eq!(std::fs::read(&grants).unwrap(), ahead, "the file is left as it is"); - assert_eq!(kept(&folder.0), Some(3), "the generation is past the file's"); + assert_eq!(kept(&folder.0), Some(7), "the generation is past the file's"); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file still grants nothing"); assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); } +/// A signed write raises the generation before it writes the file, so a signed write whose generation +/// wasn't kept also leaves the earlier file granting nothing; a revoke over that earlier file put back +/// is then not at the generation of the unkept write, and a copy of that write put back after the +/// revoke grants nothing. +#[test] +fn a_revoke_after_a_write_whose_generation_wasnt_kept_keeps_that_write_granting_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-after-unkept"); + let ids = ["test.engine.permissions.afterunkept", "test.engine.permissions.afterunkeptother", "test.engine.permissions.afterunkeptthird"]; + let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect(); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]})); + let earlier = std::fs::read(&grants).unwrap(); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": data[2], "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let unkept = std::fs::read(&grants).unwrap(); + + std::fs::write(&grants, &earlier).unwrap(); + assert_eq!(starts_from(&folder.0, ids[0], &data[0]), (false, true), "the earlier file grants nothing"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(ids[1], None)); + std::fs::write(&grants, &unkept).unwrap(); + assert_eq!(starts_from(&folder.0, ids[1], &data[1]), (false, true), "the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, ids[2], &data[2]), (false, true), "the unkept write grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + for id in ids { + _ = s.execute("plugin.remove", &json!({"id": id})); + } +} + +/// A grants file edited to carry the largest generations doesn't stop a revoke and doesn't move the +/// generation the key store keeps near the limit, so later grants are still kept: the generation +/// comes from the key store alone. +#[test] +fn a_grants_file_at_the_largest_generations_doesnt_stop_a_revoke() { + use vectorcraft_plugins::permissions::sha256_hex; + for carried in [u64::MAX, u64::MAX - 1] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-largest-generation-{}", u64::MAX - carried)); + let id = "test.engine.permissions.largestgeneration"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let edited = |entries: Value| json!({"version": 1, "generation": carried, "grants": entries, "mac": "0".repeat(64)}).to_string(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!(kept(&folder.0), Some(3)); + + // The edited file names the grant, which the revoke takes out. + std::fs::write(&grants, edited(json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]))).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists(), "generation {carried}: the entry is taken out"); + assert_eq!(kept(&folder.0), Some(5), "generation {carried}: the kept generation is raised from its own value"); + + // The edited file names no grant for it. + std::fs::write(&grants, edited(json!([]))).unwrap(); + assert!(s.store_grant(id, None), "generation {carried}: the revoke is recorded"); + assert_eq!(kept(&folder.0), Some(7), "generation {carried}: the kept generation is raised from its own value"); + + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(10), Some(10)), "generation {carried}"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "generation {carried}: a later grant is kept"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +/// A signed write whose generation wasn't kept leaves a file one generation past the kept one. A +/// revoke raises the generation past that file too, so a copy of it put back grants nothing: a revoke +/// from a file without a MAC, one while the file is gone, one over a file that doesn't hold a list, +/// and one that removes the last grant of a signed file. +#[test] +fn a_write_whose_generation_wasnt_kept_grants_nothing_after_a_revoke() { + use vectorcraft_plugins::permissions::sha256_hex; + for path in ["unsigned", "gone", "not-a-list", "signed"] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-unkept-copy-{path}")); + let id = "test.engine.permissions.unkeptcopy"; + let other = "test.engine.permissions.unkeptcopyother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let unkept = std::fs::read(&grants).unwrap(); + let before = kept(&folder.0).unwrap(); + assert_eq!(generation_of(&unkept), Some(before + 1), "{path}: the file is one generation past the kept one"); + + let other_grant = json!([{"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}]).to_string(); + match path { + "unsigned" => std::fs::write(&grants, &other_grant).unwrap(), + "gone" => std::fs::remove_file(&grants).unwrap(), + "not-a-list" => std::fs::write(&grants, br#""not a list""#).unwrap(), + _ => std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &other_grant)).unwrap(), + } + assert_eq!(s.store_grant(other, None), path != "not-a-list", "{path}"); + std::fs::write(&grants, &unkept).unwrap(); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "{path}: the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{path}: the copy grants nothing"); + assert_eq!(kept(&folder.0), Some(before + 2), "{path}: the generation is past the file whose generation wasn't kept"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); + _ = s.execute("plugin.remove", &json!({"id": other})); + } +} + /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next /// start without asking, with its budget. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 1af038597e..d7f6656357 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -375,12 +375,15 @@ is made, and approvals last for the session only, as when the key store can't be The key store also keeps a generation for each `Plug-ins` folder, as an 8-byte secret of the account `generation-v1-` followed by the SHA-256 of the folder's resolved path in hexadecimal, in the same service. A key store that holds no -generation for a folder counts as generation 0. Each time VectorCraft writes a signed `grants.json`, in the folder's -turn (`disabled.lock`), it writes the file at the next generation and then keeps that generation. When it removes a -signed `grants.json`, it keeps the next generation first, and puts the earlier one back when the file can't be removed; +generation for a folder counts as generation 0. VectorCraft reads the generation from the key store only, never from +`grants.json`. Each time VectorCraft writes a signed `grants.json`, in the folder's turn (`disabled.lock`), it first +raises the kept generation by two, then writes the file at the generation after the raised one, and then keeps that +generation; when the file can't be written, it puts the earlier generation back. When it removes a signed +`grants.json`, it raises the generation by two first, and puts the earlier one back when the file can't be removed; when the key store can't put it back either, the file grants nothing. When the key store can't keep the generation of a write, the file just written grants nothing, and the write reports a -failure. +failure. That file is one generation past the kept one, so the next raise by two moves past it. When raising the +generation by two would pass the largest 64-bit value, VectorCraft logs a warning and changes nothing. VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its generation, its grants and its folder, or at another generation than the one the key store keeps for the folder, grants nothing, and each plug-in it @@ -390,13 +393,12 @@ another `Plug-ins` folder or another computer, an earlier copy of the file put b file was removed, a write whose generation the key store didn't keep, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists -no permissions under that id, or a folder load that forgets the grant), VectorCraft keeps the next generation, then +no permissions under that id, or a folder load that forgets the grant), VectorCraft raises the generation by two, then takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. It -also keeps the next generation when a grant is forgotten while there is no `grants.json`, or while the file in its place -grants nothing (no valid MAC, too large, or neither a grants object nor a JSON list) and has no entry to take out, -whenever the key store holds a key. Each time it keeps the next generation for a file that grants nothing and -stays in place, the new generation is also past the one that file carries. When the key store can't keep that -generation, VectorCraft logs a warning. +also raises the generation by two when a grant is forgotten while there is no `grants.json`, or while the file in its +place grants nothing (no valid MAC, too large, or neither a grants object nor a JSON list) and has no entry to take out, +whenever the key store holds a key. A `generation` written into such a file has no effect on the raise. When the key +store can't raise the generation, VectorCraft logs a warning. When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no `grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored From d60e2998d7c2ac2720724d48847ec34fa59d4a00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:08:20 -0800 Subject: [PATCH 013/107] Plug-ins: a failed grants write leaves the generation raised The key store's generation for a plug-in folder now only goes up. When writing or removing a signed grants.json fails after the raise, the generation stays raised: the file left in place grants nothing and its plug-ins ask for approval again. Before, the earlier generation was put back, so a later raise could reach a generation a copy of the file was already signed at, and that copy granted again. - Keeping a lower generation than the kept one is an error. - A signed file larger than 1 MiB is found before the raise, so the file in place keeps its grants when nothing can be written. - A kept generation within two of the largest 64-bit value is not raised, so a signed write never fails after the raise for lack of a next generation. --- crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/src/store.rs | 90 ++++++++------- crates/engine/src/store/grant_keys.rs | 16 ++- crates/engine/src/tests/plugins.rs | 157 +++++++++++++++++++++++++- docs/plugins.md | 18 +-- docs/target-app-parity.md | 2 +- 6 files changed, 225 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 338ecaf958..5e2e669563 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1218,7 +1218,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); - // Installed again, it asks again. A grant that can't be removed still approves the module, and + // Installed again, it asks again. A grant that can't be removed may still approve the module, and // so may a grants file that can't be opened or read. One that is too large or doesn't hold a // list approves nothing and doesn't stop the removal. let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index c40afe37b5..73215c4999 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -211,6 +211,11 @@ fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool { if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) { return true; } + #[cfg(test)] + if file == GRANTS_FILE && GRANTS_WRITE_FAILS.get() { + log::warn!("can't save {}: the test fails it", path.display()); + return false; + } let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes)); if let Err(e) = &written { log::warn!("can't save {}: {e}", path.display()); @@ -285,6 +290,9 @@ thread_local! { /// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when /// another program holds it open. pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: writing [`GRANTS_FILE`] fails on this thread and leaves the file as it was, as on a + /// full volume. + pub(crate) static GRANTS_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then /// reports a failure, as when the last flush of a copy fails. pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -730,8 +738,9 @@ impl Session { /// written at the generation after the raised one with the MAC of its grants for this folder /// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that /// generation ([`put_grants`]). A signed file left empty is removed after raising the generation - /// ([`take_signed_grants`]). A file VectorCraft didn't write for this folder ([`Trust::Unsigned`]) - /// grants nothing: a grant replaces it with a file that holds that grant alone, and removing one + /// ([`take_signed_grants`]). The generation is never lowered: when the file can't be written or + /// removed after the raise, the file in place grants nothing and its plug-ins ask again. A file + /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant replaces it with a file that holds that grant alone, and removing one /// raises the generation ([`raise_generation`]), then takes out the entry for `id` and leaves the /// rest unsigned. Removing a grant when there is no file, or when the file grants nothing /// (unsigned, too large or not a list) and has no entry to take out, also raises the generation @@ -1611,10 +1620,12 @@ fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { /// is raised first ([`raise_generation`]), the file is written at the generation after the raised one /// with its MAC, and the key store keeps that generation once the file is written. Every signed write /// is then at a generation no file was signed at before, a write whose generation wasn't kept -/// included, since that one is at most one past the generation the key store kept. When the file -/// isn't written, the generation kept before is put back. When the file's generation can't be kept, -/// the file is at a generation the key store doesn't hold, so it grants nothing, and the write -/// reports a failure. Call it in the store's turn ([`StoreTurn`]). +/// included, since that one is at most one past the generation the key store kept. A file too large +/// either way is found before the raise, and then nothing changes. The kept generation only goes up: +/// when the file isn't written after the raise, the generation stays raised, so the file in place +/// grants nothing and its plug-ins ask again. When the file's generation can't be kept, the file is +/// at a generation the key store doesn't hold, so it grants nothing either. Both report a failure. +/// Call it in the store's turn ([`StoreTurn`]). fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool { let path = dir.join(GRANTS_FILE); let folder = plugin_store_key(dir); @@ -1634,25 +1645,26 @@ fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool return false; } }; - let Some((before, raised)) = raise_generation(dir) else { return false }; - let Some(next) = raised.checked_add(1) else { - log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display()); - keep_generation(dir, &folder, before); - return false; - }; - let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); - let file = mac - .and_then(|mac| serde_json::to_value(SignedGrants { version: GRANTS_VERSION, generation: Some(next), grants: entries, mac: Some(mac) }).ok()); - let Some(bytes) = grants_bytes(file) else { + // A file too large to keep is found before the raise, at the longest generation and a MAC of its + // length, so the file in place keeps its grants when nothing can be written. + let mut file = + SignedGrants { version: GRANTS_VERSION, generation: Some(u64::MAX), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) }; + if grants_bytes(serde_json::to_value(&file).ok()).is_none() { log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); - keep_generation(dir, &folder, before); - return false; - }; - if !put(dir, GRANTS_FILE, &bytes) { - keep_generation(dir, &folder, before); return false; } - keep_generation(dir, &folder, next) + let Some(raised) = raise_generation(dir) else { return false }; + let Some(next) = raised.checked_add(1) else { + log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display()); + return false; + }; + file.generation = Some(next); + file.mac = serde_json::to_vec(&file.grants).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); + let Some(bytes) = file.mac.as_ref().and_then(|_| grants_bytes(serde_json::to_value(&file).ok())) else { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + return false; + }; + put(dir, GRANTS_FILE, &bytes) && keep_generation(dir, &folder, next) } /// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than @@ -1675,34 +1687,30 @@ fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { } /// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is -/// raised first, so that no copy of the file grants anything once it is gone; when the file can't be -/// removed, the generation is put back, so the file keeps its grants, and when that can't be put back -/// either, the file grants nothing. The file holds no grant but the one being removed. Nothing is -/// removed when the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). +/// raised first, so that no copy of the file grants anything once it is gone. The generation stays +/// raised when the file can't be removed: the file left in place then grants nothing, and its +/// plug-ins ask again. The file holds no grant but the one being removed. Nothing is removed when +/// the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). fn take_signed_grants(dir: &Path) -> bool { - let Some((before, _)) = raise_generation(dir) else { return false }; - if take(dir, GRANTS_FILE) { - return true; - } - keep_generation(dir, &plugin_store_key(dir), before); - false + raise_generation(dir).is_some() && take(dir, GRANTS_FILE) } /// Keep a generation two past the one kept for the grants file of the plug-in store `dir`, so that -/// no signed copy of the file made before grants anything → the generation kept before and the one -/// kept now; `None`, with a log record, when the key store can't read or keep it or the generation -/// is too large to raise. A signed write whose generation wasn't kept is at the generation after the -/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the key -/// store alone, never from a file, which anyone can edit. -fn raise_generation(dir: &Path) -> Option<(u64, u64)> { +/// no signed copy of the file made before grants anything → the generation kept now; `None`, with a +/// log record, when the key store can't read or keep it or the generation is within two of the +/// largest 64-bit value. A signed write whose generation wasn't kept is at the generation after the +/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the +/// key store alone, never from a file, which anyone can edit, and it is never lowered again. +fn raise_generation(dir: &Path) -> Option { let folder = plugin_store_key(dir); let raised = grant_keys::current_generation(&folder).and_then(|generation| { - let next = generation.checked_add(2); + // A signed write goes one past the raised generation, so that one must fit too. + let next = generation.checked_add(3).and(generation.checked_add(2)); let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; - grant_keys::set_current_generation(&folder, next).map(|()| (generation, next)) + grant_keys::set_current_generation(&folder, next).map(|()| next) }); match raised { - Ok(generations) => Some(generations), + Ok(generation) => Some(generation), Err(e) => { log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); None diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs index 2ae59dc825..0c551e4ecc 100644 --- a/crates/engine/src/store/grant_keys.rs +++ b/crates/engine/src/store/grant_keys.rs @@ -6,9 +6,9 @@ //! machine) grants nothing. //! //! The key store also keeps a generation for each plug-in folder, raised on every signed write of -//! its grants file, and the file carries its generation inside the MAC. A file whose generation is -//! not the one kept (an earlier copy put back over the current file, or a write whose generation -//! the key store didn't keep) grants nothing either. +//! its grants file and never lowered, and the file carries its generation inside the MAC. A file +//! whose generation is not the one kept (an earlier copy put back over the current file, or a write +//! whose generation the key store didn't keep or that failed after the raise) grants nothing either. //! //! The process uses one key store ([`set_grant_key_store`]); the apps use the system's //! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key @@ -182,9 +182,15 @@ pub(crate) fn current_generation(folder: &Path) -> Result { Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0)) } -/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. +/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. The kept +/// generation only goes up: one lower than the kept one is an error, and the kept one stays, since a +/// lower one could match a file signed before. pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> { - current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.set_generation(folder, generation) + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + if store.generation(folder)?.is_some_and(|kept| generation < kept) { + return Err(KeyStoreError("the key store keeps a later generation".into())); + } + store.set_generation(folder, generation) } /// The start of every MAC input: what it is a MAC of, and the version of the file. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index ea7a1a48f2..75eea61a01 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2918,8 +2918,9 @@ fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { } /// When the last grant can't be removed because `grants.json` can't be deleted, a replacing module -/// that asks for no permissions doesn't stay in the store: the store gets back the module the grant -/// still covers, and the grant is left as it was. +/// that asks for no permissions doesn't stay in the store: the store gets back the earlier module, +/// and the file is left as it was. The generation was raised before the removal and stays raised, so +/// the file left in place grants nothing and the module asks again. #[test] fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { let folder = crate::tests_links::Folder::new("plugin-store-undeletable-grants"); @@ -2939,8 +2940,8 @@ fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); crate::store::GRANTS_DELETE_FAILS.set(false); assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); - assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays as it was"); - assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false, "the grant still covers the module"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file stays as it was"); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "the file left in place grants nothing"); run(&mut s, "plugin.remove", json!({"id": id})); assert!(!grants.exists(), "a removal that can delete the file forgets the grant"); @@ -4938,6 +4939,154 @@ fn a_write_whose_generation_wasnt_kept_grants_nothing_after_a_revoke() { } } +/// A signed write that fails after raising the generation leaves the generation raised: the file +/// left in place, signed at the generation before the raise, grants nothing and its plug-ins ask +/// again, and so does a copy of it put back after a later write. +#[test] +fn a_grants_write_that_fails_leaves_the_generation_raised() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-write-fails"); + let id = "test.engine.permissions.writefails"; + let other = "test.engine.permissions.writefailsother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let earlier = std::fs::read(&grants).unwrap(); + assert_eq!((generation_of(&earlier), kept(&folder.0)), (Some(3), Some(3))); + + crate::store::GRANTS_WRITE_FAILS.set(true); + let grant = vectorcraft_plugins::permissions::Grant { + id: other.into(), + hash: vectorcraft_plugins::permissions::sha256_hex(b"module"), + permissions: vec![vectorcraft_plugins::permissions::Permission::DocRead], + }; + let written = s.store_grant(other, Some(grant)); + crate::store::GRANTS_WRITE_FAILS.set(false); + assert!(!written, "the write reports a failure"); + assert_eq!(std::fs::read(&grants).unwrap(), earlier, "the file is left as it was"); + assert_eq!(kept(&folder.0), Some(5), "the generation stays raised"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file left in place grants nothing"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(8), Some(8)), "the next write is past the raise"); + assert_eq!(starts_from(&folder.0, other, &other_data), (true, false), "the next write keeps its grant"); + std::fs::write(&grants, &earlier).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy from before the raise grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); + _ = s.execute("plugin.remove", &json!({"id": other})); +} + +/// A revoke whose signed grants file can't be removed leaves the generation raised: the grant left in +/// the file doesn't come back, and a later removal takes the file away. +#[test] +fn a_revoke_whose_grants_file_cant_be_removed_doesnt_bring_the_grant_back() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-remove-fails"); + let id = "test.engine.permissions.removefails"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let recorded = std::fs::read(&grants).unwrap(); + + crate::store::GRANTS_DELETE_FAILS.set(true); + let revoked = s.store_grant(id, None); + crate::store::GRANTS_DELETE_FAILS.set(false); + assert!(!revoked, "the removal reports a failure"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file is left as it was"); + assert_eq!(kept(&folder.0), Some(5), "the generation stays raised"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the revoked grant doesn't come back"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None), "a later removal is recorded"); + assert!(!grants.exists(), "and takes the file away"); + std::fs::write(&grants, &recorded).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); +} + +/// The key store's generation for a folder only goes up: a lower one is refused and the kept one +/// stays, while the same one and a higher one are kept. +#[test] +fn the_kept_grants_generation_is_never_lowered() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-lowered"); + let store = crate::store::plugin_store_key(&folder.0); + assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok()); + assert!(crate::store::grant_keys::set_current_generation(&store, 3).is_err(), "a lower generation is refused"); + assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(5), "the kept one stays"); + assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok(), "the same one is kept"); + assert!(crate::store::grant_keys::set_current_generation(&store, 6).is_ok()); + assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(6)); +} + +/// A kept generation within two of the largest 64-bit value isn't raised: a signed write leaves the +/// file and the generation as they are, and the file keeps its grant. Three below it, the write goes +/// to the largest value. +#[test] +fn a_kept_generation_near_the_largest_value_isnt_raised() { + use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + for (kept_before, written) in [(u64::MAX - 2, None), (u64::MAX - 3, Some(u64::MAX))] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-generation-near-max-{}", u64::MAX - kept_before)); + let store = crate::store::plugin_store_key(&folder.0); + let id = "test.engine.permissions.nearmax"; + let other = "test.engine.permissions.nearmaxother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, kept_before).unwrap(); + let file = + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + std::fs::write(&grants, &file).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file grants"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let grant = Grant { id: other.into(), hash: sha256_hex(b"module"), permissions: vec![Permission::DocRead] }; + assert_eq!(s.store_grant(other, Some(grant)), written.is_some(), "{kept_before}"); + match written { + None => { + assert_eq!(std::fs::read(&grants).unwrap(), file, "{kept_before}: the file is left as it is"); + assert_eq!(kept_generation(&keys, &folder.0), Some(kept_before), "{kept_before}: the generation too"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file keeps its grant"); + } + Some(generation) => { + assert_eq!( + (generation_of(&std::fs::read(&grants).unwrap()), kept_generation(&keys, &folder.0)), + (Some(generation), Some(generation)) + ); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the new file keeps the grant"); + } + } + std::fs::remove_file(&grants).unwrap(); + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + } +} + /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next /// start without asking, with its budget. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index d7f6656357..339b672675 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -378,20 +378,22 @@ followed by the SHA-256 of the folder's resolved path in hexadecimal, in the sam generation for a folder counts as generation 0. VectorCraft reads the generation from the key store only, never from `grants.json`. Each time VectorCraft writes a signed `grants.json`, in the folder's turn (`disabled.lock`), it first raises the kept generation by two, then writes the file at the generation after the raised one, and then keeps that -generation; when the file can't be written, it puts the earlier generation back. When it removes a signed -`grants.json`, it raises the generation by two first, and puts the earlier one back when the file can't be removed; -when the key store can't put it back either, the file grants nothing. -When the key store can't keep the generation of a write, the file just written grants nothing, and the write reports a -failure. That file is one generation past the kept one, so the next raise by two moves past it. When raising the -generation by two would pass the largest 64-bit value, VectorCraft logs a warning and changes nothing. +generation. When it removes a signed `grants.json`, it raises the generation by two first. The kept generation never +goes down: when the file can't be written or removed after the raise, the generation stays raised, the file left in +place grants nothing, and each plug-in it names that lists permissions asks for approval again. VectorCraft checks +before the raise whether the signed file would be larger than 1 MiB; when it would, VectorCraft logs a warning and +leaves the file and the generation as they are. When the key store can't keep the generation of a write, the file +just written grants nothing, and the write reports a failure. That file is one generation past the kept one, so the +next raise by two moves past it. When the kept generation is within two of the largest 64-bit value, VectorCraft +logs a warning and leaves the file and the generation as they are. VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its generation, its grants and its folder, or at another generation than the one the key store keeps for the folder, grants nothing, and each plug-in it names that lists permissions asks for approval again. This covers a file that an earlier version wrote (a plain JSON list), a grant that another program edited or added, a file whose `mac` was removed or changed, a file copied from another `Plug-ins` folder or another computer, an earlier copy of the file put back after a grant was revoked or the -file was removed, a write whose generation the key store didn't keep, and a file whose key is no longer in the key -store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when +file was removed, a write whose generation the key store didn't keep, a file left in place by a write or removal that +failed, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists no permissions under that id, or a folder load that forgets the grant), VectorCraft raises the generation by two, then takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. It diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 686e392e49..c397de9452 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2660,7 +2660,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. -- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal and never lowered. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept, a file left in place by a failed write or removal) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. From 685e7cc3ea9c3cc0ef60d56d3f64fc3952fb2141 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:07:55 -0800 Subject: [PATCH 014/107] Plug-ins: a removal the key store can't make last fails plugin.remove now fails and leaves the plug-in installed while the key store can't be reached, also when grants.json is missing or doesn't name the plug-in, since an earlier signed copy put back could otherwise grant it again. A grants file that is too large or doesn't hold a list no longer stops a removal once the generation is raised. Removing an id that isn't installed deletes the module stored for it that didn't load and reports it removed. The system key store is reached through keyring-core and the platform store crates keyring 4.2 uses; a failed connection is tried again on the next call. The key is read from the key store each time grants.json is checked or signed, so a key removed or replaced there is not used. The key and the generations are kept as hexadecimal text. On Windows the lock for making the first key is in %LOCALAPPDATA%. The wrong-key and copied-file cases of the edited-file test are at the generation kept for their folder, so only the MAC rejects them. --- Cargo.lock | 17 +- crates/engine/Cargo.toml | 12 +- crates/engine/src/cmd/plugin.rs | 18 ++- crates/engine/src/store.rs | 29 ++-- crates/engine/src/store/grant_keys.rs | 215 ++++++++++++++++++++------ crates/engine/src/tests/plugins.rs | 97 +++++++++++- docs/mcp.md | 8 +- docs/plugins.md | 32 ++-- docs/target-app-parity.md | 2 +- 9 files changed, 327 insertions(+), 103 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6e94cee6fb..70b0d0bffb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3596,18 +3596,6 @@ dependencies = [ "serde", ] -[[package]] -name = "keyring" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" -dependencies = [ - "apple-native-keyring-store", - "keyring-core", - "windows-native-keyring-store", - "zbus-secret-service-keyring-store", -] - [[package]] name = "keyring-core" version = "1.1.0" @@ -7204,6 +7192,7 @@ dependencies = [ name = "vectorcraft-engine" version = "0.24.1" dependencies = [ + "apple-native-keyring-store", "cfb", "chrono", "craft-cdr", @@ -7224,7 +7213,7 @@ dependencies = [ "jxl-color", "jxl-grid", "jxl-oxide", - "keyring", + "keyring-core", "kurbo 0.13.1", "log", "proptest", @@ -7261,6 +7250,8 @@ dependencies = [ "vectorcraft-tools", "vectorcraft-trace", "wat", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", "zune-core", "zune-jpegxl", ] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4a393d890f..98a748000e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -79,6 +79,8 @@ rustix = { workspace = true, features = ["std", "process"] } # (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" +# Credential Manager, the system key store of grant_keys.rs on Windows (see keyring-core below). +windows-native-keyring-store = "1.1" # The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] @@ -90,7 +92,15 @@ rayon = { version = "1.12", optional = true } hmac = "0.12.1" sha2 = { version = "0.10", default-features = false } getrandom = "0.4" -keyring = "4.2" +keyring-core = "1.1" + +# The system key store of grant_keys.rs on each platform, connected through keyring-core: the same +# store crates and features that keyring 4.2 uses. All MIT OR Apache-2.0. +[target.'cfg(target_os = "macos")'.dependencies] +apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] } + +[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))'.dependencies] +zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] } [dev-dependencies] # JPEG XL files for the `.jxl` open and place tests. diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 5e2e669563..c2395534a3 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1219,9 +1219,10 @@ fn remove(s: &mut Session, p: &Value) -> Result { // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); // Installed again, it asks again. A grant that can't be removed may still approve the module, and - // so may a grants file that can't be opened or read. One that is too large or doesn't hold a - // list approves nothing and doesn't stop the removal. - let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id); + // so may a grants file that can't be opened or read, or a signed copy of the file put back when + // the generation couldn't be raised (the key store can't be reached). Without a plug-in folder + // nothing keeps a grant. + let forget = || s.store_grant_in(&turn, id, None) || s.plugin_dir.is_none(); // Its settings and cache are moved aside and its grant removed before anything is deleted: when // either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove` // tries again. @@ -1237,8 +1238,13 @@ fn remove(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other(e)); } registry::revoke(id); - s.unstore_plugin(&turn, id); - if !stored && (!installed || !registry::remove(id)) { + // A module stored for an id that isn't installed (one no grant covers is skipped at startup) + // counts as removed once its file is gone. + let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id); + if !s.unstore_plugin(&turn, id) && module { + return Err(EngineError::Other(format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default()))); + } + if !stored && !module && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } Ok(json!({"removed": id})) @@ -1315,7 +1321,7 @@ pub fn specs() -> Vec { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", always, remove ), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 73215c4999..57e693ef43 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -748,9 +748,11 @@ impl Session { /// doesn't grant it again. The generation is never read from the file; when it can't be raised, /// nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry - /// for `id` stays. A grants file that is too large, can't - /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; - /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and + /// for `id` stays; a removal then reports a failure, also when the file doesn't name `id`. A + /// grants file that is too large, can't be read or doesn't hold a list is left as it is, with a + /// log record, and nothing is recorded; so is one whose new content would be larger than + /// `MAX_GRANTS_FILE`. A removal still holds for a file that is too large or doesn't hold a list + /// once the generation is raised ([`retire_signed_copies`]). The file is read and /// written in `turn`. → whether the store now holds what was asked (`false` without a folder, /// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every /// session in the process attached to the store ([`Session::ignore_stored_grant`]). @@ -809,11 +811,9 @@ impl Session { Err(e) => { log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); // A file that is too large or doesn't hold a list grants nothing and is left as it - // is, but a signed copy made before it must not grant `id` again once it is put back. - if grant.is_none() && !e.unread { - retire_signed_copies(dir); - } - return false; + // is, but a signed copy made before it must not grant `id` again once it is put back: + // the removal holds once no such copy can. + return grant.is_none() && !e.unread && retire_signed_copies(dir); } }; #[cfg(test)] @@ -822,9 +822,10 @@ impl Session { } match (file.trust, &grant) { // Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for - // the session only, and one the file may still hold for `id` can't be removed. - (Trust::Unknown, Some(_)) => return false, - (Trust::Unknown, None) => return !file.names(id), + // the session only, and one the file may still hold for `id` can't be removed. A file + // that doesn't name `id` may not be the one the kept generation was signed for, so the + // removal isn't known to hold either. + (Trust::Unknown, _) => return false, // The file grants nothing. A new grant replaces it with a signed file that holds that // grant alone; removing one takes its entry out and leaves the rest unsigned. (Trust::Unsigned, Some(_)) => { @@ -875,6 +876,12 @@ impl Session { }) } + /// Does the attached plug-in store hold a module file for the plug-in `id`, loaded or not (one + /// that no grant covers is skipped at startup and stays in the folder)? + pub(crate) fn holds_stored_plugin(&self, id: &str) -> bool { + self.plugin_dir.as_deref().is_some_and(|dir| std::fs::symlink_metadata(dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id)))).is_ok()) + } + /// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a /// folder, and when `turn` isn't held). pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool { diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs index 0c551e4ecc..034d44d582 100644 --- a/crates/engine/src/store/grant_keys.rs +++ b/crates/engine/src/store/grant_keys.rs @@ -260,11 +260,26 @@ fn from_hex(tag: &str) -> Option> { pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect() } -/// The system's key store, through `keyring`. The key is read once and kept for the process. +/// The system's key store, through `keyring-core` and the store crate of the platform. The key is +/// read from the store each time it is needed. The key and the generations are kept as lower-case +/// hexadecimal text, since some stores (KDE Wallet behind the Secret Service) keep only UTF-8. #[cfg(not(target_arch = "wasm32"))] -#[derive(Default)] struct OsGrantKeys { - read: Mutex>, + /// Held while a key is kept, so that the threads of the process that make the first key at the + /// same time keep one. + making: Mutex<()>, + /// The connection to the system's key store, once one is made. A failed connection is not + /// kept: the next call tries again, so a key store that starts after VectorCraft is used. + store: Mutex>>, + /// How a connection is made ([`connect`]). + connect: fn() -> Result, keyring_core::Error>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Default for OsGrantKeys { + fn default() -> Self { + OsGrantKeys { making: Mutex::default(), store: Mutex::default(), connect } + } } #[cfg(not(target_arch = "wasm32"))] @@ -272,96 +287,141 @@ impl OsGrantKeys { const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants"; const ACCOUNT: &str = "hmac-sha256-v1"; - fn entry() -> Result { - keyring::Entry::new(Self::SERVICE, Self::ACCOUNT).map_err(store_error) + /// The system's key store: the connection made before, else a new one. + fn store(&self) -> Result, KeyStoreError> { + let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(store) = store.as_ref() { + return Ok(store.clone()); + } + Ok(store.insert((self.connect)().map_err(store_error)?).clone()) + } + + fn entry(&self, account: &str) -> Result { + self.store()?.build(Self::SERVICE, account, None).map_err(store_error) + } + + fn key_entry(&self) -> Result { + self.entry(Self::ACCOUNT) } /// The key the system's key store keeps, read from it. - fn stored(entry: &keyring::Entry) -> Result, KeyStoreError> { + fn stored(entry: &keyring_core::Entry) -> Result, KeyStoreError> { match entry.get_secret() { - // A secret of another length is not a key this version made: there is none. - Ok(secret) => Ok(<[u8; KEY_LEN]>::try_from(secret.as_slice()).ok().map(GrantKey)), - Err(keyring::Error::NoEntry) => Ok(None), + // A secret that is not 64 hexadecimal digits is not a key this version made: there is none. + Ok(secret) => Ok(std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok()) + .map(GrantKey)), + Err(keyring_core::Error::NoEntry) => Ok(None), Err(e) => Err(store_error(e)), } } /// The entry of the generation of the plug-in store whose folder is `folder`: the account /// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits. - fn generation_entry(folder: &Path) -> Result { + fn generation_entry(&self, folder: &Path) -> Result { use sha2::Digest; let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes()); - let account: String = digest.iter().map(|b| format!("{b:02x}")).collect(); - keyring::Entry::new(Self::SERVICE, &format!("generation-v1-{account}")).map_err(store_error) + self.entry(&format!("generation-v1-{}", to_hex(&digest))) } } +/// A connection to the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs. The same stores, made the same way, that `keyring` 4.2 +/// uses, so entries it kept are read. +#[cfg(not(target_arch = "wasm32"))] +fn connect() -> Result, keyring_core::Error> { + #[cfg(target_os = "macos")] + { + let store: Arc = apple_native_keyring_store::keychain::Store::new()?; + Ok(store) + } + #[cfg(windows)] + { + let store: Arc = windows_native_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))] + { + let store: Arc = zbus_secret_service_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(not(any(target_os = "macos", windows, all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))] + Err(keyring_core::Error::NoDefaultStore) +} + +/// `bytes` as lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +fn to_hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + #[cfg(not(target_arch = "wasm32"))] impl GrantKeyStore for OsGrantKeys { + /// Read from the key store each time, so that a key removed or replaced there is not used. fn key(&self) -> Result, KeyStoreError> { - let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(key) = read.as_ref() { - return Ok(Some(key.clone())); - } - Ok(Self::stored(&Self::entry()?)?.map(|key| read.insert(key).clone())) + Self::stored(&self.key_entry()?) } fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { - let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); - Self::entry()?.set_secret(&key.0).map_err(store_error)?; - *read = Some(key.clone()); - Ok(()) + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(store_error) } - /// Reads the key store again, not the key read before, and makes the key only while holding - /// [`creation_lock`], so that processes of this user that make the first key at the same time - /// all keep the first one made. + /// Reads the key store again and makes the key only while holding [`creation_lock`], so that + /// processes of this user that make the first key at the same time all keep the first one made. fn create_key(&self) -> Result { - let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); - let entry = Self::entry()?; + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + let entry = self.key_entry()?; if let Some(key) = Self::stored(&entry)? { - return Ok(read.insert(key).clone()); + return Ok(key); } let _turn = creation_lock()?; - let key = match Self::stored(&entry)? { - Some(key) => key, + match Self::stored(&entry)? { + Some(key) => Ok(key), None => { - entry.set_secret(&GrantKey::random()?.0).map_err(store_error)?; - Self::stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))? + entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(store_error)?; + Self::stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) } - }; - *read = Some(key.clone()); - Ok(key) + } } /// Read from the key store each time, since another process on the folder may have raised it. - /// A kept value that is not 8 bytes is an error, so that nothing counts as signed with it. + /// A kept value that is not 16 hexadecimal digits is an error, so that nothing counts as signed + /// with it. fn generation(&self, folder: &Path) -> Result, KeyStoreError> { - match Self::generation_entry(folder)?.get_secret() { - Ok(secret) => <[u8; 8]>::try_from(secret.as_slice()) + match self.generation_entry(folder)?.get_secret() { + Ok(secret) => std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok()) .map(|bytes| Some(u64::from_be_bytes(bytes))) - .map_err(|_| KeyStoreError("the key store holds a generation of another length".into())), - Err(keyring::Error::NoEntry) => Ok(None), + .ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())), + Err(keyring_core::Error::NoEntry) => Ok(None), Err(e) => Err(store_error(e)), } } fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { - Self::generation_entry(folder)?.set_secret(&generation.to_be_bytes()).map_err(store_error) + self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(store_error) } } /// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is -/// dropped, waiting while another process holds it: the temporary folder on Windows and macOS, -/// `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file can't be -/// locked: no key is made then. +/// dropped, waiting while another process holds it: `%LOCALAPPDATA%` on Windows, the temporary +/// folder on macOS, `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file +/// can't be locked: no key is made then. #[cfg(not(target_arch = "wasm32"))] fn creation_lock() -> Result { - #[cfg(any(windows, target_os = "macos"))] - let dir = Some(std::env::temp_dir()); + #[cfg(windows)] + let (dir, variable) = (std::env::var_os("LOCALAPPDATA"), "%LOCALAPPDATA%"); + #[cfg(target_os = "macos")] + let (dir, variable) = (Some(std::env::temp_dir().into_os_string()), "$TMPDIR"); #[cfg(not(any(windows, target_os = "macos")))] - let dir = std::env::var_os("XDG_RUNTIME_DIR").map(std::path::PathBuf::from).filter(|dir| dir.is_absolute()); - let dir = dir.ok_or_else(|| KeyStoreError("there is no folder for the key's lock ($XDG_RUNTIME_DIR is not set)".into()))?; + let (dir, variable) = (std::env::var_os("XDG_RUNTIME_DIR"), "$XDG_RUNTIME_DIR"); + let dir = dir.map(std::path::PathBuf::from).filter(|dir| dir.is_absolute()); + let dir = dir.ok_or_else(|| KeyStoreError(format!("there is no folder for the key's lock ({variable} is not set)")))?; let file = std::fs::File::options() .create(true) .truncate(false) @@ -375,11 +435,64 @@ fn creation_lock() -> Result { /// What a key store error says, without the secret some of them hold. #[cfg(not(target_arch = "wasm32"))] -fn store_error(e: keyring::Error) -> KeyStoreError { +fn store_error(e: keyring_core::Error) -> KeyStoreError { KeyStoreError(match e { - keyring::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"), - keyring::Error::PlatformFailure(e) => format!("the key store failed ({e})"), - keyring::Error::NoDefaultStore => "there is no key store".into(), + keyring_core::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"), + keyring_core::Error::PlatformFailure(e) => format!("the key store failed ({e})"), + keyring_core::Error::NoDefaultStore => "there is no key store".into(), _ => "the key store can't read or keep the key".into(), }) } + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + use keyring_core::api::CredentialStoreApi; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Connections asked for from [`flaky`]. + static TRIES: AtomicUsize = AtomicUsize::new(0); + /// The store [`flaky`] connects to. + static MOCK: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that can't be reached on the first try and is reached on every later one. + fn flaky() -> Result, keyring_core::Error> { + if TRIES.fetch_add(1, Ordering::SeqCst) == 0 { + return Err(keyring_core::Error::NoDefaultStore); + } + let store: Arc = MOCK.clone(); + Ok(store) + } + + /// The secret `MOCK` keeps for `account`, as it is kept. + fn kept(account: &str) -> Vec { + MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap() + } + + /// The system key store is connected again after a connection fails, the key and the + /// generations are kept as hexadecimal text, and the key is read from the store each time; a + /// value kept as raw bytes is not read as a key or a generation. + #[test] + fn the_system_key_store_reconnects_and_keeps_text() { + let keys = OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }; + assert!(keys.key().is_err(), "the first connection fails"); + let key = GrantKey::from_bytes([0xa7; KEY_LEN]); + keys.set_key(&key).unwrap(); + assert_eq!(kept(OsGrantKeys::ACCOUNT), "a7".repeat(KEY_LEN).into_bytes(), "the key is kept as text"); + assert_eq!(OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }.key().unwrap(), Some(key), "and read back"); + + let folder = Path::new("/plug-ins"); + keys.set_generation(folder, 0x1_0000_0005).unwrap(); + let account = format!("generation-v1-{}", to_hex(&::digest(folder.as_os_str().as_encoded_bytes()))); + assert_eq!(kept(&account), b"0000000100000005", "the generation is kept as text"); + assert_eq!(keys.generation(folder).unwrap(), Some(0x1_0000_0005)); + + MOCK.build(OsGrantKeys::SERVICE, &account, None).unwrap().set_secret(&5u64.to_be_bytes()).unwrap(); + assert!(keys.generation(folder).is_err(), "a generation kept as raw bytes is an error"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret(&[0xa7; KEY_LEN]).unwrap(); + assert_eq!(keys.key().unwrap(), None, "a key kept as raw bytes is none, also after a key was read"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("b8".repeat(KEY_LEN).as_bytes()).unwrap(); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xb8; KEY_LEN])), "a key replaced in the key store is the one used"); + } +} diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 75eea61a01..e0ebeab953 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4313,8 +4313,12 @@ fn a_grants_file_changed_outside_vectorcraft_grants_nothing() { change(&mut file); serde_json::to_vec(&file).unwrap() }; + // At the generation kept for the folder, so that only the MAC tells the file apart. + let generation = file["generation"].as_u64().unwrap(); let other_key = { - let _other = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([7; 32]))); + let keys = MemoryGrantKeys::with_key(GrantKey::from_bytes([7; 32])); + crate::store::grant_keys::GrantKeyStore::set_generation(&keys, &crate::store::plugin_store_key(&folder.0), generation).unwrap(); + let _other = ThreadKeys::using(keys); crate::store::signed_grants_file(&folder.0, &file["grants"].to_string()) }; let tag = file["mac"].as_str().unwrap().to_string(); @@ -4339,6 +4343,7 @@ fn a_grants_file_changed_outside_vectorcraft_grants_nothing() { std::fs::write(&grants, &written).unwrap(); std::fs::write(copy.0.join("copied.wasm"), &wasm).unwrap(); std::fs::write(copy.0.join("grants.json"), &written).unwrap(); + crate::store::grant_keys::set_current_generation(&crate::store::plugin_store_key(©.0), generation).unwrap(); assert_eq!(starts_from(©.0, id, &data), (false, true), "copied into another folder"); assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file left as written keeps its grant"); std::fs::remove_file(&added_file).unwrap(); @@ -4459,6 +4464,87 @@ fn an_unreachable_key_store_keeps_approvals_in_the_session() { assert!(!grants.exists()); } +/// While the key store can't be reached, removing a plug-in fails and leaves it installed when no +/// earlier signed copy of the grants file can be kept from granting it again: with the grants file +/// gone, and with a grants file that doesn't name the plug-in. Once the key store can be reached, the +/// removal raises the generation, and the copy put back grants nothing. +#[test] +fn a_removal_the_key_store_cannot_make_last_fails() { + let folder = crate::tests_links::Folder::new("plugin-store-unreachable-remove"); + let id = "test.engine.permissions.unreachableremove"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + let written = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + + let locked = ThreadKeys::using(UnreachableKeys); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with the grants file gone: {refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed"); + drop(locked); + run(&mut s, "plugin.remove", json!({"id": id})); + std::fs::write(&grants, &written).unwrap(); + std::fs::write(&module, &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing"); + std::fs::remove_file(&grants).unwrap(); + std::fs::remove_file(&module).unwrap(); + + let other = "test.engine.permissions.unreachableremoveother"; + let plain = vectorcraft_format::base64_encode(&asking(id, "[]", &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": plain})); + let names: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect(); + assert_eq!(names, vec![json!(other)], "the grants file doesn't name the plug-in"); + let locked = ThreadKeys::using(UnreachableKeys); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with a grants file that can't be checked: {refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed"); + drop(locked); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "plugin.remove", json!({"id": other})); +} + +/// A stored plug-in that didn't load, because the grants file of an older version doesn't count, and +/// that keeps no settings or cache, is removed with its module and its entry, and the removal +/// reports it removed. A removal whose stored module can't be deleted fails. +#[test] +fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-unloaded-remove"); + let id = "test.engine.permissions.unloadedremove"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write(&module, &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the unsigned list grants nothing"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id}))); + assert!(!module.exists(), "the module is removed"); + assert!(!grants.exists(), "and its entry"); + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "a second removal finds nothing"); + + // A stored module that can't be deleted (here a folder in its place), of a plug-in that keeps + // settings, fails the removal. + std::fs::create_dir_all(module.join("held")).unwrap(); + std::fs::create_dir_all(crate::store::plugin_data_dir(&folder.0, id)).unwrap(); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains("can't delete"), "{refused}"); + assert!(module.exists()); + std::fs::remove_dir_all(&module).unwrap(); +} + /// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same /// key, generation, grants and folder verifies. A key's bytes are never printed. #[test] @@ -4610,14 +4696,15 @@ fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { std::fs::write(&grants, &signed).unwrap(); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over an unsigned file doesn't come back"); - // A file that doesn't hold a list is in place: the revoke isn't recorded, and still raises the - // generation. + // A file that doesn't hold a list is in place: it is left as it is, and the revoke holds once it + // raises the generation. let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); let signed = std::fs::read(&grants).unwrap(); std::fs::write(&grants, br#""not a list""#).unwrap(); - assert!(!s.store_grant(id, None)); + assert!(s.store_grant(id, None)); + assert_eq!(std::fs::read(&grants).unwrap(), br#""not a list""#, "the file is left as it is"); std::fs::write(&grants, &signed).unwrap(); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over a file without a list doesn't come back"); } @@ -4926,7 +5013,7 @@ fn a_write_whose_generation_wasnt_kept_grants_nothing_after_a_revoke() { "not-a-list" => std::fs::write(&grants, br#""not a list""#).unwrap(), _ => std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &other_grant)).unwrap(), } - assert_eq!(s.store_grant(other, None), path != "not-a-list", "{path}"); + assert!(s.store_grant(other, None), "{path}"); std::fs::write(&grants, &unkept).unwrap(); assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "{path}: the revoked grant doesn't come back"); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{path}: the copy grants nothing"); diff --git a/docs/mcp.md b/docs/mcp.md index 7fc070afcc..66c3463593 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13231,9 +13231,11 @@ approval lasts for that session only and the file is left as it is. `plugin.remo forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When -`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed. -When the plug-in's settings and cache can't be moved back from their `.removed` folder then either, the error names -that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A +`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed; +so does a `plugin.remove` while the system key store can't be reached, also when `grants.json` is missing or doesn't +name the plug-in. For an id that isn't installed, `plugin.remove` also deletes the module stored for it that didn't +load and returns `{removed}`. When the plug-in's settings and cache can't be moved back from their `.removed` folder +then either, the error names that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A filter without `doc.write` or `state` that returns output needing them gets an error and the document is unchanged. A plug-in of API level 2 (`api: 2` in its entry) that lists `progress` may report its progress, see Cancel and write log lines: `notifications/cancelled` makes its `vc_cancelled` return 1, and its log lines go to the server's log diff --git a/docs/plugins.md b/docs/plugins.md index 339b672675..a1a8c0c848 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -362,27 +362,33 @@ each time it is drawn, and a paint linked to a global swatch is drawn in that sw `mac` is an HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the folder the file is in, the `generation` and the `grants` list written as compact JSON. The key is 32 random bytes that VectorCraft makes when it records the first grant. VectorCraft keeps the key in the system key store, as the secret of -the account `hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, and never in a file: +the account `hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, written as 64 lower-case +hexadecimal digits, and never in a file: - On macOS the key is in the user's Keychain. - On Windows the key is a generic credential in Credential Manager. - On Linux and the BSDs the key is in the Secret Service, for example GNOME Keyring. When its collection is locked, the desktop may ask to unlock it. -VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in the temporary folder on Windows and -macOS, and in `$XDG_RUNTIME_DIR` elsewhere. When that file can't be locked, or `$XDG_RUNTIME_DIR` is not set, no key -is made, and approvals last for the session only, as when the key store can't be reached. +When VectorCraft can't connect to the key store, it tries again the next time it needs the key, so a key store that +starts after VectorCraft is used without a restart. VectorCraft reads the key from the key store each time it checks or +signs `grants.json`, so a key removed or replaced there is not used. -The key store also keeps a generation for each `Plug-ins` folder, as an 8-byte secret of the account `generation-v1-` -followed by the SHA-256 of the folder's resolved path in hexadecimal, in the same service. A key store that holds no -generation for a folder counts as generation 0. VectorCraft reads the generation from the key store only, never from -`grants.json`. Each time VectorCraft writes a signed `grants.json`, in the folder's turn (`disabled.lock`), it first +VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in `%LOCALAPPDATA%` on Windows, in the +temporary folder on macOS, and in `$XDG_RUNTIME_DIR` elsewhere. When that file can't be locked, or `%LOCALAPPDATA%` or +`$XDG_RUNTIME_DIR` is not set, no key is made, and approvals last for the session only, as when the key store can't be +reached. + +The key store also keeps a generation for each `Plug-ins` folder, as a secret of 16 lower-case hexadecimal digits (the +generation as an 8-byte big-endian number) of the account `generation-v1-` followed by the SHA-256 of the folder's +resolved path in hexadecimal, in the same service. A key store that holds no generation for a folder counts as +generation 0. VectorCraft reads the generation from the key store only, never from `grants.json`. Each time VectorCraft writes a signed `grants.json`, in the folder's turn (`disabled.lock`), it first raises the kept generation by two, then writes the file at the generation after the raised one, and then keeps that generation. When it removes a signed `grants.json`, it raises the generation by two first. The kept generation never goes down: when the file can't be written or removed after the raise, the generation stays raised, the file left in place grants nothing, and each plug-in it names that lists permissions asks for approval again. VectorCraft checks before the raise whether the signed file would be larger than 1 MiB; when it would, VectorCraft logs a warning and -leaves the file and the generation as they are. When the key store can't keep the generation of a write, the file +leaves the file and the generation as they are, and the file keeps its grants. When the key store can't keep the generation of a write, the file just written grants nothing, and the write reports a failure. That file is one generation past the kept one, so the next raise by two moves past it. When the kept generation is within two of the largest 64-bit value, VectorCraft logs a warning and leaves the file and the generation as they are. @@ -393,7 +399,7 @@ names that lists permissions asks for approval again. This covers a file that an list), a grant that another program edited or added, a file whose `mac` was removed or changed, a file copied from another `Plug-ins` folder or another computer, an earlier copy of the file put back after a grant was revoked or the file was removed, a write whose generation the key store didn't keep, a file left in place by a write or removal that -failed, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when +failed after the generation was raised, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists no permissions under that id, or a folder load that forgets the grant), VectorCraft raises the generation by two, then takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. It @@ -404,8 +410,10 @@ store can't raise the generation, VectorCraft logs a warning. When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no `grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored -for the id is not replaced, and `plugin.remove` of a plug-in that the file names returns an error, as for a grant that -can't be removed. With `VECTORCRAFT_NO_PREFS` set there is no plug-in store, and the web build keeps no grants file. The +for the id is not replaced, and `plugin.remove` of a plug-in returns an error and leaves the plug-in installed, as for a +grant that can't be removed. This also happens when there is no `grants.json` or the file doesn't name the plug-in. +`plugin.remove` of an id that isn't installed deletes the module stored for it that didn't load, such as one an +earlier version's `grants.json` approved, and returns `{removed}`. With `VECTORCRAFT_NO_PREFS` set there is no plug-in store, and the web build keeps no grants file. The MAC does not protect against another program running as the same user, which can read the key from the key store or change VectorCraft itself. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c397de9452..99bc22fc5d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2660,7 +2660,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. -- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal and never lowered. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept, a file left in place by a failed write or removal) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal and never lowered. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept, a file left in place by a write or removal that failed after the generation was raised) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file, and `plugin.remove` of a stored plug-in that didn't load deletes its module and reports it removed. When the key store can't be reached, an approval lasts for the session only, the file is left as it is, and `plugin.remove` fails and leaves the plug-in installed. A key store that can't be reached is tried again the next time it is needed. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/store/grant_keys.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. From c417aff8fbd9657fc4d9b6bfdbf54127b1a1cae9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:25:43 -0800 Subject: [PATCH 015/107] Scripts: .js scripts have Promise and run its jobs before the run ends A script run from a .js file now has Promise as ECMA-262 11th edition section 25.6 defines it: the constructor, then, catch, finally, and Promise.resolve, reject, all, allSettled and race. .jsx scripts and scripts given as source keep the ES5.1 built-ins; a named engine gets Promise at the first .js run that names it and keeps it. - The callbacks run as jobs from one FIFO queue after the script's own code ends and before the run ends, sliced like the script, with no native recursion along a then chain. Each job takes 1 unit of fuel, so an endless chain stops at the fuel limit. - More than 1,048,576 waiting jobs end the run with a Jobs limit error. A run that fails, hits a limit or is stopped drops its waiting jobs and rolls back as before. - A promise still rejected with no handler when the run ends goes to the report's unhandledRejections (first 20) and unhandledRejectionCount, and to the Script Console with its file, line and column. - Until the language has iterators, all, allSettled and race take arrays, objects with a whole-number length and strings, and the statics always build plain Promise objects. Promise.any is not provided. cargo xtask test262 now runs the suite's built-ins/Promise tests that need only the built-ins present: 402 of 538 runs pass. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/include.rs | 7 + crates/engine/src/script/mod.rs | 69 +- crates/engine/src/tests/script_include.rs | 56 ++ crates/js/src/builtins.rs | 4 + crates/js/src/builtins/promise.rs | 1109 +++++++++++++++++++++ crates/js/src/heap.rs | 22 +- crates/js/src/interp.rs | 23 +- crates/js/src/lib.rs | 18 +- crates/js/src/promise_tests.rs | 223 +++++ crates/js/src/realm.rs | 85 +- crates/js/tests/test262.rs | 146 ++- docs/mcp.md | 30 +- docs/target-app-parity.md | 1 + xtask/src/test262.rs | 4 +- 14 files changed, 1765 insertions(+), 32 deletions(-) create mode 100644 crates/js/src/builtins/promise.rs create mode 100644 crates/js/src/promise_tests.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 4223d829ba..6b83c81759 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -219,6 +219,13 @@ pub(crate) struct Files { frames: Vec, } +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as +/// ECMAScript 5.1 with the ExtendScript extensions. +pub(crate) fn es2015_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) +} + /// The output being built: its UTF-16 text, the line it is on, the units since that line began, /// whether its last unit is a carriage return, and what the last `#strict` line so far set. struct Out { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..6d51ac2925 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1592,24 +1592,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, /// with that file's name unless it is the run's own script. fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option>) { - let map = |m: &include::SourceMap| { - let (index, file, line, column) = m.locate(e.line, e.column); - let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; - (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) - }; // An error `$.evalFile` raised for a file it could not run, and no script caught, is at that // file's place. if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file)); } + placed(host, e, realm.error_source(), realm.error_tag()) +} + +/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`] +/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name +/// unless it is the run's own script. +fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option>) { + let map = |m: &include::SourceMap| { + let (index, file, line, column) = m.locate(e.line, e.column); + let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; + (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) + }; if e.line == 0 { return (e.clone(), None); } // An error in code from a source whose map is not at hand, such as code that `eval` compiled, // is given without a place. let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None); - match realm.error_source() { + match source { 0 => { let (e, index, file) = map(&host.script_map.borrow()); (e, (index > 0).then_some(file)) @@ -1626,7 +1633,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let kept = host.kept_maps.as_ref().map(|k| k.borrow()); - match kept.as_ref().and_then(|k| k.get(realm.error_tag())) { + match kept.as_ref().and_then(|k| k.get(tag)) { Some(kept) => { let (e, index, file) = map(&kept.map); let file = match &kept.script { @@ -1967,11 +1974,17 @@ impl Session { // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; + // A `.js` script's realm has the later editions' built-ins (`Promise`). A kept realm gets + // them at the first `.js` run that names it, and keeps them as it keeps its globals. + let es2015 = include::es2015_script(request.file.as_deref()); + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; let strict = options.strict; let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); + if es2015 { + realm.add_es2015(); + } realm } None => { @@ -2264,6 +2277,11 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + let rejections = rejections_report(host, &job.realm); + if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) { + o.insert("unhandledRejections".into(), Value::Array(rejections)); + o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count())); + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); @@ -2309,6 +2327,29 @@ const NO_RUN: &str = "this function's script run has ended"; const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped"; const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web"; const ENGINE_BUSY: &str = "the script engine is in use by another run"; +const UNHANDLED_REJECTION: &str = "unhandled promise rejection"; +const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections"; + +/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when +/// known, the line, column and file it was rejected at. +fn rejections_report(host: &Host, realm: &Realm) -> Vec { + let mut out = Vec::new(); + for r in realm.unhandled_rejections() { + let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored }; + let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag); + let mut o = json!({ + "message": e.message, + "messageOrigin": if e.authored { "script" } else { "built-in" }, + "line": e.line, + "column": e.column, + }); + if let (Some(file), Some(map)) = (file, o.as_object_mut()) { + map.insert("file".into(), json!(&*file)); + } + out.push(o); + } + out +} /// The report of a run that failed; `file` is the included file the error is in. fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { @@ -2389,6 +2430,18 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: if report["ok"] == false { each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); } + if let Some(rejections) = report["unhandledRejections"].as_array() { + for r in rejections { + let mut placed = r.clone(); + placed["message"] = json!(format!("{UNHANDLED_REJECTION}: {}", r["message"].as_str().unwrap_or_default())); + each_line(&error_text(&host.name, &placed), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + let more = report["unhandledRejectionCount"].as_u64().unwrap_or(0).saturating_sub(rejections.len() as u64); + if more > 0 { + let text = format!("{}: {more} more {UNHANDLED_REJECTIONS}", host.name); + each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + } let timing = clock().is_some(); let ms = millis(host.run_nanos.get()); let slow = slowest(&host.commands.borrow()); diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index cc6756c332..3de6757888 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -689,3 +689,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() { } let _ = std::fs::remove_dir_all(base); } + +#[test] +fn a_js_script_has_promise_and_a_jsx_script_does_not() { + let base = folder("promise-realm"); + let main = base.join("main/main.js"); + write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);"); + let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["function", 1, 2])); + assert!(r.get("unhandledRejections").is_none(), "{r}"); + let r = run(&base, "vc.log(typeof Promise);").unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() { + let base = folder("promise-engine"); + let jsx = base.join("main/a.jsx"); + let js = base.join("main/b.js"); + let mut s = Session::new(); + let mut go = |path: &Path, text: &str| { + write(path, text); + s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone() + }; + assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"])); + assert_eq!( + go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"), + json!([1, "function", 2]) + ); + assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() { + let base = folder("promise-rejections"); + write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n"); + let main = base.join("main/main.js"); + write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n"); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + let got: Vec<(String, u64, Option)> = r["unhandledRejections"] + .as_array() + .unwrap() + .iter() + .map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc")))) + .collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}"); + assert_eq!(r["unhandledRejectionCount"], 2); + let c = s.execute("script.console", &json!({})).unwrap(); + let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect(); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}"); + assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..1be49acef9 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -15,6 +15,7 @@ mod global; mod json; mod math; mod object; +pub(crate) mod promise; use std::rc::Rc; @@ -145,6 +146,9 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + promise::install(interp)?; + } Ok(()) } diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs new file mode 100644 index 0000000000..d960fac60b --- /dev/null +++ b/crates/js/src/builtins/promise.rs @@ -0,0 +1,1109 @@ +//! `Promise` (ECMA-262 11th edition, section 25.6, ) +//! and the run's queue of promise jobs (section 8.4), in realms with [`crate::Options::es2015`]: +//! the constructor, `then`, `catch` and `finally`, and `Promise.resolve`, `reject`, `all`, +//! `allSettled` and `race`. `Promise.any` (ES2021) is not provided. +//! +//! A job is queued when a promise settles with reactions waiting, when `then` is called on a +//! settled promise, and when a promise is resolved with a thenable. Jobs run one at a time, in the +//! order they were queued, once the script's own code has ended and no other code runs: at the end +//! of [`crate::Realm::run`], and in the slices [`crate::Realm::advance`] runs after the script's +//! code, before it reports the run done. A job that a job queues joins the end of the queue. A job +//! takes a unit of fuel, its callback runs on the run's fuel, heap and frame limits, and a callback +//! written in JavaScript runs as the script's own code, so a slice can pause inside it. Each queued +//! job counts [`JOB_BYTES`] toward the heap limit, and more than [`MAX_JOBS`] queued jobs end the +//! run with [`LimitKind::Jobs`]. A run that ends with an error or a limit, or is ended, drops the +//! jobs still queued. A promise that is still pending when the queue is empty stays pending. +//! +//! A promise rejected while it has no handler is noted (HostPromiseRejectionTracker, section +//! 25.6.1.9); one that still has none when the run ends successfully is reported by +//! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. +//! +//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object +//! whose `length` is a whole number by index, and a string by code point; other values reject the +//! promise they return with a `TypeError`. The statics need a constructor as `this`, and the +//! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` +//! are not read. + +use std::collections::VecDeque; +use std::rc::Rc; + +use super::{arg, constructor, create_at, method, native, new_array}; +use crate::LimitKind; +use crate::bytecode::Code; +use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; + +/// Where a promise was rejected: the code and the instruction. +pub(crate) type Site = (Rc, usize); + +/// The estimated bytes of a promise's state, without its reactions. +pub(crate) const PROMISE_BYTES: usize = 64; +/// The estimated bytes of a reaction a pending promise holds. +pub(crate) const REACTION_BYTES: usize = 48; +/// The estimated bytes of the state a promise operation's functions share. +pub(crate) const RECORD_BYTES: usize = 48; +/// The estimated bytes of a queued job. +pub(crate) const JOB_BYTES: usize = 64; +/// The most jobs the queue may hold at once. +pub(crate) const MAX_JOBS: usize = 1 << 20; +/// The most unhandled rejections a run reports one by one. +pub(crate) const MAX_REPORTED: usize = 20; +/// The most characters of a rejection's reason a report gives. +const MAX_REASON_CHARS: usize = 500; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum State { + Pending, + Fulfilled, + Rejected, +} + +/// A `then` waiting for a pending promise: the handlers (`undefined` when not callable) and the +/// promise `then` returned. +#[derive(Clone)] +pub(crate) struct Reaction { + on_fulfilled: Value, + on_rejected: Value, + derived: ObjId, +} + +/// A promise's internal slots (section 25.6.6), with where it was rejected. +#[derive(Clone)] +pub(crate) struct PromiseData { + pub(crate) state: State, + pub(crate) result: Value, + reactions: Vec, + pub(crate) handled: bool, + pub(crate) site: Option, +} + +impl PromiseData { + fn new() -> Self { + Self { state: State::Pending, result: Value::Undefined, reactions: Vec::new(), handled: false, site: None } + } + + /// The values the promise holds, for the collector. + pub(crate) fn values(&self) -> Vec { + let mut out = vec![self.result.clone()]; + for r in &self.reactions { + out.extend([r.on_fulfilled.clone(), r.on_rejected.clone(), Value::Object(r.derived)]); + } + out + } + + /// The estimated bytes of the state, beyond the object. + pub(crate) fn bytes(&self) -> usize { + PROMISE_BYTES + REACTION_BYTES * self.reactions.len() + } +} + +/// The state the functions a promise operation makes share. +#[derive(Clone)] +pub(crate) enum Record { + /// A promise's resolve and reject functions (section 25.6.1.3): the first call wins. + Resolving { promise: ObjId, done: bool }, + /// `Promise.all` and `allSettled`: the result's resolving record, the values so far and the + /// inputs not yet settled. + Combinator { resolving: ObjId, values: ObjId, remaining: u64 }, + /// The functions for one input of `Promise.all` or `allSettled`. + Element { combinator: ObjId, index: u32, called: bool }, + /// `finally`'s callback. + Finally { on_finally: Value }, + /// A value `finally` passes on or throws again. + Thunk { value: Value }, +} + +impl Record { + /// The values the record holds, for the collector. + pub(crate) fn values(&self) -> Vec { + match self { + Record::Resolving { promise, .. } => vec![Value::Object(*promise)], + Record::Combinator { resolving, values, .. } => vec![Value::Object(*resolving), Value::Object(*values)], + Record::Element { combinator, .. } => vec![Value::Object(*combinator)], + Record::Finally { on_finally: v } | Record::Thunk { value: v } => vec![v.clone()], + } + } +} + +/// A queued job. +enum Job { + /// PromiseReactionJob (section 25.6.2.1): calls `handler` with `argument` and settles + /// `derived` with the result, or passes `argument` on when `handler` is not callable. + Reaction { handler: Value, argument: Value, reject: bool, derived: ObjId, site: Option }, + /// PromiseResolveThenableJob (section 25.6.2.2): calls `then` on `thenable` with new + /// resolving functions for `promise`. + Thenable { promise: ObjId, thenable: Value, then: Value }, +} + +/// What happens when the running job's call ends. +enum Then { + /// The result resolves this promise, and an exception rejects it. + Settle(ObjId), + /// An exception rejects through this resolving record. + Reject(ObjId), +} + +/// The built-in functions a promise operation's functions call, with their record. +#[derive(Clone, Copy)] +enum Kind { + Resolve, + Reject, + AllElement, + SettledFulfilled, + SettledRejected, + ThenFinally, + CatchFinally, + ValueThunk, + Thrower, +} + +const KINDS: [(Kind, NativeFn); 9] = [ + (Kind::Resolve, resolve_function), + (Kind::Reject, reject_function), + (Kind::AllElement, all_element), + (Kind::SettledFulfilled, settled_fulfilled), + (Kind::SettledRejected, settled_rejected), + (Kind::ThenFinally, then_finally), + (Kind::CatchFinally, catch_finally), + (Kind::ValueThunk, value_thunk), + (Kind::Thrower, thrower), +]; + +/// `Promise`'s objects and the run's job queue. +pub(crate) struct Promises { + proto: Option, + ctor: Option, + /// The built-ins for each [`Kind`], in [`KINDS`] order. + natives: Vec, + queue: VecDeque, + running: Option, + /// The script's completion value while the jobs after it run. + completion: Option, + /// The script's own code has ended and the queue's jobs are running. + pub(crate) draining: bool, + /// Promises rejected in this run while they had no handler. + rejected: Vec, + /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). + pub(crate) max_jobs: usize, +} + +impl Default for Promises { + fn default() -> Self { + Self { + proto: None, + ctor: None, + natives: Vec::new(), + queue: VecDeque::new(), + running: None, + completion: None, + draining: false, + rejected: Vec::new(), + max_jobs: MAX_JOBS, + } + } +} + +impl Promises { + /// Adds what the queue and the promise objects hold to the collector's roots. + pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { + 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), + None => {} + } + for job in &self.queue { + match job { + Job::Reaction { handler, argument, derived, site, .. } => { + roots.values.extend([handler, argument]); + roots.objects.push(*derived); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Job::Thenable { promise, thenable, then } => { + roots.values.extend([thenable, then]); + roots.objects.push(*promise); + } + } + } + } + + /// The estimated bytes the queued jobs hold. + pub(crate) fn queue_bytes(&self) -> usize { + JOB_BYTES.saturating_mul(self.queue.len()) + } + + /// Drops the noted rejections whose promise has a handler now. + pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) { + self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled)); + } +} + +/// Creates `Promise`, its prototype methods and its statics. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + interp.promises.proto = Some(proto); + let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; + interp.promises.ctor = Some(ctor); + constructor(interp, "Promise", ctor, proto)?; + method(interp, proto, "then", promise_then, 2)?; + method(interp, proto, "catch", promise_catch, 1)?; + method(interp, proto, "finally", promise_finally, 1)?; + method(interp, ctor, "resolve", promise_resolve_static, 1)?; + method(interp, ctor, "reject", promise_reject_static, 1)?; + method(interp, ctor, "all", promise_all, 1)?; + method(interp, ctor, "allSettled", promise_all_settled, 1)?; + method(interp, ctor, "race", promise_race, 1)?; + for (_, f) in KINDS { + let n = native(interp, "", f, 1, NativeKind::Plain, false)?; + interp.promises.natives.push(n); + } + Ok(()) +} + +/// Turns on [`crate::Options::es2015`] in a realm made without it and creates `Promise` there, +/// replacing a global `Promise` an earlier script defined. A realm that has the built-in `Promise` +/// already keeps it. When `Promise` cannot be created, every later run of the realm ends with an +/// internal error, as for a realm whose built-ins could not be installed. +pub(crate) fn add_to(interp: &mut Interp) { + interp.options.es2015 = true; + if interp.promises.ctor.is_some() || interp.install_error.is_some() { + return; + } + if let Err(e) = install(interp) { + let reason = match e { + Abrupt::Throw(v) => interp.describe(&v), + Abrupt::Limit(kind) => format!("limit reached: {kind:?}"), + Abrupt::Internal(message) => message, + }; + interp.install_error = Some(format!("the built-ins could not be installed: {reason}")); + } +} + +// ---- helpers ---- + +/// Runs `f`, then drops the temporary roots it added. +fn scoped(interp: &mut Interp, f: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let mark = interp.temp_roots.len(); + let r = f(interp); + interp.temp_roots.truncate(mark); + r +} + +fn root(interp: &mut Interp, v: &Value) { + interp.temp_roots.push(v.clone()); +} + +/// An exception that a promise operation turns into a rejection: it is no longer propagating, and +/// the place it was thrown at, when known, is the rejection's. +fn caught(interp: &mut Interp) -> Option { + interp.passing = Value::Undefined; + interp.thrown_mark = None; + interp.throw_site.take() +} + +/// The instruction the innermost script frame is running. +fn here(interp: &Interp) -> Option { + interp.frames.last().map(|f| (f.code.clone(), f.pc.saturating_sub(1))) +} + +/// The value an error of type `t` with `message` is. +fn error_value(interp: &mut Interp, t: ErrorType, message: &str) -> Value { + match interp.throw(t, message) { + Abrupt::Throw(v) => v, + _ => Value::Undefined, + } +} + +fn promise_data(interp: &mut Interp, p: ObjId) -> JsResult<&mut PromiseData> { + match interp.heap.object_mut(p).map(|o| &mut o.class) { + Some(Class::Promise(d)) => Ok(d), + _ => Err(Abrupt::Internal("a promise operation lost its promise".into())), + } +} + +fn record<'a>(interp: &'a mut Interp, r: &Value) -> JsResult<&'a mut Record> { + match r.as_object().and_then(|o| interp.heap.object_mut(o)).map(|o| &mut o.class) { + Some(Class::PromiseRecord(rec)) => Ok(rec), + _ => Err(Abrupt::Internal("a promise function lost its record".into())), + } +} + +fn is_promise(interp: &Interp, v: &Value) -> bool { + v.as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Promise(_))) +} + +/// `this` for a `Promise.prototype` method that needs a promise. +fn this_promise(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if is_promise(interp, this) => Ok(o), + _ => Err(interp.type_error(&format!("Promise.prototype.{name} was called on a value that is not a promise"))), + } +} + +/// Invoke (section 7.3.18): calls `v[name]` with `v` as `this`. +fn invoke(interp: &mut Interp, v: &Value, name: &str, args: &[Value]) -> JsResult { + let f = interp.get_value(v, &key(name))?; + if !interp.is_callable(&f) { + return Err(interp.type_error(&format!("{name} is not a function"))); + } + interp.call(&f, v, args) +} + +/// A new pending promise. +fn new_promise(interp: &mut Interp) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + PROMISE_BYTES)?; + let proto = interp.promises.proto; + let o = interp.heap.alloc_object(Object::new(Class::Promise(Box::new(PromiseData::new())), proto)); + interp.heap.bytes = interp.heap.bytes.saturating_add(PROMISE_BYTES); + Ok(o) +} + +/// A new record. The values it holds must be rooted. +fn new_record(interp: &mut Interp, rec: Record) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + RECORD_BYTES)?; + let o = interp.heap.alloc_object(Object::new(Class::PromiseRecord(Box::new(rec)), None)); + interp.heap.bytes = interp.heap.bytes.saturating_add(RECORD_BYTES); + Ok(o) +} + +/// A function that calls the built-in for `kind` with `rec` before its own arguments. `rec` must +/// be rooted. +fn record_function(interp: &mut Interp, kind: Kind, rec: ObjId, length: u32) -> JsResult { + let Some(&target) = interp.promises.natives.get(kind as usize) else { return Err(Abrupt::Internal("Promise is not installed".into())) }; + interp.reserve_heap(OBJECT_BYTES + PROP_BYTES + BOUND_ARG_BYTES + 16)?; + let proto = interp.intrinsics.function_proto; + let args: Rc<[Value]> = Rc::from([Value::Object(rec)]); + let f = interp.heap.alloc_object(Object::new(Class::Function(Func::Bound { target, this: Value::Undefined, args }), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES); + interp.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + Ok(Value::Object(f)) +} + +/// CreateResolvingFunctions (section 25.6.1.3): the shared record, the resolve function and the +/// reject function. `promise` must be rooted. +fn resolving_functions(interp: &mut Interp, promise: ObjId) -> JsResult<(ObjId, Value, Value)> { + scoped(interp, |interp| { + let rec = new_record(interp, Record::Resolving { promise, done: false })?; + root(interp, &Value::Object(rec)); + let resolve = record_function(interp, Kind::Resolve, rec, 1)?; + root(interp, &resolve); + let reject = record_function(interp, Kind::Reject, rec, 1)?; + Ok((rec, resolve, reject)) + }) +} + +/// Checks that `n` more jobs fit in the queue and in the heap. Everything the caller still needs +/// must be reachable from the roots. +fn reserve_jobs(interp: &mut Interp, n: usize) -> JsResult<()> { + if interp.promises.queue.len().saturating_add(n) > interp.promises.max_jobs { + return Err(Abrupt::Limit(LimitKind::Jobs)); + } + interp.reserve_heap(JOB_BYTES.saturating_mul(n)) +} + +/// Queues a job [`reserve_jobs`] made room for. +fn push_job(interp: &mut Interp, job: Job) { + interp.heap.bytes = interp.heap.bytes.saturating_add(JOB_BYTES); + interp.promises.queue.push_back(job); +} + +/// Settles pending promise `p` (FulfillPromise and RejectPromise, sections 25.6.1.4 and 25.6.1.7) +/// and queues a job for each reaction. `p` and `value` must be rooted. +fn settle(interp: &mut Interp, p: ObjId, fulfilled: bool, value: Value, site: Option) -> JsResult<()> { + let waiting = promise_data(interp, p)?.reactions.len(); + reserve_jobs(interp, waiting)?; + let data = promise_data(interp, p)?; + if data.state != State::Pending { + return Ok(()); + } + data.state = if fulfilled { State::Fulfilled } else { State::Rejected }; + data.result = value.clone(); + if !fulfilled { + data.site.clone_from(&site); + } + let reactions = std::mem::take(&mut data.reactions); + let handled = data.handled; + interp.heap.bytes = interp.heap.bytes.saturating_sub(REACTION_BYTES.saturating_mul(reactions.len())); + for r in reactions { + let handler = if fulfilled { r.on_fulfilled } else { r.on_rejected }; + push_job(interp, Job::Reaction { handler, argument: value.clone(), reject: !fulfilled, derived: r.derived, site: site.clone() }); + } + if !fulfilled && !handled { + interp.promises.rejected.push(p); + } + Ok(()) +} + +fn reject_promise(interp: &mut Interp, p: ObjId, reason: Value, site: Option) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &reason); + settle(interp, p, false, reason, site) + }) +} + +/// A resolve function's steps after its first-call check (section 25.6.1.3.2): `resolution` +/// fulfills `p`, unless it is `p` itself (a `TypeError` rejects it) or an object whose `then` is +/// callable (a job adopts its state), and an exception reading `then` rejects it. +fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &resolution); + let Value::Object(o) = resolution else { return settle(interp, p, true, resolution, None) }; + if o == p { + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + let site = here(interp); + return settle(interp, p, false, e, site); + } + let then = match interp.get_from(o, &key("then"), &resolution) { + Ok(t) => t, + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + return settle(interp, p, false, e, site); + } + Err(e) => return Err(e), + }; + if !interp.is_callable(&then) { + return settle(interp, p, true, resolution, None); + } + root(interp, &then); + reserve_jobs(interp, 1)?; + push_job(interp, Job::Thenable { promise: p, thenable: resolution, then }); + Ok(()) + }) +} + +/// The resolve function of the resolving record `rec`. +fn resolve_through(interp: &mut Interp, rec: ObjId, value: Value) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + resolve_promise(interp, p, value) +} + +/// The reject function of the resolving record `rec`. +fn reject_through(interp: &mut Interp, rec: ObjId, reason: Value, site: Option) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + reject_promise(interp, p, reason, site) +} + +/// PerformPromiseThen (section 25.6.5.4.1) with `derived` as the result capability's promise. +/// Every value must be rooted. +fn perform_then(interp: &mut Interp, p: ObjId, on_fulfilled: Value, on_rejected: Value, derived: ObjId) -> JsResult<()> { + let on_fulfilled = if interp.is_callable(&on_fulfilled) { on_fulfilled } else { Value::Undefined }; + let on_rejected = if interp.is_callable(&on_rejected) { on_rejected } else { Value::Undefined }; + let state = promise_data(interp, p)?.state; + if state == State::Pending { + interp.reserve_heap(REACTION_BYTES)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(REACTION_BYTES); + } else { + reserve_jobs(interp, 1)?; + } + let data = promise_data(interp, p)?; + data.handled = true; + match data.state { + State::Pending => { + data.reactions.push(Reaction { on_fulfilled, on_rejected, derived }); + } + State::Fulfilled => { + let argument = data.result.clone(); + push_job(interp, Job::Reaction { handler: on_fulfilled, argument, reject: false, derived, site: None }); + } + State::Rejected => { + let (argument, site) = (data.result.clone(), data.site.clone()); + push_job(interp, Job::Reaction { handler: on_rejected, argument, reject: true, derived, site }); + } + } + Ok(()) +} + +/// PromiseResolve (section 25.6.4.5.1) with `c` as the constructor: `x` when it is a promise whose +/// `constructor` is `c`, otherwise a new promise resolved with `x`. +fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &x); + if let Value::Object(o) = x + && is_promise(interp, &x) + { + let ctor = interp.get_from(o, &key("constructor"), &x)?; + if crate::interp::same_value(&ctor, c) { + return Ok(x); + } + } + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + resolve_promise(interp, p, x)?; + Ok(Value::Object(p)) + }) +} + +// ---- the job queue ---- + +impl Interp { + /// A run begun with [`crate::Realm::start`] is going: its script's code or the jobs after it. + pub(crate) fn running(&self) -> bool { + !self.frames.is_empty() || self.promises.draining + } + + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's + /// code ended with `completion`, which this gives back. + pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { + self.promises.completion = Some(completion); + loop { + if !self.frames.is_empty() { + let r = self.execute(); + self.job_returned(r)?; + continue; + } + let Some(job) = self.promises.queue.pop_front() else { break }; + self.start_job(job)?; + } + Ok(self.promises.completion.take().unwrap_or(Value::Undefined)) + } + + /// [`Interp::execute_slice`] for a run begun with [`crate::Realm::start`]: runs the script's + /// code and then the queued jobs, and gives `Some` with the script's completion value once the + /// code has ended and the queue is empty. + pub(crate) fn execute_run_slice(&mut self, pause_at: u64) -> JsResult> { + loop { + if self.frames.is_empty() { + let Some(job) = self.promises.queue.pop_front() else { + self.promises.draining = false; + return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined))); + }; + self.start_job(job)?; + if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + return Ok(None); + } + continue; + } + match self.execute_slice(pause_at) { + Ok(None) => return Ok(None), + Ok(Some(v)) if self.promises.running.is_none() => { + // The script's own code ended. + if self.promises.queue.is_empty() { + return Ok(Some(v)); + } + self.promises.completion = Some(v); + self.promises.draining = true; + } + Ok(Some(v)) => self.finish_job(Ok(v))?, + Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?, + Err(e) => return Err(e), + } + if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + return Ok(None); + } + } + } + + fn job_returned(&mut self, r: JsResult) -> JsResult<()> { + match r { + Ok(v) => self.finish_job(Ok(v)), + Err(Abrupt::Throw(v)) => self.finish_job(Err(v)), + Err(e) => Err(e), + } + } + + /// Starts a job: a native callback runs to its end here, and a callback written in JavaScript + /// gets a frame the caller runs. + fn start_job(&mut self, job: Job) -> JsResult<()> { + self.heap.bytes = self.heap.bytes.saturating_sub(JOB_BYTES); + self.use_fuel()?; + scoped(self, |interp| { + let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, derived, site } => { + if !interp.is_callable(&handler) { + return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; + } + root(interp, &Value::Object(derived)); + (handler, Value::Undefined, vec![argument], Then::Settle(derived)) + } + Job::Thenable { promise, thenable, then } => { + interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]); + let (rec, resolve, reject) = resolving_functions(interp, promise)?; + (then, thenable, vec![resolve, reject], Then::Reject(rec)) + } + }; + interp.temp_roots.push(f.clone()); + interp.temp_roots.push(this.clone()); + interp.temp_roots.extend(args.iter().cloned()); + interp.promises.running = Some(then); + match interp.start_call(f, this, args) { + Ok(Some(v)) => interp.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => interp.finish_job(Err(e)), + Err(e) => Err(e), + } + }) + } + + /// Ends the running job with its call's result or exception. + fn finish_job(&mut self, r: Result) -> JsResult<()> { + 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::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(rec), Err(e)) => scoped(self, |interp| { + root(interp, &Value::Object(rec)); + reject_through(interp, rec, e, site) + }), + } + } + + /// Drops the run's queued jobs and its state; with `keep_rejections` false, the rejections it + /// noted too. + pub(crate) fn end_jobs(&mut self, keep_rejections: bool) { + let queued = self.promises.queue_bytes(); + self.heap.bytes = self.heap.bytes.saturating_sub(queued); + self.promises.queue.clear(); + self.promises.running = None; + self.promises.completion = None; + self.promises.draining = false; + if !keep_rejections { + self.promises.rejected.clear(); + } + } + + /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of + /// them described, and how many there are; the run's notes are cleared. + 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 count = 0; + for p in rejected { + let (reason, site) = match self.heap.object(p).map(|o| &o.class) { + Some(Class::Promise(d)) if !d.handled && d.state == State::Rejected => (d.result.clone(), d.site.clone()), + _ => continue, + }; + count += 1; + if out.len() >= MAX_REPORTED { + continue; + } + let mut message = self.describe(&reason); + if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) { + message.truncate(cut); + message.push('…'); + } + let authored = 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 }); + } + (out, count) + } +} + +// ---- Promise ---- + +/// `new Promise(executor)` (section 25.6.3.1). Calling `Promise` without `new` is a `TypeError`. +fn promise_ctor(interp: &mut Interp, _: Value, args: &[Value], constructed: bool) -> JsResult { + if !constructed { + return Err(interp.type_error("Promise must be called with new")); + } + let executor = arg(args, 0); + if !interp.is_callable(&executor) { + return Err(interp.type_error("the Promise executor is not a function")); + } + scoped(interp, |interp| { + root(interp, &executor); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match interp.call(&executor, &Value::Undefined, &[resolve, reject]) { + Ok(_) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// A promise's resolve function (section 25.6.1.3.2). +fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a resolve function lost its record".into()))?; + resolve_through(interp, rec, arg(args, 1))?; + Ok(Value::Undefined) +} + +/// 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); + reject_through(interp, rec, arg(args, 1), site)?; + Ok(Value::Undefined) +} + +/// `Promise.prototype.then` (section 25.6.5.4). +fn promise_then(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let p = this_promise(interp, &this, "then")?; + scoped(interp, |interp| { + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + perform_then(interp, p, arg(args, 0), arg(args, 1), derived)?; + Ok(Value::Object(derived)) + }) +} + +/// `Promise.prototype.catch` (section 25.6.5.1). +fn promise_catch(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + invoke(interp, &this, "then", &[Value::Undefined, arg(args, 0)]) +} + +/// `Promise.prototype.finally` (section 25.6.5.3). +fn promise_finally(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !matches!(this, Value::Object(_)) { + return Err(interp.type_error("Promise.prototype.finally was called on a value that is not an object")); + } + let on_finally = arg(args, 0); + if !interp.is_callable(&on_finally) { + return invoke(interp, &this, "then", &[on_finally.clone(), on_finally]); + } + scoped(interp, |interp| { + let rec = new_record(interp, Record::Finally { on_finally })?; + root(interp, &Value::Object(rec)); + let then_finally = record_function(interp, Kind::ThenFinally, rec, 1)?; + root(interp, &then_finally); + let catch_finally = record_function(interp, Kind::CatchFinally, rec, 1)?; + root(interp, &catch_finally); + invoke(interp, &this, "then", &[then_finally, catch_finally]) + }) +} + +/// Then Finally and Catch Finally (sections 25.6.5.3.1 and 25.6.5.3.2): calls the callback, then +/// passes `value` on, or throws it again when `throws`, once the callback's result settles. +fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult { + let rec_value = arg(args, 0); + let value = arg(args, 1); + let Record::Finally { on_finally } = record(interp, &rec_value)? else { return Err(Abrupt::Internal("not a finally record".into())) }; + let on_finally = on_finally.clone(); + let result = interp.call(&on_finally, &Value::Undefined, &[])?; + scoped(interp, |interp| { + root(interp, &value); + let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object); + let promise = promise_resolve(interp, &ctor, result)?; + root(interp, &promise); + let rec = new_record(interp, Record::Thunk { value })?; + root(interp, &Value::Object(rec)); + let thunk = record_function(interp, if throws { Kind::Thrower } else { Kind::ValueThunk }, rec, 0)?; + root(interp, &thunk); + invoke(interp, &promise, "then", &[thunk]) + }) +} + +fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, false) +} + +fn catch_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, true) +} + +fn thunk_value(interp: &mut Interp, args: &[Value]) -> JsResult { + match record(interp, &arg(args, 0))? { + Record::Thunk { value } => Ok(value.clone()), + _ => Err(Abrupt::Internal("not a thunk record".into())), + } +} + +fn value_thunk(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + thunk_value(interp, args) +} + +fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Err(Abrupt::Throw(thunk_value(interp, args)?)) +} + +/// `v` is a constructor: a function written in JavaScript, a built-in constructor, or a bound +/// function whose target is one. +fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { + let mut v = v.clone(); + loop { + let func = match v.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::Function(f)) => f.clone(), + _ => return Ok(false), + }; + match func { + Func::Closure { .. } => return Ok(true), + Func::Native { constructor, .. } => return Ok(constructor), + Func::Bound { target, .. } => { + interp.use_fuel()?; + v = Value::Object(target); + } + _ => return Ok(false), + } + } +} + +/// The `this` value of a static method, which must be a constructor. +fn this_constructor(interp: &mut Interp, this: &Value, name: &str) -> JsResult<()> { + if is_constructor(interp, this)? { + return Ok(()); + } + Err(interp.type_error(&format!("Promise.{name} was called on a value that is not a constructor"))) +} + +/// `Promise.resolve` (section 25.6.4.6). +fn promise_resolve_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "resolve")?; + promise_resolve(interp, &this, arg(args, 0)) +} + +/// `Promise.reject` (section 25.6.4.5). +fn promise_reject_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "reject")?; + scoped(interp, |interp| { + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let site = here(interp); + reject_promise(interp, p, arg(args, 0), site)?; + Ok(Value::Object(p)) + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Combine { + All, + AllSettled, + Race, +} + +impl Combine { + fn name(self) -> &'static str { + match self { + Combine::All => "all", + Combine::AllSettled => "allSettled", + Combine::Race => "race", + } + } +} + +fn promise_all(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::All) +} + +fn promise_all_settled(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::AllSettled) +} + +fn promise_race(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::Race) +} + +/// `Promise.all`, `allSettled` and `race` (sections 25.6.4.1, 25.6.4.2 and 25.6.4.4): an exception +/// on the way rejects the promise they return (IfAbruptRejectPromise). +fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsResult { + this_constructor(interp, &this, how.name())?; + scoped(interp, |interp| { + root(interp, &input); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match combine_inputs(interp, &this, &input, how, rec, &resolve, &reject) { + Ok(()) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. +enum Inputs { + Indexed { object: ObjId, length: f64 }, + CodePoints(Vec), +} + +impl Inputs { + fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { + match input { + Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { + Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { + Ok(Inputs::Indexed { object: *o, length }) + } + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + }, + Value::String(s) => Ok(Inputs::CodePoints(s.flat().to_vec())), + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + } + } + + /// The input at `index`, which counts code units for a string; `None` past the end. + fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { + match self { + Inputs::Indexed { object, length } => { + if *index >= *length { + return Ok(None); + } + let v = super::get_at(interp, *object, *index)?; + *index += 1.0; + Ok(Some(v)) + } + Inputs::CodePoints(units) => { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = *index as usize; + let Some(&first) = units.get(i) else { return Ok(None) }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let n = if pair { 2 } else { 1 }; + let piece = units.get(i..i + n).unwrap_or_default().to_vec(); + *index += n as f64; + let bytes = crate::heap::string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Some(Value::String(crate::value::Str::from_units(piece)))) + } + } + } +} + +fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { + let resolve_fn = interp.get_value(this, &key("resolve"))?; + if !interp.is_callable(&resolve_fn) { + return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); + } + root(interp, &resolve_fn); + let inputs = Inputs::new(interp, input, how)?; + let combinator = if how == Combine::Race { + None + } else { + let values = new_array(interp, 0)?; + root(interp, &Value::Object(values)); + let c = new_record(interp, Record::Combinator { resolving: rec, values, remaining: 1 })?; + root(interp, &Value::Object(c)); + Some((c, values)) + }; + let mut position = 0.0; + let mut index: u32 = 0; + loop { + interp.use_fuel()?; + let mark = interp.temp_roots.len(); + let Some(next) = inputs.get(interp, &mut position)? else { break }; + root(interp, &next); + let next_promise = interp.call(&resolve_fn, this, &[next])?; + root(interp, &next_promise); + match combinator { + None => { + invoke(interp, &next_promise, "then", &[resolve.clone(), reject.clone()])?; + } + Some((c, values)) => { + create_at(interp, values, f64::from(index), Value::Undefined)?; + let el = new_record(interp, Record::Element { combinator: c, index, called: false })?; + root(interp, &Value::Object(el)); + let (on_fulfilled, on_rejected) = if how == Combine::All { + (record_function(interp, Kind::AllElement, el, 1)?, reject.clone()) + } else { + let f = record_function(interp, Kind::SettledFulfilled, el, 1)?; + root(interp, &f); + (f, record_function(interp, Kind::SettledRejected, el, 1)?) + }; + interp.temp_roots.extend([on_fulfilled.clone(), on_rejected.clone()]); + if let Record::Combinator { remaining, .. } = record(interp, &Value::Object(c))? { + *remaining += 1; + } + invoke(interp, &next_promise, "then", &[on_fulfilled, on_rejected])?; + } + } + interp.temp_roots.truncate(mark); + index = index.checked_add(1).filter(|&i| i < u32::MAX).ok_or_else(|| interp.throw(ErrorType::Range, "too many promises to combine"))?; + } + if let Some((c, _)) = combinator { + element_done(interp, c)?; + } + Ok(()) +} + +/// Counts one more settled input of a `Promise.all` or `allSettled`; after the last one, resolves +/// the result with the values. +fn element_done(interp: &mut Interp, c: ObjId) -> JsResult<()> { + let Record::Combinator { resolving, values, remaining } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + *remaining = remaining.saturating_sub(1); + if *remaining > 0 { + return Ok(()); + } + let (resolving, values) = (*resolving, *values); + scoped(interp, |interp| { + root(interp, &Value::Object(c)); + resolve_through(interp, resolving, Value::Object(values)) + }) +} + +/// Stores `value` as one input's result (the first call only) and counts the input settled. +fn element_settled(interp: &mut Interp, args: &[Value], make: impl FnOnce(&mut Interp, Value) -> JsResult) -> JsResult { + let rec_value = arg(args, 0); + let Record::Element { combinator, index, called } = record(interp, &rec_value)? else { + return Err(Abrupt::Internal("not an element record".into())); + }; + if *called { + return Ok(Value::Undefined); + } + *called = true; + let (c, index) = (*combinator, *index); + let Record::Combinator { values, .. } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + let values = *values; + let v = make(interp, arg(args, 1))?; + scoped(interp, |interp| { + root(interp, &v); + super::put_at(interp, values, f64::from(index), v.clone())?; + element_done(interp, c) + })?; + Ok(Value::Undefined) +} + +/// `Promise.all` Resolve Element Functions (section 25.6.4.1.2). +fn all_element(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |_, v| Ok(v)) +} + +/// An `allSettled` result object: `{ status, value }` or `{ status, reason }`. +fn settled_object(interp: &mut Interp, fulfilled: bool, v: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &v); + interp.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES + 64)?; + let o = interp.new_object(); + root(interp, &Value::Object(o)); + let (status, name) = if fulfilled { ("fulfilled", "value") } else { ("rejected", "reason") }; + interp.define(o, key("status"), Prop::Data { value: Value::str(status), flags: OPEN })?; + interp.define(o, key(name), Prop::Data { value: v, flags: OPEN })?; + Ok(Value::Object(o)) + }) +} + +/// `Promise.allSettled` Resolve Element Functions (section 25.6.4.2.2). +fn settled_fulfilled(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, true, v)) +} + +/// `Promise.allSettled` Reject Element Functions (section 25.6.4.2.3). +fn settled_rejected(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, false, v)) +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..f880e7a05b 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,10 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A promise (ECMA-262 11th edition, section 25.6) and its state. + Promise(Box), + /// The state that the functions a promise operation makes share; scripts never see it. + PromiseRecord(Box), } /// What an XML value is. @@ -309,7 +313,8 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) => "Object", + Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", Class::Ordinary | Class::ForIn(_) => "Object", @@ -680,6 +685,21 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Promise(p) => { + for v in p.values() { + mark_value(&v, work, strings); + } + if let Some((code, _)) = &p.site { + mark_code(code, strings); + } + extra = p.bytes(); + } + Class::PromiseRecord(r) => { + for v in r.values() { + mark_value(&v, work, strings); + } + extra = crate::builtins::promise::RECORD_BYTES; + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..45de3cbe92 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -310,6 +310,8 @@ pub(crate) struct Interp { pub(crate) error_mark: Option, /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. pub(crate) strict_writes: bool, + /// `Promise` and the run's promise job queue ([`crate::builtins::promise`]). + pub(crate) promises: crate::builtins::promise::Promises, } /// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's @@ -540,6 +542,7 @@ impl Interp { finally_sites: Vec::new(), error_mark: None, strict_writes: false, + promises: crate::builtins::promise::Promises::default(), }; crate::builtins::install(&mut interp); interp.fuel = limits.fuel; @@ -754,6 +757,7 @@ impl Interp { pub(crate) fn collect_garbage(&mut self) { self.drop_left_finally_marks(); self.drop_left_finally_sites(self.stack.len()); + self.promises.forget_handled(&self.heap); let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); @@ -775,11 +779,13 @@ impl Interp { roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); roots.envs.push(self.global_env); + self.promises.add_roots(&mut roots); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); - self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()); + let queued = self.promises.queue_bytes(); + self.heap.bytes = self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()).saturating_add(queued); } /// Runs frames until the boundary frame on top returns, and returns its value. @@ -2536,6 +2542,21 @@ impl Interp { r } + /// Starts a call to `f` with no frame running, for a promise job: a native or host function + /// runs now and gives `Some` with its result, and a function written in JavaScript gets a + /// boundary frame that the caller runs, and gives `None`. A host function called here cannot + /// wait for its result, since no script code is running; a function written in JavaScript + /// runs as the script's own code does. + pub(crate) fn start_call(&mut self, f: Value, this: Value, args: Vec) -> JsResult> { + self.reentry += 1; + let prepared = self.prepare_call(f, this, args); + self.reentry -= 1; + match prepared? { + Prepared::Done(v) => Ok(Some(v)), + Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None), + } + } + fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..5d07c64493 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -46,6 +46,13 @@ //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and //! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each //! node. +//! +//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section +//! 25.6, ): the constructor, `then`, +//! `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. The promise +//! jobs a script queues run in order once its code has ended, before its run ends, on the run's +//! limits; a promise still rejected with no handler at the end is reported by +//! [`Realm::unhandled_rejections`]. #![forbid(unsafe_code)] pub mod ast; @@ -83,7 +90,9 @@ pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; +pub use realm::{ + Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE, +}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -100,11 +109,14 @@ pub struct Options { pub max_source_units: usize, /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, + /// Give a realm the later editions' built-ins this engine has: `Promise` and its job queue. + /// Off, a realm has the ES5.1 built-ins only, as ExtendScript scripts expect. + pub es2015: bool, } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } } } @@ -209,6 +221,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod promise_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs new file mode 100644 index 0000000000..96e93764ff --- /dev/null +++ b/crates/js/src/promise_tests.rs @@ -0,0 +1,223 @@ +//! `Promise` and the promise job queue in realms with [`Options::es2015`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran. +fn log(src: &str) -> String { + let mut r = realm(); + if let Err(e) = r.run(&format!("var log = [];\n{src}")) { + panic!("{src}\n{e:?}"); + } + match r.run("log.join(' ')") { + Ok(JsValue::String(s)) => s, + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn an_extendscript_realm_has_no_promise() { + assert_eq!(Realm::new().run("typeof Promise").unwrap(), JsValue::String("undefined".into())); + assert_eq!(string("typeof Promise"), "function"); +} + +#[test] +fn then_callbacks_run_after_the_scripts_code_in_order() { + let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ + new Promise(function (res) { log.push('executor'); res(2); }).then(function (v) { log.push('b' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "executor sync a1 b2"); +} + +#[test] +fn jobs_run_first_in_first_out_and_a_jobs_jobs_join_the_end() { + let src = "var p = Promise.resolve();\n\ + p.then(function () { log.push(1); Promise.resolve().then(function () { log.push(4); }); });\n\ + p.then(function () { log.push(2); });\n\ + p.then(function () { log.push(3); });"; + assert_eq!(log(src), "1 2 3 4"); +} + +#[test] +fn a_thenable_is_adopted_in_a_later_job() { + let src = "var thenable = { then: function (res) { log.push('then'); res(7); } };\n\ + Promise.resolve(thenable).then(function (v) { log.push('got' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "sync then got7"); + let rejecting = "var t = { then: function (res, rej) { rej('no'); res(1); } };\n\ + new Promise(function (res) { res(t); }).then(null, function (r) { log.push('rejected ' + r); });"; + assert_eq!(log(rejecting), "rejected no"); + let throwing = "var t = { then: function (res) { res(1); throw new Error('late'); } };\n\ + Promise.resolve(t).then(function (v) { log.push('kept ' + v); });"; + assert_eq!(log(throwing), "kept 1"); +} + +#[test] +fn a_promise_resolved_with_itself_rejects_with_a_type_error() { + let src = "var res; var p = new Promise(function (r) { res = r; }); res(p);\n\ + p.then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true"); +} + +#[test] +fn catch_finally_and_the_combinators_settle_as_the_specification_says() { + let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\ + Promise.resolve(5).finally(function () { log.push('finally'); return 9; }).then(function (v) { log.push('kept ' + v); });\n\ + Promise.all([1, Promise.resolve(2), { then: function (r) { r(3); } }]).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\ + Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\ + Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\ + Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\ + Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\ + Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });"; + let out = log(src); + for part in [ + "caught x", + "finally", + "kept 5", + "all 1,2,3", + "rejected:r fulfilled:4", + "race fast", + "chars 2", + "not a list true", + "no length true", + "bad length true", + ] { + assert!(out.contains(part), "{part} in {out}"); + } +} + +#[test] +fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { + let mut r = realm(); + for src in [ + "Promise(function () {})", + "new Promise(1)", + "Promise.prototype.then.call({}, null)", + "Promise.resolve.call(1, 2)", + "Promise.all.call(Math.max, [])", + ] { + match r.run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } + } +} + +#[test] +fn an_unhandled_rejection_is_reported_with_its_line() { + let mut r = realm(); + r.run("var a = 1;\nPromise.reject(new Error('lost'));\nnew Promise(function () {\n throw new TypeError('also');\n});\nPromise.reject(2).catch(function () {});") + .unwrap(); + let got: Vec<(String, u32)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.line)).collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2), ("TypeError: also".to_string(), 4)]); + assert_eq!(r.unhandled_rejection_count(), 2); + assert!(r.unhandled_rejections().iter().all(|j| j.authored)); +} + +#[test] +fn a_rejection_handled_in_a_later_job_is_not_reported() { + let mut r = realm(); + r.run("var p = Promise.reject(1); Promise.resolve().then(function () { p.catch(function () {}); });").unwrap(); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.unhandled_rejection_count(), 0); +} + +#[test] +fn a_run_that_fails_reports_no_rejections_and_drops_its_jobs() { + let mut r = realm(); + let e = r.run("var ran = false; Promise.reject(1); Promise.resolve().then(function () { ran = true; }); throw 'stop';").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Thrown, "stop")); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.run("ran").unwrap(), JsValue::Bool(false)); +} + +#[test] +fn an_endless_then_chain_is_stopped_by_fuel() { + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run("function again() { return Promise.resolve().then(again); } again();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + let e = r.run("var res; var p = new Promise(function (r) { res = r; }); function loop() { p.then(loop); } p.then(loop); res(1);").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert!(!r.is_running()); +} + +#[test] +fn each_job_takes_fuel() { + // `then` on a settled promise queues a job, and on a pending one it does not; the difference in + // fuel between 50 calls and none is the jobs' fuel. + let used = |start: &str, calls: usize| { + let mut r = realm(); + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + r.run(&format!("var p = {start};{}", "p.then();".repeat(calls))).unwrap(); + 1_000_000 - r.fuel_left() + }; + let settled = used("Promise.resolve()", 50) - used("Promise.resolve()", 0); + let pending = used("new Promise(function () {})", 50) - used("new Promise(function () {})", 0); + assert_eq!(settled - pending, 50); +} + +#[test] +fn more_jobs_than_the_queue_holds_end_the_run_with_a_clear_error() { + let mut r = realm(); + r.interp().promises.max_jobs = 100; + let e = r.run("var p = Promise.resolve(); for (var i = 0; i < 200; i++) p.then(function () {});").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Jobs)); + assert!(e.message.contains("more than 100 promise jobs"), "{}", e.message); + assert!(r.run("var q = Promise.resolve(); for (var i = 0; i < 50; i++) q.then(function () {}); 1").is_ok()); +} + +#[test] +fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.start("var t = 0; Promise.resolve().then(function () { for (var i = 0; i < 5000; i++) t += i; }); 'done'").unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 1, "{paused_in_jobs}"); + assert!(!r.is_running()); + assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0)); +} + +#[test] +fn an_ended_sliced_run_drops_its_jobs() { + let mut r = realm(); + r.start("var ran = 0; Promise.resolve().then(function () { for (;;) ran++; });").unwrap(); + let mut slices = 0; + while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining { + slices += 1; + assert!(slices < 1000); + } + assert!(r.is_running()); + r.end(); + assert!(!r.is_running()); + assert_eq!(r.interp().promises.queue_bytes(), 0); + assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into())); +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ee2cd364f8..5373a8194e 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -57,6 +57,23 @@ pub enum LimitKind { Unbroken, /// A host function ended the run ([`crate::HostError::Abort`]). Host, + /// More promise jobs were waiting to run than a run may queue. + Jobs, +} + +/// A promise the last run rejected that still had no rejection handler when the run ended +/// ([`Realm::unhandled_rejections`]). `line` and `column` are where it was rejected: the `throw`, +/// or the call to its reject function or `Promise.reject`; they are 0 when that is not known. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Rejection { + /// The reason, described as an uncaught exception's message is. + pub message: String, + pub line: u32, + pub column: u32, + /// The source tag of the code `line` and `column` are in ([`Realm::error_tag`]). + pub tag: u32, + /// `message` is text the script supplied ([`RunError::authored`]). + pub authored: bool, } /// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an @@ -169,6 +186,8 @@ pub struct Realm { /// before the first script, for a script the realm did not compile, and once the tags are used /// up. script_tag: u32, + /// The unhandled rejections of the last run that ended successfully, and how many there were. + rejections: (Vec, usize), } impl Default for Realm { @@ -186,7 +205,7 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE, rejections: (Vec::new(), 0) } } /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default @@ -215,6 +234,13 @@ impl Realm { self.interp.reset_gc_threshold(); } + /// Gives a realm made without [`Options::es2015`] the built-ins that option adds (`Promise`), + /// for its next runs; a realm that has them already is left as it is. It does not take them + /// away again. Call it between runs. + pub fn add_es2015(&mut self) { + crate::builtins::promise::add_to(&mut self.interp); + } + /// The realm's interrupt flag. Setting it stops a running script, or the next one to start. pub fn interrupt(&self) -> Interrupt { Interrupt(self.interp.interrupt.clone()) @@ -231,19 +257,21 @@ impl Realm { let _ = interp.define(global, key(name), Prop::Data { value: Value::Object(o), flags: HIDDEN }); } - /// Runs `source` as a script in the global environment and returns its completion value (the - /// value of the last expression statement that ran). A realm whose built-ins could not be - /// installed runs nothing and gives an internal error. + /// Runs `source` as a script in the global environment, then the promise jobs it queued, and + /// returns its completion value (the value of the last expression statement that ran). A realm + /// whose built-ins could not be installed runs nothing and gives an internal error. pub fn run(&mut self, source: &str) -> Result { let code = self.compile(source)?; - let result = self.interp.run_global(code, false); + let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v)); self.outcome(result) } /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { self.script_tag = UNKNOWN_SOURCE; + self.rejections = (Vec::new(), 0); let interp = &mut self.interp; + interp.end_jobs(false); if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false }); } @@ -293,8 +321,12 @@ impl Realm { interp.waiting = false; interp.resuming = None; interp.passing = Value::Undefined; + interp.end_jobs(result.is_ok()); match result { - Ok(v) => Ok(interp.to_js_value(&v)), + Ok(v) => { + self.rejections = interp.take_unhandled(); + Ok(interp.to_js_value(&v)) + } Err(Abrupt::Throw(v)) => { let message = interp.describe(&v); let authored = interp.thrown_by_script(&v); @@ -305,6 +337,11 @@ impl Realm { let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false }) } + Err(Abrupt::Limit(LimitKind::Jobs)) => { + let max = interp.promises.max_jobs; + let message = format!("limit reached: Jobs (more than {max} promise jobs were waiting to run)"); + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Jobs), message, line, column, authored: false }) + } Err(Abrupt::Limit(kind)) => { Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false }) } @@ -324,12 +361,14 @@ impl Realm { /// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one /// instruction), and pauses where it can resume: between two instructions of the script's own /// code. A getter, a built-in's callback or another nested run has native frames under it, so - /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned + /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. After the script's code + /// ends, the slices run the promise jobs it queued, pausing between jobs and inside a callback + /// written in JavaScript, and the run is done once the queue is empty. Once this has returned /// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its /// result ([`Realm::waits`]), the run does not advance: this gives an internal error. pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; - if interp.frames.is_empty() { + if !interp.running() { return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false }); } if interp.waiting { @@ -345,7 +384,7 @@ impl Realm { let cap = slice.saturating_add(self.unbroken_fuel).min(total); interp.fuel = cap; interp.in_slice = true; - let r = interp.execute_slice(cap - slice.min(cap)); + let r = interp.execute_run_slice(cap - slice.min(cap)); interp.in_slice = false; let used = cap - interp.fuel; interp.fuel = total - used; @@ -360,7 +399,28 @@ impl Realm { /// Is a run begun with [`Realm::start`] still going? pub fn is_running(&self) -> bool { - !self.interp.frames.is_empty() + self.interp.running() + } + + /// The promises the last run rejected that still had no rejection handler when it ended + /// successfully, in the order they were rejected: the first 20 of them. Empty after a run that + /// ended with an error, and until a run ends. + pub fn unhandled_rejections(&self) -> &[Rejection] { + &self.rejections.0 + } + + /// How many unhandled rejections the last run that ended successfully had, the ones + /// [`Realm::unhandled_rejections`] leaves out included. + pub fn unhandled_rejection_count(&self) -> usize { + self.rejections.1 + } + + /// Which source the code with tag `tag` is, as [`Realm::error_source`] gives it for an error. + pub fn source_of(&self, tag: u32) -> u32 { + match tag { + UNKNOWN_SOURCE => UNKNOWN_SOURCE, + tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), + } } /// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's @@ -434,10 +494,7 @@ impl Realm { /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which /// includes code from an earlier script and from the sources given during its run. pub fn error_source(&self) -> u32 { - match self.interp.error_tag { - UNKNOWN_SOURCE => UNKNOWN_SOURCE, - tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), - } + self.source_of(self.interp.error_tag) } /// The source tag of the code the last error's `line` and `column` are in, which stays the same diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 23337128bb..9f5223ea36 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -35,6 +35,12 @@ //! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without //! `test/annexB/` skips them; a folder there with no test to parse or run fails them. //! +//! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`: +//! those whose feature tags name only `Promise`, `Promise.allSettled` and +//! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests +//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its +//! failures go to `promise-failures.txt`. +//! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -43,7 +49,6 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize}; - /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] struct Meta { @@ -696,6 +701,145 @@ fn run_annex_b(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); } +/// The feature tags a `test/built-ins/Promise` test may carry and still run: `Promise`, +/// `Promise.allSettled` and `Promise.prototype.finally`. +const PROMISE_FEATURES: &[&str] = &["Promise", "Promise.allSettled", "Promise.prototype.finally"]; + +#[test] +fn promise_builtins_run() { + let Some(dir) = suite_dir() else { + println!("test262 Promise: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_promise(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global +/// `print` that collects its output; an `async` test passes when it prints +/// `Test262:AsyncTestComplete`. +fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { + let options = Options { es2015: true, ..Options::default() }; + let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let out = printed.clone(); + realm.define_function("print", move |args| { + let line = match args.first() { + Some(JsValue::String(s)) => s.clone(), + Some(other) => format!("{other:?}"), + None => String::new(), + }; + out.borrow_mut().push_str(&line); + out.borrow_mut().push('\n'); + Ok(JsValue::Undefined) + }); + let result = realm.run(script); + if asynchronous && result.is_ok() { + let printed = printed.borrow(); + return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { + Ok(()) + } else { + Err(format!("printed {:?}", printed.trim())) + }; + } + match (result, negative_type) { + (Ok(_), None) => Ok(()), + (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), + (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { + realm.bind_last_thrown("__thrown"); + match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { + Ok(JsValue::Bool(true)) => Ok(()), + _ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)), + } + } + (Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)), + } +} + +/// Runs the tests under `test/built-ins/Promise` whose feature tags are all in +/// [`PROMISE_FEATURES`], whose code parses as ES5 and uses only the built-ins present, as sloppy +/// and strict code as [`run_tests`] does, `async` tests included. Prints the counts and writes the +/// failures to `promise-failures.txt` beside the suite. +fn run_promise(dir: &Path) { + let root = or_fail(inside(dir, "test/built-ins/Promise")); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let done = harness("doneprintHandle.js"); + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let mut groups: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let (mut files, mut other_features) = (0usize, 0usize); + for path in or_fail(test_files(&root)) { + files += 1; + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !PROMISE_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let asynchronous = meta.flags.iter().any(|f| f == "async"); + let tags = if meta.features.is_empty() { "no feature tag".to_string() } else { meta.features.join(", ") }; + let counts = groups.entry(format!("{tags}, {}", if asynchronous { "async" } else { "sync" })).or_default(); + let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")); + if negative_parse || meta.flags.iter().any(|f| f == "module") { + counts.skipped += 1; + continue; + } + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if parse(&source, &Options::default()).is_err() || needs_missing_builtin(&[&source, &includes], &missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + let mut all = RunCounts::default(); + for (group, counts) in &groups { + println!("test262 built-ins/Promise, {group}: {}.", counts.summary()); + all.tests += counts.tests; + all.skipped += counts.skipped; + all.passed += counts.passed; + all.failed += counts.failed; + all.panicked += counts.panicked; + all.failures.push_str(&counts.failures); + } + let report = dir.join("promise-failures.txt"); + if let Err(e) = std::fs::write(&report, &all.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 built-ins/Promise through the interpreter: {files} files, {other_features} with other feature tags left out; {}. Failures: {}", + all.summary(), + report.display() + ); + assert!(all.tests > 0, "no Promise tests ran under {}", root.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..1a7b9d82dc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2616,8 +2616,10 @@ https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-act describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and -`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A script run from a +`.js` file also has `Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a +named engine (`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later +run, as it keeps its globals. The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it @@ -2644,6 +2646,27 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +In a `.js` script, `Promise` follows ECMA-262 11th edition section 25.6 +(https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, +`Promise.resolve`, `reject`, `all`, `allSettled` and `race`. `Promise.any` is not provided. These are VectorCraft's +own rules: + +- The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after + the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. + A promise still pending when no job is left stays pending, and the run ends. +- The jobs run on the run's fuel and limits, and each job takes 1 unit of fuel. A chain of callbacks that never ends + stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error + `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or + `script.stop` drops the jobs still waiting, and the documents go back as for any failed run. +- `all`, `allSettled` and `race` take an array, another object whose `length` is a whole number, or a string (one + item per character); any other value rejects the promise they return with a `TypeError`. The promises `then` and the + statics make are always plain `Promise` objects; `Symbol.species` and subclasses are not read. +- A promise rejected with no rejection handler that still has none when the run ends successfully is reported: the + report's `unhandledRejections` lists the first 20 as `{message, messageOrigin, line, column, file?}`, where it was + 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. + Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` @@ -2825,7 +2848,8 @@ VectorCraft sets these limits itself: In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, -runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In +runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`, with +`unhandledRejections` and `unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..7881566f89 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,6 +1082,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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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. Until the language has iterators, `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, 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: 402 of 538 runs pass, where none ran before. The 136 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and a `name` on built-in functions. `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: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. diff --git a/xtask/src/test262.rs b/xtask/src/test262.rs index 7ee456a6c2..3caf8f4a81 100644 --- a/xtask/src/test262.rs +++ b/xtask/src/test262.rs @@ -5,8 +5,8 @@ //! `test/language` tests and the tests of the ES5 built-ins under `test/built-ins` and //! `test/annexB/built-ins` that need only the interpreter's built-ins, run the `test/built-ins` //! tests for `String`, `Number`, `RegExp` and `Date`, parse and run the `test/annexB/language` -//! tests and run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and -//! `Function`), and print each one's counts. +//! tests, run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and +//! `Function`) and the `test/built-ins/Promise` tests, and print each one's counts. //! //! It also fetches `json2.js`, Douglas Crockford's public-domain JSON polyfill //! (https://github.com/douglascrockford/JSON-js), at a pinned commit, checks it against its SHA-256 From 3859c084d0513dabba5b63a7fdf58be76a029711 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:33:27 -0800 Subject: [PATCH 016/107] Clipboard: Paste keeps a Copy or Cut whose system clipboard write failed When another app held the system clipboard open or refused the write, Cut removed the art and kept it in the internal clipboard, but every Paste command then read the older contents that the other app had left on the system clipboard, and pasted those contents instead of the cut art. A failed Copy had the same fault. A failed write is now recorded whether or not the copied formats have text. Until another app copies something, every Paste command takes the internal clipboard, and a paste into type or a text field takes the copy's text, or nothing when the formats have no text. On macOS the clipboard service now reports the pasteboard's change count, so a later copy is noticed whatever the clipboard holds. Linux and the BSDs have no change count: there a later copy is noticed only when it changes the clipboard's text, so a failed write is kept only while the clipboard held text at the failure. The new tests run a failed Copy or Cut through the six Paste commands and a paste into type, with the clipboard locked or the write refused, with and without a change count, with On Copy: Include SVG Code off so that the formats have no text, and over a picture another app copied. --- apps/vectorcraft/src/clipboard.rs | 13 ++++ crates/ui-egui/src/sysclip.rs | 79 ++++++++++++++++------- crates/ui-egui/src/tests/clipboard.rs | 48 ++++++++++++++ crates/ui-egui/src/tests/sysclip.rs | 93 +++++++++++++++++++++++++++ docs/control-protocol.md | 4 +- docs/mcp.md | 7 +- 6 files changed, 218 insertions(+), 26 deletions(-) diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 3568b4683e..a6b60a818c 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -1513,6 +1513,13 @@ mod portable { } } + /// On macOS the pasteboard's change count ([`super::mac::change_count`]); the other + /// platforms this module serves have none. + #[cfg(target_os = "macos")] + fn change_count(&mut self) -> Option { + super::mac::change_count() + } + fn read(&mut self, mimes: &[&'static str]) -> Option { self.read_now_or_later(mimes)?.flavour() } @@ -3227,6 +3234,12 @@ mod mac { }) } + /// The pasteboard's change count, which goes up each time the pasteboard's ownership changes, + /// as when an app clears it to copy something. + pub fn change_count() -> Option { + autoreleasepool(|_| u64::try_from(NSPasteboard::generalPasteboard().changeCount()).ok()) + } + /// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is /// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger /// type is skipped and the next tried. diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index eb5a258e12..6b8a019223 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -101,8 +101,8 @@ pub(crate) struct Publishing { /// The latest one's formats wait to be written. pending: bool, /// The latest one's formats could not be written: what the system clipboard held when the - /// write failed, and the text of those formats. - unwritten: Option<(Held, String)>, + /// write failed, and the text of those formats, if they have text. + unwritten: Option<(Held, Option)>, /// The status bar's message when the latest one ran, with [`crate::state::UiState::status_sets`] /// then. Its formats' notes replace the message only while the status bar still shows it and /// nothing has set the status since. @@ -136,6 +136,12 @@ impl Publishing { fn shows_status(&self, ui: &crate::state::UiState) -> bool { ui.status == self.status.0 && ui.status_sets == self.status.1 } + + /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing + /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? + fn holds_unwritten(&self, cb: &mut (dyn SystemClipboard + 'static)) -> bool { + self.unwritten.as_ref().is_some_and(|(held, _)| Held::now(cb) == *held) + } } /// The status bar's line after a Copy (or with `cut`, a Cut) whose formats have `n` notes, the @@ -199,15 +205,34 @@ impl VectorcraftApp { || self.services.system_clipboard.as_mut().is_none_or(|cb| cb.holds_ours()) } + /// Is the latest Copy or Cut one whose formats could not be written to the system clipboard, + /// with nothing copied since? Paste then takes the internal clipboard, and a paste into type or + /// a text field takes that copy's text (nothing when its formats have no text), until another + /// app copies something. Where the platform + /// has no change count (Linux and the BSDs), a copy is noticed only when it changes the + /// clipboard's text, so the copy is kept only when the clipboard held text when the write + /// failed. When it held only a picture, or nothing that could be read, Paste takes what the + /// clipboard holds. + fn holds_unwritten_copy(&mut self) -> bool { + let Some(cb) = self.services.system_clipboard.as_deref_mut() else { return false }; + self.clipboard_publishing.holds_unwritten(cb) + } + /// The text of the latest Copy or Cut whose formats could not be written to the system - /// clipboard, while nothing has been copied since that Copy or Cut. A paste into type or a text - /// field takes this text until another app copies something. Where the platform has no change - /// count, a copy is noticed only when it changes the clipboard's text, so the copy is kept only - /// when the clipboard held text when the write failed. + /// clipboard, while nothing has been copied since that Copy or Cut + /// ([`Self::holds_unwritten_copy`]). pub(crate) fn unwritten_clipboard_text(&mut self) -> Option { - let cb = self.services.system_clipboard.as_deref_mut()?; - let (held, text) = self.clipboard_publishing.unwritten.as_ref()?; - (Held::now(cb) == *held).then(|| text.clone()) + self.clipboard_publishing.unwritten.as_ref()?.1.as_ref()?; + self.unwritten_copy().flatten() + } + + /// While [`Self::holds_unwritten_copy`]: the text of that copy's formats, `None` inside when + /// they have no text. + fn unwritten_copy(&mut self) -> Option> { + if !self.holds_unwritten_copy() { + return None; + } + self.clipboard_publishing.unwritten.as_ref().map(|(_, text)| text.clone()) } /// After Copy or Cut: offer the copied objects to other apps. With the system clipboard @@ -273,8 +298,8 @@ impl VectorcraftApp { let current = before.as_ref() == Some(&before_write); if let Err(e) = cb.write(&f) { // Another app may hold the clipboard open. It keeps what it held (or what the - // failed write left), and a paste into text takes this copy's text until - // something else is copied. + // failed write left). Until something else is copied, Paste takes this copy, + // and a paste into text takes its text. let held = Held::now(cb.as_mut()); let text = f.iter().find(|t| t.mime == TEXT).map(|t| String::from_utf8_lossy(&t.data).into_owned()); // A change during the write is the failed write emptying the clipboard and @@ -289,7 +314,7 @@ impl VectorcraftApp { // Without a change count, a clipboard with no text can't show a later copy of // a picture, or tell an empty clipboard from one that couldn't be read. let trackable = held != Held::Text(None); - app.clipboard_publishing.unwritten = text.filter(|_| current && left_by_write && trackable).map(|text| (held, text)); + app.clipboard_publishing.unwritten = (current && left_by_write && trackable).then_some((held, text)); return Err(e); } Ok(warnings) @@ -377,17 +402,20 @@ impl VectorcraftApp { let waited = ctx.data(|d| d.get_temp::(egui::Id::unique("clipboard.pending-at-tick"))).unwrap_or(false); ctx.data_mut(|d| d.remove::(egui::Id::unique("clipboard.pending-at-tick"))); if !(self.clipboard_publishing.pending || waited) { - // A copy whose formats could not be written: a paste takes its text, not the text the - // clipboard kept ([`Self::unwritten_clipboard_text`]). + // A copy whose formats could not be written: a paste takes its text, or nothing when + // they have none, not the text the clipboard kept ([`Self::unwritten_copy`]). let pasting = textless || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Paste(_)))); - if pasting && let Some(text) = self.unwritten_clipboard_text() { + if pasting && let Some(text) = self.unwritten_copy() { ctx.input_mut(|i| { - for e in &mut i.events { - if let egui::Event::Paste(t) = e { - t.clone_from(&text); + i.events.retain_mut(|e| match (e, &text) { + (egui::Event::Paste(t), Some(text)) => { + t.clone_from(text); + true } - } - if textless { + (egui::Event::Paste(_), None) => false, + _ => true, + }); + if textless && let Some(text) = text { i.events.insert(0, egui::Event::Paste(text)); } }); @@ -452,7 +480,10 @@ impl VectorcraftApp { // A picture or file the host read from the paste. (Some(f), _) if f.mime != TEXT => import_command(&f, center), (_, Some(cb)) => { - if self.clipboard_publishing.pending || cb.holds_ours() { + // After a Copy or Cut whose formats could not be written, with nothing copied + // since, what the clipboard still holds is older than the internal clipboard. + let publishing = &self.clipboard_publishing; + if publishing.pending || publishing.holds_unwritten(cb.as_mut()) || cb.holds_ours() { return Ok(None); } let mut read = |mimes: &[&'static str]| if defer { cb.read_deferred(mimes) } else { cb.read(mimes).map(ClipboardRead::Now) }; @@ -520,12 +551,12 @@ impl VectorcraftApp { } /// The text on the system clipboard once the formats a Copy or Cut is making are written, for a - /// paste into a text field or type. When they could not be written, their text - /// ([`Self::unwritten_clipboard_text`]). + /// paste into a text field or type. When they could not be written, their text, or `None` when + /// they have none ([`Self::unwritten_copy`]). pub(crate) fn written_clipboard_text(&mut self) -> Option { // Only other copies' formats are ahead of them on the worker ([`Self::publish_clipboard`]). background::wait_until(self, |app| !app.clipboard_publishing.pending); - self.unwritten_clipboard_text().or_else(|| self.system_clipboard_text()) + self.unwritten_copy().unwrap_or_else(|| self.system_clipboard_text()) } /// The text on the system clipboard, if any. diff --git a/crates/ui-egui/src/tests/clipboard.rs b/crates/ui-egui/src/tests/clipboard.rs index 1892df67be..1c037b0f41 100644 --- a/crates/ui-egui/src/tests/clipboard.rs +++ b/crates/ui-egui/src/tests/clipboard.rs @@ -396,6 +396,54 @@ fn type_paste_without_a_change_count_drops_a_refused_copy_it_cannot_track() { assert_eq!(paste_at(&mut app, 5), "Own: "); } +/// After a Copy whose formats have no text (On Copy: Include SVG Code off) and could not be +/// written, a paste into type takes nothing, from the menu or a paste event, not the text another +/// app left on the clipboard. A later copy in another app still pastes. +#[test] +fn a_paste_into_type_after_a_refused_textless_copy_takes_nothing() { + use vectorcraft_engine::cmd::clipboard::TEXT; + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + for uncounted in [false, true] { + let (mut app, board) = super::sysclip::app(); + if uncounted { + super::sysclip::without_change_count(&board); + } + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": false})); + let rect = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [rect]})); + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]); + super::sysclip::refuse_writes(&board, true); + run(&mut app, "edit.copy", json!({})); + crate::background::wait_all(&mut app); + super::sysclip::refuse_writes(&board, false); + + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + let text = |app: &VectorcraftApp| { + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + t.plain_text() + }; + let place = |app: &mut VectorcraftApp| { + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + }; + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: ", "uncounted {uncounted}: the menu's Paste"); + place(&mut app); + super::sysclip::frame(&mut app, vec![egui::Event::Paste("Old".into())]); + assert_eq!(text(&app), "Own: ", "uncounted {uncounted}: a paste event"); + + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"New".to_vec())]); + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: New", "uncounted {uncounted}: the later copy"); + } +} + #[test] fn a_paste_event_waiting_on_a_refused_copy_pastes_that_copy() { let _guard = TEST_CLIP_LOCK.lock().unwrap(); diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 6ae55087b8..d857f5be93 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -359,6 +359,99 @@ fn our_own_copy_pastes_the_lossless_internal_clipboard() { assert!(matches!(pasted(&app)[0].kind, NodeKind::Path { .. })); } +/// SVG markup of three closed paths, a group of two more and a compound path with a hole: five +/// objects. +fn closed_paths_svg() -> String { + let mut svg = String::from(r#""#); + for x in [10, 20, 30] { + svg.push_str(&format!(r##""##)); + } + svg.push_str(r#""#); + svg.push_str(r#""#); + svg +} + +/// Paste the objects of [`closed_paths_svg`] from another app and select them all → their count. +fn paste_closed_paths(app: &mut VectorcraftApp, board: &Rc>) -> usize { + copy_elsewhere(board, vec![(SVG, closed_paths_svg().into_bytes())]); + run(app, "edit.paste", json!({})); + run(app, "select.all", json!({})); + let objects = count(app); + assert_eq!(app.session.active().unwrap().selection.objects.len(), objects); + objects +} + +/// A Copy or Cut whose formats can't be written to the system clipboard (another app holds it +/// open, or refuses the write) stays what every Paste command takes while nothing else is copied, +/// with and without a change count, and when its formats have no text; the clipboard's older +/// contents do not replace it, and a paste into text takes the copy's text, or nothing. A later +/// copy in another app still wins. Without a change count, a clipboard that held only a picture +/// can't show a later copy, so there Paste takes the picture. +#[test] +fn a_copy_the_system_clipboard_refused_still_pastes_the_copied_art() { + type Fail = fn(&Rc>, bool); + // Case, Copy or Cut, how the write fails, no change count, On Copy: Include SVG Code, the + // other app's copy before it is a picture, Paste takes the copied art. + let cases: [(&str, &str, Fail, bool, bool, bool, bool); 8] = [ + ("locked", "edit.cut", lock, false, true, false, true), + ("refused", "edit.cut", refuse_writes, false, true, false, true), + ("refused, uncounted", "edit.cut", refuse_writes, true, true, false, true), + ("refused, no text", "edit.cut", refuse_writes, false, false, false, true), + ("refused, uncounted, no text", "edit.cut", refuse_writes, true, false, false, true), + ("refused copy", "edit.copy", refuse_writes, false, true, false, true), + ("refused, over a picture", "edit.cut", refuse_writes, false, true, true, true), + ("refused, uncounted, over a picture", "edit.cut", refuse_writes, true, true, true, false), + ]; + let pastes = + ["edit.paste", "edit.pasteInFront", "edit.pasteInBack", "edit.pasteInPlace", "edit.pasteOnAllArtboards", "edit.pasteWithoutFormatting"]; + for (case, op, fail, uncounted, svg_text, over_picture, kept) in cases { + let (mut app, board) = app(); + if uncounted { + without_change_count(&board); + } + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": svg_text})); + let objects = paste_closed_paths(&mut app, &board); + if over_picture { + copy_elsewhere(&board, vec![(PNG, blue_png())]); + } else { + copy_elsewhere(&board, vec![(TEXT, b"Words another app copied".to_vec())]); + } + fail(&board, true); + run(&mut app, op, json!({})); + background::wait_all(&mut app); + fail(&board, false); + assert!(app.ui.status.starts_with("Couldn't copy to the system clipboard"), "{case}: {}", app.ui.status); + let left = if op == "edit.cut" { 0 } else { objects }; + assert_eq!(count(&app), left, "{case}"); + if !kept { + run(&mut app, "edit.paste", json!({})); + assert!(matches!(pasted(&app)[0].kind, NodeKind::Image { .. }), "{case}: the picture"); + continue; + } + let text = app.written_clipboard_text(); + assert_eq!(text.is_some(), svg_text, "{case}: a paste into text takes the copy's text, or nothing: {text:?}"); + assert!(text.is_none_or(|t| t.contains(" Date: Sat, 21 Nov 2026 22:36:50 -0800 Subject: [PATCH 017/107] Plug-ins: a number parameter can show a slider beside its field A `number` or `int` parameter may now declare `"widget": "slider"`, with an optional `step` counted from `min`. The filter, live-effect and exporter dialogs and the Appearance panel's effect editor then show a slider over the parameter's range before its number field. The slider is named by the row's label for screen readers and moves by the step with the arrow keys. A value off the slider's steps, typed in the field or set by a script, is kept until the slider is moved. Install refuses the keys on any other parameter, on a range with no room, or with a step that cannot apply, and the refusals have rows in every complete catalog. Hosts from before these keys ignore them, as they do the other display keys. While a slider is dragged, the preview runs the plug-in at most about ten times a second, on the latest value, and the value the drag ends on always previews. In the Appearance panel a drag is one undo step. --- crates/plugins/src/dialog.rs | 114 +++++++++- crates/ui-egui/src/dialogs.rs | 5 +- crates/ui-egui/src/dialogs/effect.rs | 6 +- crates/ui-egui/src/dialogs/form.rs | 201 +++++++++++++++++- crates/ui-egui/src/dialogs/plugin.rs | 12 +- .../src/dialogs/tests_plugin_fields.rs | 196 ++++++++++++++++- crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/panels/appearance.rs | 81 ++++++- crates/ui-egui/src/panels/appearance/tests.rs | 92 ++++++++ docs/plugins.md | 10 +- docs/target-app-parity.md | 1 + 35 files changed, 824 insertions(+), 19 deletions(-) diff --git a/crates/plugins/src/dialog.rs b/crates/plugins/src/dialog.rs index 3777dab2e0..76c08cce02 100644 --- a/crates/plugins/src/dialog.rs +++ b/crates/plugins/src/dialog.rs @@ -1,5 +1,6 @@ //! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`, -//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters). +//! `group`, `help`, `helpUrl`, `visibleWhen`, `widget` and `step` keys of each one +//! (docs/plugins.md › Parameters). //! //! These keys are presentation only. A host from before them ignores them, so a plug-in that //! declares them still installs there, and a plug-in is given every parameter whether its dialog @@ -58,6 +59,66 @@ pub struct ParamUi { /// Shown only while each parameter named here has one of the values listed for it. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub visible_when: BTreeMap>, + /// The control that shows a number: [`Widget::Slider`] adds a slider beside its field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub widget: Option, + /// How far the slider moves the value at a time, counted from `min` (a whole number for an + /// `int`); without it, a slider moves a `number` to two decimal places (more when `max` minus + /// `min` is under 1) and an `int` by 1. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub step: Option, +} + +/// The control a `number` or `int` parameter's row shows besides its number field (`widget`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Widget { + /// A slider over `min..max`, beside the number field. + Slider, +} + +/// The largest whole number an `f64` holds exactly, which bounds an `int` slider's range. +const EXACT_INT: i64 = 1 << 53; + +impl ParamUi { + /// The range a slider shows `spec`'s value over, when the parameter asks for one + /// ([`Widget::Slider`]) and `spec` is a `number` or `int` the manifest checks allow it on. + pub fn slider_range(&self, spec: &ParamSpec) -> Option> { + if self.widget != Some(Widget::Slider) { + return None; + } + match spec { + ParamSpec::Number { min, max, .. } if min < max => Some(*min..=*max), + ParamSpec::Int { min, max, .. } if min < max && -EXACT_INT <= *min && *max <= EXACT_INT => Some(*min as f64..=*max as f64), + _ => None, + } + } + + /// Checks `widget` and `step` against parameter `spec`; `bad` builds the error. + fn validate_slider(&self, spec: &ParamSpec, bad: impl Fn(&str) -> Result<()>) -> Result<()> { + if self.widget.is_none() { + return match self.step { + Some(_) => bad("`step` is only for a parameter with a slider"), + None => Ok(()), + }; + } + let Some(range) = self.slider_range(spec) else { + return match spec { + ParamSpec::Number { .. } | ParamSpec::Int { .. } => { + bad(&format!("a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT}")) + } + _ => bad("a slider is only for `number` and `int` parameters"), + }; + }; + let Some(step) = self.step else { return Ok(()) }; + if !step.is_finite() || step <= 0.0 || step > range.end() - range.start() { + return bad("`step` must be a number above 0 and at most `max` minus `min`"); + } + if matches!(spec, ParamSpec::Int { .. }) && step.fract() != 0.0 { + return bad("an `int` parameter's `step` must be a whole number"); + } + Ok(()) + } } /// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless @@ -86,6 +147,9 @@ impl ParamUi { return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes")); } } + if let Some((_, p)) = m.params.get(index) { + self.validate_slider(&p.spec, bad)?; + } if self.visible_when.len() > MAX_CONDITIONS { return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters")); } @@ -304,4 +368,52 @@ mod tests { let fine = with("help", r#""Two\nlines.""#); assert!(Manifest::parse(fine.as_bytes()).is_ok()); } + + /// A `number` or `int` parameter with a range may ask for a slider, with a step from `min`; + /// the keys read back as written, and a parameter without them shows no slider. + #[test] + fn slider_keys_parse_and_round_trip() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","params":{ + "area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"}, + "count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider","step":2}, + "plain":{"type":"number","min":0,"max":100,"default":10}}}"#, + ) + .unwrap(); + let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap()); + assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0)); + assert_eq!((count.ui.slider_range(&count.spec), count.ui.step), (Some(1.0..=20.0), Some(2.0))); + assert_eq!(plain.ui.slider_range(&plain.spec), None); + assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m); + assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider")); + } + + #[test] + fn slider_keys_that_cannot_apply_are_refused() { + let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#); + for bad in [ + // Only numbers have a slider, over a range that has room to move. + r#"{"type":"bool","widget":"slider"}"#, + r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#, + r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#, + r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#, + r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#, + // A control the host doesn't have, and a step without a slider. + r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#, + r#"{"type":"number","min":0,"max":1,"default":0,"step":0.1}"#, + // Steps that go nowhere, past the range, or between whole numbers. + r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider","step":0}"#, + r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider","step":-0.5}"#, + r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider","step":2}"#, + r#"{"type":"int","min":0,"max":10,"widget":"slider","step":2.5}"#, + ] { + assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}"); + } + // A command's parameters are checked the same way. + let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#); + assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok()); + assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err()); + let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider","step":10}"#); + assert!(Manifest::parse(fine.as_bytes()).is_ok()); + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..73efcceb5d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -179,7 +179,10 @@ pub(crate) use export_for_screens::{ open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, saved_options as screen_saved_options, saved_rows as screen_saved_rows, settings_format as screen_settings_format, }; -pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffix, read_number_list, unit_suffix}; +pub(crate) use form::{ + PARAM_SLIDER_WIDTH, SlidePreview, field_places, humanize, number_list_text, plugin_color_button, plugin_slider, ppi_suffix, read_number_list, + unit_suffix, +}; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; pub(crate) use new_document::{popup_open as new_document_popup_open, preset_name}; pub use png_options::open as open_raster_options; diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index df5789e649..811cc2da46 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -269,7 +269,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } // Plug-in effects get fields from their parameter schema; colour adjustments their sliders. let changed = match vectorcraft_plugins::effect::installed(&id) { - Some(plugin) => form::schema_fields(app, ui, d, plugin.manifest()), + // While a slider is dragged, the preview catches up with it a few times a second. + Some(plugin) => { + let changed = form::schema_fields(app, ui, d, plugin.manifest()); + form::slide_preview(ui, d, changed).unwrap_or(false) + } // The Color Effects add-on's take the plain form of their parameters. None if vectorcraft_effects::is_adjustment(&id) && !vectorcraft_effects::addons::color::is_color_effect(&id) => adjust_fields(ui, d), None if id == vectorcraft_effects::addons::halftone::HALFTONE => { diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index f19cd18cda..2c8b6cf7aa 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -610,7 +610,8 @@ fn typed_number(x: f64) -> Value { /// Editor for a plug-in's parameters from its manifest (the filter, live effect and exporter /// dialogs): numbers within their range, whole numbers, checkboxes, dropdowns, text and lists of -/// numbers, a row each. A row is labelled as the manifest says (else from the parameter's name), +/// numbers, a row each, with a slider before the number of a parameter that asks for one +/// ([`plugin_slider`]). A row is labelled as the manifest says (else from the parameter's name), /// with its unit after the value and its help on the label and on a help button that opens its /// page. Parameters outside any group come first, then each group as a section that folds /// ([`Manifest::sections`]); a parameter whose `visibleWhen` the values don't meet is left out @@ -634,6 +635,7 @@ pub(super) fn schema_fields(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (bool, Option) { let mut changed = false; let mut help = None; + let mut sliding = false; let visible = m.visible(&d.fields); let sections = m.sections(); // Every section's label column is as wide as the longest label shown, so the fields line up @@ -653,8 +655,9 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b let grid = egui::Grid::new(("plugin-grid", section)).num_columns(2).spacing([12.0, 8.0]).min_col_width(label_width); grid.show(ui, |ui| { for (k, p) in shown { - let (row_changed, opened) = param_row(ui, d, k, p); + let (row_changed, opened, row_sliding) = param_row(ui, d, k, p); changed |= row_changed; + sliding |= row_sliding; help = help.take().or(opened); ui.end_row(); } @@ -668,17 +671,97 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b } } }); + if sliding { + d.fields.insert(SLIDING.into(), json!(true)); + } else { + d.fields.remove(SLIDING); + } (changed, help) } +/// The field set while one of a plug-in dialog's sliders is being dragged ([`schema_rows`]). +const SLIDING: &str = "__sliding"; +/// The fields holding the dialog's [`SlidePreview`]: its `at` and its `held`. +const SLID_AT: &str = "__slidAt"; +const HELD: &str = "__held"; + +/// How often, at most, dragging the slider of a plug-in's parameter runs the plug-in again for +/// its preview (seconds). +pub(crate) const SLIDE_PREVIEW_EVERY: f64 = 0.1; + +/// When a drag on a plug-in parameter's slider last previewed, and whether a value it reached +/// has not previewed yet ([`SlidePreview::due`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct SlidePreview { + /// The time of the drag's last preview (seconds of the UI's clock). + pub at: Option, + /// A value changed since that preview. + pub held: bool, +} + +impl SlidePreview { + /// Whether to preview on this frame at time `now`, given whether a value `changed` on it and + /// whether a slider is `sliding`: `Err(wait)` to wait `wait` seconds, else whether there is a + /// change to preview. While a slider is dragged, a change previews at once when the drag's + /// last preview is at least [`SLIDE_PREVIEW_EVERY`] old, and otherwise waits for that time, + /// so a plug-in runs about ten times a second during a drag, on the latest value, rather than + /// on every frame. A change still waiting when the drag ends previews then. + pub(crate) fn due(&mut self, now: f64, sliding: bool, changed: bool) -> Result { + let pending = std::mem::take(&mut self.held) || changed; + if !sliding { + self.at = None; + return Ok(pending); + } + if !pending { + return Ok(false); + } + match self.at.map(|at| now - at) { + Some(since) if (0.0..SLIDE_PREVIEW_EVERY).contains(&since) => { + self.held = true; + Err(SLIDE_PREVIEW_EVERY - since) + } + _ => { + self.at = Some(now); + Ok(true) + } + } + } + + /// [`SlidePreview::due`] at `ui`'s time, asking for a frame when a wait ends: `None` to wait. + pub(crate) fn due_now(&mut self, ui: &egui::Ui, sliding: bool, changed: bool) -> Option { + let due = self.due(ui.input(|i| i.time), sliding, changed); + if let Err(wait) = due { + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } + due.ok() + } +} + +/// Whether the plug-in dialog `d` previews its values on this frame, given whether one `changed` +/// on it ([`schema_rows`]): `None` to wait while one of its sliders is dragged, else whether there +/// is a change to preview ([`SlidePreview::due`]). +pub(super) fn slide_preview(ui: &egui::Ui, d: &mut Dialog, changed: bool) -> Option { + let mut slide = SlidePreview { at: d.fields.get(SLID_AT).and_then(Value::as_f64), held: d.bool(HELD) }; + let due = slide.due_now(ui, d.bool(SLIDING), changed); + match slide.at { + Some(at) => d.fields.insert(SLID_AT.into(), json!(at)), + None => d.fields.remove(SLID_AT), + }; + match slide.held { + true => d.fields.insert(HELD.into(), json!(true)), + false => d.fields.remove(HELD), + }; + due +} + /// The label of parameter `k`'s row: its manifest `label`, else its name spaced out. fn param_label(k: &str, p: &Param) -> String { p.ui.label.as_ref().map_or_else(|| humanize(k), |l| format!("{l}:")) } /// One row of [`schema_fields`]: parameter `k`'s label and value field → whether the value changed, -/// and the help page asked for. -fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Option) { +/// the help page asked for, and whether its slider is being dragged. +fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Option, bool) { let t = Tokens::get(ui.ctx()); let label = param_label(k, p); let shown_label = ui.label(egui::RichText::new(&label).color(t.text)); @@ -687,11 +770,17 @@ fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Op let unit = p.ui.unit.as_deref().unwrap_or_default(); let suffix = unit_suffix(unit); let mut opened = None; + let mut sliding = false; let new = ui .horizontal(|ui| { // The row's painted label names every input in its value column (egui 0.37's strict // accessibility gate), not only the first one. - let (new, in_field) = ui.label_inputs_by(shown_label.id, |ui| value_field(ui, k, &label, &p.spec, &cur, &suffix)); + let (new, in_field) = ui.label_inputs_by(shown_label.id, |ui| { + let slid = p.ui.slider_range(&p.spec).map(|range| plugin_slider(ui, k, &p.spec, &cur, range, p.ui.step, PARAM_SLIDER_WIDTH)); + sliding = slid.as_ref().is_some_and(|(_, resp)| resp.dragged()); + let (typed, in_field) = value_field(ui, k, &label, &p.spec, &cur, &suffix, field_places(p)); + (slid.and_then(|(v, _)| v).or(typed), in_field) + }); if !in_field && !unit.is_empty() { ui.label(egui::RichText::new(unit).color(t.text_dim)); } @@ -704,17 +793,111 @@ fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Op }) .inner; let changed = new.map(|v| d.fields.insert(k.to_string(), v)).is_some(); - (changed, opened) + (changed, opened, sliding) +} + +/// Width of the slider a plug-in parameter asks for (`"widget": "slider"`) in its dialog, and the +/// most it takes in the Appearance panel. +pub(crate) const PARAM_SLIDER_WIDTH: f32 = 140.0; + +/// The slider of a `number` or `int` parameter that asks for one, `width` wide, over `range` (its +/// `min..max`), showing its value `cur`: dragging it or stepping it with the keys moves the value +/// by `step` from `min` (an `int` without one by 1, a `number` without one to two decimal places, +/// more when the range is under 1) → the value it moved to, and the slider's response. A value +/// off the slider's grid is kept until the slider is used. Screen readers get it as a slider with +/// the row's label as its name and the value as its number. +pub(crate) fn plugin_slider( + ui: &mut egui::Ui, + id: impl std::hash::Hash + std::fmt::Debug, + spec: &ParamSpec, + cur: &Value, + range: std::ops::RangeInclusive, + step: Option, + width: f32, +) -> (Option, egui::Response) { + let int = matches!(spec, ParamSpec::Int { .. }); + let (lo, hi) = (*range.start(), *range.end()); + let before = cur.as_f64().unwrap_or(lo).clamp(lo, hi); + let mut v = before; + // `Edits` clamps and rounds only what the pointer, the keys or a screen reader set, so drawing + // the slider leaves a value off its grid as it is. + let slider = egui::Slider::new(&mut v, range).show_value(false).clamping(egui::SliderClamping::Edits); + let places = if int { None } else { slider_places(lo, hi, step) }; + let slider = match step { + Some(step) => slider.step_by(step), + None if int => slider.integer(), + None => slider.fixed_decimals(places.unwrap_or(2)), + }; + let resp = ui + .push_id(("plugin-slider", id), |ui| { + ui.spacing_mut().slider_width = width; + crate::widgets::slider(ui, slider) + }) + .inner; + if v == before { + return (None, resp); + } + // Rounding onto the step's grid can pass `max`, which the plug-in would refuse, and a step + // such as 0.1 leaves binary noise (0.30000000000000004) that the plug-in would be given. + let v = match (step, places) { + (Some(_), Some(places)) => round_to(v, lo, places), + _ => v, + } + .clamp(lo, hi); + let new = (v != before).then(|| if int { json!(v.round() as i64) } else { json!(v) }); + (new, resp) +} + +/// The decimal places a `number` slider over `lo..=hi` moves its value to: with a `step`, the +/// step's and `lo`'s own (`None` when either has more than 17); without one, two, and more when +/// the range is under 1. +fn slider_places(lo: f64, hi: f64, step: Option) -> Option { + match step { + Some(step) => Some(decimal_places(step)?.max(decimal_places(lo)?)), + None => Some(2 + (-(hi - lo).log10()).ceil().clamp(0.0, 330.0) as usize), + } +} + +/// The decimal places the number field of plug-in parameter `p` shows and reads: those its slider +/// moves to, from 2 to the field's limit of 6, when it has one, else 2. +pub(crate) fn field_places(p: &Param) -> usize { + match (&p.spec, p.ui.slider_range(&p.spec)) { + (ParamSpec::Number { .. }, Some(range)) => slider_places(*range.start(), *range.end(), p.ui.step).unwrap_or(6).clamp(2, 6), + _ => 2, + } +} + +/// How many decimal places `x` is written with, when that is at most 17. +fn decimal_places(x: f64) -> Option { + (0..=17).find(|&d| { + let scaled = x * 10f64.powi(d as i32); + (scaled - scaled.round()).abs() <= ulp(scaled) + }) +} + +/// The gap between `x` and the next larger `f64` in magnitude. +fn ulp(x: f64) -> f64 { + let x = x.abs(); + f64::from_bits(x.to_bits() + 1) - x +} + +/// `v`, a value on a slider's grid counted from `lo`, rounded to `places` decimal places when that +/// moves it by no more than the binary noise of that count (four units in the last place of the +/// larger of `v` and `lo`, as in 0.30000000000000004), else `v`. +fn round_to(v: f64, lo: f64, places: usize) -> f64 { + let scale = 10f64.powi(places as i32); + let rounded = (v * scale).round() / scale; + if rounded.is_finite() && (rounded - v).abs() <= 4.0 * ulp(v.abs().max(lo.abs())) { rounded } else { v } } /// The field of parameter `k`'s value `cur` (a checkbox is called by the row's `label`) → the new /// value when it changed, and whether the field shows `suffix` (numbers do; the other fields leave -/// the unit to a label after them). -fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: &Value, suffix: &str) -> (Option, bool) { +/// the unit to a label after them). A number shows `places` decimal places ([`field_places`]). +fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: &Value, suffix: &str, places: usize) -> (Option, bool) { match spec { ParamSpec::Number { min, max, .. } => { let x = cur.as_f64().unwrap_or(*min); - (crate::widgets::range_field_named(ui, ("plugin-num", k), Some(label), x, *min..=*max, suffix, 2, 100.0).map(|x| json!(x)), true) + (crate::widgets::range_field_named(ui, ("plugin-num", k), Some(label), x, *min..=*max, suffix, places, 100.0).map(|x| json!(x)), true) } ParamSpec::Int { min, max, .. } => { let x = cur.as_i64().unwrap_or(*min).clamp(*min, *max); diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 706188f6da..f1722650bb 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -230,8 +230,18 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if run_with.is_none() && !d.str("__command").is_empty() { return true; } - form::schema_fields(app, ui, d, run_with.as_ref().unwrap_or(plugin.manifest())); + let changed = form::schema_fields(app, ui, d, run_with.as_ref().unwrap_or(plugin.manifest())); match plugin.manifest().budget { + // While a slider is dragged, the preview catches up with it a few times a second. Turning + // Preview off during the drag still rolls the preview back at once. + Budget::Light if form::slide_preview(ui, d, changed).is_none() => { + ui.add_space(8.0); + form::preview_check(ui, d); + if !d.bool("preview") { + let (label, p) = (d.str("__label"), params(d)); + form::preview_without_check(app, d, &label, &command(d), p); + } + } Budget::Light => { let (label, p) = (d.str("__label"), params(d)); form::preview(app, ui, d, &label, &command(d), p); diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs index f5f4e719a0..8d2eaeab8a 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -1,7 +1,7 @@ //! A plug-in's parameters in its dialog as its manifest presents them (docs/plugins.md › //! Parameters): labels, units after the values, help on the labels and a button to its page, -//! sections by group, text and lists of numbers, and parameters shown only while their -//! `visibleWhen` holds. The plug-in is removed after each test: plug-ins are process-wide. +//! sections by group, text and lists of numbers, parameters shown only while their +//! `visibleWhen` holds, and sliders. The plug-in is removed after each test: plug-ins are process-wide. use std::sync::{Arc, Mutex}; @@ -130,6 +130,198 @@ fn the_help_button_opens_the_parameter_s_page() { remove(&mut h, id); } +/// A plug-in's dialog draws a slider for a number that asks for one, named by its row's label, +/// and none for one that doesn't. Screen readers' steps move it by the parameter's `step`, counted +/// from `min`; a value they set lands on the step's grid. Drawing a slider leaves a value off its +/// grid as it is, a fractional step gives the plug-in the step's own decimals, a range under 1 +/// without a step still moves, and a drag reports itself to the dialog's preview while it lasts. +#[test] +fn a_plug_in_number_that_asks_for_a_slider_gets_one_that_steps_by_its_step() { + use egui::accesskit::{Action, ActionData, ActionRequest, Role}; + use egui_kittest::kittest::NodeT; + type Rows = egui_kittest::Harness<'static, (Dialog, vectorcraft_plugins::Manifest)>; + let m = vectorcraft_plugins::Manifest::parse( + br#"{"id":"test.area","name":"Area","kind":"filter","params":{ + "area":{"type":"number","min":0,"max":100,"default":10,"label":"Area","widget":"slider","step":5}, + "plain":{"type":"number","min":0,"max":100,"default":10,"label":"Plain"}, + "third":{"type":"int","min":1,"max":20,"default":1,"label":"Third","widget":"slider","step":3}, + "odd":{"type":"number","min":0,"max":100,"default":12,"label":"Odd","widget":"slider","step":5}, + "tenth":{"type":"number","min":0,"max":1,"default":0,"label":"Tenth","widget":"slider","step":0.1}, + "tiny":{"type":"number","min":0,"max":0.004,"default":0.001,"label":"Tiny","widget":"slider"}, + "milli":{"type":"number","min":0,"max":1,"default":0.004,"label":"Milli","widget":"slider","step":0.001}}}"#, + ) + .unwrap(); + let fields = json!({ "area": 10, "plain": 10, "third": 1, "odd": 12, "tenth": 0, "tiny": 0.001, "milli": 0.004 }); + let dialog = Dialog::new(plugin::KIND, fields); + let mut h: Rows = egui_kittest::Harness::builder().with_size(vec2(520.0, 480.0)).build_ui_state( + |ui, (d, m): &mut (Dialog, vectorcraft_plugins::Manifest)| { + form::schema_rows(ui, d, m); + }, + (dialog, m), + ); + h.run(); + let value = |h: &Rows, key: &str| h.state().0.fields[key].as_f64().unwrap(); + let act = |h: &mut Rows, label: &str, action: Action, data: Option| { + let (target_node, target_tree) = h.get_by_role_and_label(Role::Slider, label).accesskit_node().locate(); + h.event(egui::Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action, data })); + h.run(); + }; + assert_eq!(h.query_all_by_role(Role::Slider).count(), 6, "only the parameters that ask for one have a slider"); + // A number field shows the places its slider moves to. + assert!(h.query_all_by_value("0.004").next().is_some(), "Milli's field shows 0.004"); + assert_eq!((value(&h, "odd"), value(&h, "tiny")), (12.0, 0.001), "values off the sliders' grids are kept"); + h.state_mut().0.fields.extend([("odd".into(), json!(13)), ("tenth".into(), json!(0.15))]); + h.run(); + assert_eq!((value(&h, "odd"), value(&h, "tenth")), (13.0, 0.15), "typed values are kept"); + h.state_mut().0.fields.insert("tenth".into(), json!(0)); + let node = h.get_by_role_and_label(Role::Slider, "Area:").accesskit_node(); + assert_eq!((node.numeric_value(), node.min_numeric_value(), node.max_numeric_value()), (Some(10.0), Some(0.0), Some(100.0))); + act(&mut h, "Area:", Action::Increment, None); + assert_eq!(value(&h, "area"), 15.0, "one step up"); + act(&mut h, "Area:", Action::SetValue, Some(ActionData::NumericValue(47.0))); + let set = value(&h, "area"); + assert!((set / 5.0).fract() == 0.0 && (set - 47.0).abs() <= 2.5, "47 lands on the nearest step: {set}"); + // The grid is counted from `min`: 1, 4, 7. + act(&mut h, "Third:", Action::Increment, None); + act(&mut h, "Third:", Action::Increment, None); + assert_eq!(h.state().0.fields["third"], json!(7)); + for _ in 0..3 { + act(&mut h, "Tenth:", Action::Increment, None); + } + assert_eq!(h.state().0.fields["tenth"], json!(0.3)); + act(&mut h, "Tiny:", Action::SetValue, Some(ActionData::NumericValue(0.0025))); + let tiny = value(&h, "tiny"); + assert!((tiny - 0.0025).abs() < 0.0001, "a small range still moves: {tiny}"); + // Dragging along the rail moves the value and marks the drag for the preview until it ends. + let rail = h.get_by_role_and_label(Role::Slider, "Area:").rect(); + let at = |x: f32| egui::pos2(rail.left() + x * rail.width(), rail.center().y); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.event(egui::Event::PointerMoved(at(0.2))); + h.event(button(at(0.2), true)); + h.run(); + for x in [0.4, 0.6, 0.8] { + h.event(egui::Event::PointerMoved(at(x))); + h.run(); + } + assert!(h.state().0.bool("__sliding"), "the drag is in progress"); + let dragged = value(&h, "area"); + assert!(dragged > set && (dragged / 5.0).fract() == 0.0 && dragged <= 100.0, "moved right on the grid: {dragged}"); + h.event(button(at(0.8), false)); + h.run(); + assert!(!h.state().0.bool("__sliding"), "the drag ended"); +} + +/// During a drag on a plug-in parameter's slider, the preview runs at most every +/// [`form::SLIDE_PREVIEW_EVERY`] on the latest value, and the value the drag ends on previews even +/// when its turn hadn't come; outside a drag every change previews at once. +#[test] +fn a_slider_drag_previews_a_few_times_a_second_and_its_last_value() { + let mut slide = form::SlidePreview::default(); + let frame = 1.0 / 60.0; + // A drag of one second, with a new value on every frame. + let previews = (0..60).filter(|i| slide.due(*i as f64 * frame, true, true) == Ok(true)).count(); + assert!(previews > 1 && previews <= (1.0 / form::SLIDE_PREVIEW_EVERY) as usize + 1, "{previews} previews in 60 frames"); + // A change just after a preview waits; the frame the drag ends on previews it. + assert_eq!(slide.due(1.5, true, true), Ok(true)); + assert!(slide.due(1.5 + frame, true, true).is_err() && slide.held, "the last change is still to preview"); + assert_eq!(slide.due(1.5 + 2.0 * frame, false, false), Ok(true)); + assert_eq!(slide.due(1.5 + 3.0 * frame, false, false), Ok(false), "nothing left to preview"); + // A change that waits previews on the first frame after its wait, even without another change. + assert_eq!(slide.due(2.0, true, true), Ok(true)); + let wait = slide.due(2.0 + frame, true, true).expect_err("too soon after the last preview"); + assert!(wait > 0.0 && wait <= form::SLIDE_PREVIEW_EVERY); + assert_eq!(slide.due(2.0 + frame + wait, true, false), Ok(true)); + // Outside a drag, a change previews at once however soon it comes. + assert_eq!((slide.due(3.0, false, true), slide.due(3.0 + frame, false, true)), (Ok(true), Ok(true))); +} + +/// A filter's and a live effect's dialogs, at frames a sixtieth of a second apart: a drag on a +/// slider previews fewer values than it has frames, and the value it ends on previews. In the +/// filter's dialog, turning Preview off during the drag rolls the preview back at once. +#[test] +fn a_slider_drag_in_a_plug_in_dialog_previews_a_few_times_a_second() { + use egui::accesskit::Role; + let params = r#"{"area":{"type":"number","min":0,"max":100,"default":10,"label":"Area","widget":"slider","step":1}}"#; + for kind in ["filter", "effect"] { + let id = format!("test.ui.fields.slide{kind}"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let wasm = wat::parse_str(tpl::module(&tpl::manifest(&id, kind, params), tpl::ECHO, "", 1)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap(); + match kind { + "filter" => app.run("plugin.dialog", json!({"id": id})), + _ => app.run("effect.dialog", json!({"effect": vectorcraft_plugins::effect::effect_id(&id)})), + } + .unwrap(); + let mut fonts = false; + let mut h: Harness = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + set(&mut h, "preview", json!(true)); + // What the canvas shows: the filter's last previewed params, the effect's previewed value. + let previewed = |h: &Harness| match kind { + "filter" => h.state().ui.dialog.as_ref().and_then(|d| d.fields.get(form::PREVIEWED)).map(|p| p["params"]["area"].clone()), + _ => { + let doc = h.state().session.doc().unwrap(); + doc.doc.node(vectorcraft_doc::NodeId(shape)).and_then(|n| n.appearance.effects.last()).map(|e| e.params["area"].clone()) + } + }; + let area = |h: &Harness| h.state().ui.dialog.as_ref().expect("the dialog is open").fields["area"].clone(); + let rail = h.get_by_role_and_label(Role::Slider, "Area:").rect(); + let at = |x: f32| egui::pos2(rail.left() + x * rail.width(), rail.center().y); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + h.event(egui::Event::PointerMoved(at(0.1))); + h.event(button(at(0.1), true)); + h.step(); + let mut seen = vec![]; + for i in 1..=30 { + h.event(egui::Event::PointerMoved(at(0.1 + 0.025 * i as f32))); + h.step(); + let shown = previewed(&h); + if seen.last() != Some(&shown) { + seen.push(shown); + } + } + assert!(seen.len() > 2 && seen.len() < 15, "{kind}: {} values previewed in 30 frames: {seen:?}", seen.len()); + h.event(button(at(0.85), false)); + h.step(); + h.step(); + assert_eq!(previewed(&h), Some(area(&h)), "{kind}: the value the drag ended on previews"); + if kind == "filter" { + // A second drag, until a frame previews; the next frame waits, and Preview off rolls back then. + h.event(button(at(0.5), true)); + h.step(); + for i in 1..=10 { + let before = previewed(&h); + h.event(egui::Event::PointerMoved(at(0.5 - 0.02 * i as f32))); + h.step(); + if previewed(&h) != before { + break; + } + } + h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false)); + h.event(egui::Event::PointerMoved(at(0.2))); + h.step(); + assert_eq!(previewed(&h), None, "Preview off rolled the preview back"); + assert!(!h.state().session.in_interaction(), "and ended its interaction"); + h.event(button(at(0.2), false)); + h.step(); + } + h.state_mut().ui.dialog = None; + let _ = h.state_mut().session.cancel_interaction(); + remove(&mut h, &id); + } +} + /// `CRAFT_UI_PLUGIN_FIELDS_SHOT=` saves a picture of a dialog whose parameters use every /// presentation key there, and the test plug-in beside it (`hatch-test-filter.wasm`) to install in /// the app. Its parameter names are written as many plug-ins write them, in snake case, and it uses diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a29912a288 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7749,6 +7749,11 @@ variable-list-end {0}, {1} {0} i {1} @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` anomena `{other}`, que no és un paràmetre declarat abans d’aquest @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` anomena com a màxim {MAX_CONDITIONS} paràmetres @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` pren els valors de `{other}`, d’una casella de selecció o d’una opció +@msg `step` is only for a parameter with a slider `step` només s’aplica a un paràmetre amb control lliscant +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} un control lliscant necessita `min` inferior a `max`, i un de `int` un interval dins de ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters un control lliscant només s’aplica a paràmetres `number` i `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` ha de ser un nombre superior a 0 i com a màxim `max` menys `min` +@msg an `int` parameter's `step` must be a whole number el `step` d’un paràmetre `int` ha de ser un nombre enter @msg `visible` must be true or false `visible` ha de ser true o false @msg `{key}` must be a number from {_1} to {_2} `{key}` ha de ser un nombre de {_1} a {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` ha de ser una matriu de {MAX_ITEMS} entrades com a màxim diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..df10024d18 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7359,6 +7359,11 @@ axis Y Axis osa Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` uvádí `{other}`, což není parametr deklarovaný před tímto @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` smí uvádět nejvýše {MAX_CONDITIONS} parametrů @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` přebírá hodnoty `{other}`, a to zaškrtávacího políčka nebo volby +@msg `step` is only for a parameter with a slider `step` je jen pro parametr s posuvníkem +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} posuvník potřebuje `min` menší než `max` a posuvník typu `int` rozsah v mezích ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters posuvník je jen pro parametry `number` a `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` musí být číslo větší než 0 a nejvýše `max` minus `min` +@msg an `int` parameter's `step` must be a whole number `step` parametru `int` musí být celé číslo @msg `visible` must be true or false `visible` musí být true nebo false @msg `{key}` must be a number from {_1} to {_2} `{key}` musí být číslo od {_1} do {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` musí být pole s nejvýše {MAX_ITEMS} položkami diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..64a5722e1c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -590,6 +590,11 @@ liquify-list-end {0}, {1} {0} og {1} @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` angiver `{other}`, som ikke er en parameter, der er erklæret før denne @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` angiver højst {MAX_CONDITIONS} parametre @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` tager værdierne for `{other}`, fra et afkrydsningsfelt eller et valg +@msg `step` is only for a parameter with a slider `step` gælder kun for en parameter med skyder +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} en skyder kræver, at `min` er mindre end `max`, og en `int`-skyder et interval inden for ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters en skyder gælder kun for `number`- og `int`-parametre +@msg `step` must be a number above 0 and at most `max` minus `min` `step` skal være et tal over 0 og højst `max` minus `min` +@msg an `int` parameter's `step` must be a whole number `step` for en `int`-parameter skal være et heltal @msg `visible` must be true or false `visible` skal være true eller false @msg `{key}` must be a number from {_1} to {_2} `{key}` skal være et tal fra {_1} til {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` skal være et array med højst {MAX_ITEMS} elementer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..84ba615bcc 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6942,6 +6942,11 @@ axis Y Axis Y-Achse @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` nennt `{other}`, aber das ist kein Parameter, der vor diesem deklariert ist @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` darf höchstens {MAX_CONDITIONS} Parameter nennen @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` nimmt die Werte von `{other}` an, die eines Kontrollkästchens oder einer Auswahl +@msg `step` is only for a parameter with a slider `step` gibt es nur für einen Parameter mit Schieberegler +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} ein Schieberegler braucht `min` unter `max`, und ein `int`-Schieberegler einen Bereich innerhalb von ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters ein Schieberegler ist nur für `number`- und `int`-Parameter +@msg `step` must be a number above 0 and at most `max` minus `min` `step` muss eine Zahl über 0 und höchstens `max` minus `min` sein +@msg an `int` parameter's `step` must be a whole number der `step` eines `int`-Parameters muss eine ganze Zahl sein @msg `visible` must be true or false `visible` muss true oder false sein @msg `{key}` must be a number from {_1} to {_2} `{key}` muss eine Zahl von {_1} bis {_2} sein @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` muss ein Array mit höchstens {MAX_ITEMS} Einträgen sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..a3daf1f4e8 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7349,6 +7349,11 @@ axis Y Axis Άξονας Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one το `visibleWhen` αναφέρει το `{other}`, που δεν είναι παράμετρος δηλωμένη πριν από αυτήν @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters το `visibleWhen` αναφέρει έως {MAX_CONDITIONS} παραμέτρους @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice το `visibleWhen` δέχεται τιμές του `{other}`, ενός πλαισίου ελέγχου ή μιας επιλογής +@msg `step` is only for a parameter with a slider το `step` ισχύει μόνο για παράμετρο με ρυθμιστικό +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} ένα ρυθμιστικό χρειάζεται `min` μικρότερο από `max`, και ένα ρυθμιστικό `int` εύρος εντός ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters ένα ρυθμιστικό ισχύει μόνο για παραμέτρους `number` και `int` +@msg `step` must be a number above 0 and at most `max` minus `min` το `step` πρέπει να είναι αριθμός μεγαλύτερος από 0 και το πολύ `max` μείον `min` +@msg an `int` parameter's `step` must be a whole number το `step` μιας παραμέτρου `int` πρέπει να είναι ακέραιος αριθμός @msg `visible` must be true or false το `visible` πρέπει να είναι true ή false @msg `{key}` must be a number from {_1} to {_2} το `{key}` πρέπει να είναι αριθμός από {_1} έως {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries το `{key}` πρέπει να είναι πίνακας έως {MAX_ITEMS} στοιχείων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..a40f5a08ea 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7335,6 +7335,11 @@ axis Y Axis Eje Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` nombra `{other}`, que no es un parámetro declarado antes de este @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` nombra como máximo {MAX_CONDITIONS} parámetros @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` toma los valores de `{other}`, de una casilla de verificación o una opción +@msg `step` is only for a parameter with a slider `step` solo es para un parámetro con control deslizante +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} un control deslizante necesita `min` menor que `max`, y uno de `int` un intervalo dentro de ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters un control deslizante solo es para parámetros `number` e `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` debe ser un número mayor que 0 y como máximo `max` menos `min` +@msg an `int` parameter's `step` must be a whole number el `step` de un parámetro `int` debe ser un número entero @msg `visible` must be true or false `visible` debe ser true o false @msg `{key}` must be a number from {_1} to {_2} `{key}` debe ser un número de {_1} a {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` debe ser una lista de {MAX_ITEMS} entradas como máximo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..652508fccb 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7426,6 +7426,11 @@ axis Y Axis Y-akseli @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` nimeää parametrin `{other}`, jota ei ole esitelty ennen tätä parametria @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` nimeää enintään {MAX_CONDITIONS} parametria @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` ottaa parametrin `{other}` arvot, valintaruudun tai valinnan arvot +@msg `step` is only for a parameter with a slider `step` on vain liukusäätimellä varustetulle parametrille +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} liukusäädin vaatii, että `min` on pienempi kuin `max`, ja `int`-liukusäädin alueen välillä ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters liukusäädin on vain `number`- ja `int`-parametreille +@msg `step` must be a number above 0 and at most `max` minus `min` `step`-arvon on oltava 0:aa suurempi luku ja enintään `max` miinus `min` +@msg an `int` parameter's `step` must be a whole number `int`-parametrin `step`-arvon on oltava kokonaisluku @msg `visible` must be true or false `visible` on oltava true tai false @msg `{key}` must be a number from {_1} to {_2} `{key}` on oltava luku {_1} ja {_2} väliltä @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` on oltava enintään {MAX_ITEMS} kohteen taulukko diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..7060ca0afb 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7355,6 +7355,11 @@ axis Y Axis Axe Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` nomme `{other}`, qui n’est pas un paramètre déclaré avant celui-ci @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` nomme au plus {MAX_CONDITIONS} paramètres @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` prend les valeurs de `{other}`, celles d’une case à cocher ou d’un choix +@msg `step` is only for a parameter with a slider `step` ne s’applique qu’à un paramètre avec un curseur +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} un curseur exige `min` inférieur à `max`, et un curseur `int` une plage comprise dans ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters un curseur ne s’applique qu’aux paramètres `number` et `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` doit être un nombre supérieur à 0 et au plus égal à `max` moins `min` +@msg an `int` parameter's `step` must be a whole number le `step` d’un paramètre `int` doit être un nombre entier @msg `visible` must be true or false `visible` doit valoir true ou false @msg `{key}` must be a number from {_1} to {_2} `{key}` doit être un nombre de {_1} à {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` doit être un tableau d’au plus {MAX_ITEMS} entrées diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..22b5cd3a64 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6543,6 +6543,11 @@ arrowhead Feather पंख @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` में `{other}` दिया गया है, जो इससे पहले घोषित पैरामीटर नहीं है @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` में अधिकतम {MAX_CONDITIONS} पैरामीटर हो सकते हैं @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` `{other}` के मान लेता है, जो चेकबॉक्स या विकल्प होना चाहिए +@msg `step` is only for a parameter with a slider `step` केवल स्लाइडर वाले पैरामीटर के लिए है +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} स्लाइडर के लिए `min` का `max` से कम होना ज़रूरी है, और `int` स्लाइडर की सीमा ±{EXACT_INT} के भीतर होनी चाहिए +@msg a slider is only for `number` and `int` parameters स्लाइडर केवल `number` और `int` पैरामीटर के लिए है +@msg `step` must be a number above 0 and at most `max` minus `min` `step` 0 से बड़ी और अधिकतम `max` घटा `min` जितनी संख्या होनी चाहिए +@msg an `int` parameter's `step` must be a whole number `int` पैरामीटर का `step` पूर्ण संख्या होना चाहिए @msg `visible` must be true or false `visible` true या false होना चाहिए @msg `{key}` must be a number from {_1} to {_2} `{key}` {_1} से {_2} तक की संख्या होना चाहिए @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` अधिकतम {MAX_ITEMS} प्रविष्टियों का ऐरे होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..6b8edaec62 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7344,6 +7344,11 @@ axis Y Axis Y tengely @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one a `visibleWhen` ezt nevezi meg: `{other}`, de ez nem az ennél korábban megadott paraméterek egyike @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters a `visibleWhen` legfeljebb {MAX_CONDITIONS} paramétert nevezhet meg @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice a `visibleWhen` a(z) `{other}` értékeit veszi át, egy jelölőnégyzetét vagy egy választásét +@msg `step` is only for a parameter with a slider a `step` csak csúszkás paraméterhez adható meg +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} a csúszkához a `min` értéknek kisebbnek kell lennie a `max` értéknél, egy `int` csúszka tartományának pedig ±{EXACT_INT} között kell lennie +@msg a slider is only for `number` and `int` parameters csúszka csak `number` és `int` paraméterhez adható +@msg `step` must be a number above 0 and at most `max` minus `min` a `step` értéke 0-nál nagyobb és legfeljebb `max` mínusz `min` lehet +@msg an `int` parameter's `step` must be a whole number egy `int` paraméter `step` értékének egész számnak kell lennie @msg `visible` must be true or false `visible`: true vagy false kell @msg `{key}` must be a number from {_1} to {_2} `{key}`: {_1} és {_2} közötti szám kell @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}`: legfeljebb {MAX_ITEMS} elemű tömb kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..edd22bccda 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -472,6 +472,11 @@ @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` menyebut `{other}`, yang bukan parameter yang dideklarasikan sebelum parameter ini @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` menyebut paling banyak {MAX_CONDITIONS} parameter @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` menerima nilai `{other}`, dari kotak centang atau pilihan +@msg `step` is only for a parameter with a slider `step` hanya untuk parameter dengan penggeser +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} penggeser memerlukan `min` di bawah `max`, dan penggeser `int` memerlukan rentang dalam ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters penggeser hanya untuk parameter `number` dan `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` harus berupa angka di atas 0 dan paling banyak `max` dikurangi `min` +@msg an `int` parameter's `step` must be a whole number `step` parameter `int` harus berupa bilangan bulat @msg `visible` must be true or false `visible` harus true atau false @msg `{key}` must be a number from {_1} to {_2} `{key}` harus berupa angka dari {_1} sampai {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` harus berupa larik berisi paling banyak {MAX_ITEMS} entri diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c51dbd94ed 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6981,6 +6981,11 @@ axis Y Axis Asse Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` nomina `{other}`, che non è un parametro dichiarato prima di questo @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` nomina al massimo {MAX_CONDITIONS} parametri @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` accetta i valori di `{other}`, quelli di una casella di controllo o di una scelta +@msg `step` is only for a parameter with a slider `step` vale solo per un parametro con cursore +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} un cursore richiede `min` minore di `max`, e un cursore `int` un intervallo entro ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters un cursore vale solo per i parametri `number` e `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` deve essere un numero maggiore di 0 e al massimo `max` meno `min` +@msg an `int` parameter's `step` must be a whole number lo `step` di un parametro `int` deve essere un numero intero @msg `visible` must be true or false `visible` deve essere true o false @msg `{key}` must be a number from {_1} to {_2} `{key}` deve essere un numero da {_1} a {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` deve essere un array di al massimo {MAX_ITEMS} voci diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..c17c753429 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7056,6 +7056,11 @@ axis Y Axis Y 軸 @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` が指定した `{other}` は、このパラメーターより前に宣言されたパラメーターではありません @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` に指定できるパラメーターは {MAX_CONDITIONS} 個までです @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` が受け取るのは、チェックボックスか選択肢である `{other}` の値です +@msg `step` is only for a parameter with a slider `step` はスライダーのあるパラメーターにのみ指定できます +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} スライダーには `max` より小さい `min` が必要で、`int` のスライダーの範囲は ±{EXACT_INT} 以内である必要があります +@msg a slider is only for `number` and `int` parameters スライダーは `number` と `int` のパラメーターにのみ使えます +@msg `step` must be a number above 0 and at most `max` minus `min` `step` は 0 より大きく、`max` から `min` を引いた値以下の数値である必要があります +@msg an `int` parameter's `step` must be a whole number `int` パラメーターの `step` は整数である必要があります @msg `visible` must be true or false `visible` は true または false にしてください @msg `{key}` must be a number from {_1} to {_2} `{key}` は {_1} から {_2} の数値にしてください @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` は {MAX_ITEMS} 項目以下の配列にしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..358338736d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9462,6 +9462,11 @@ axis Y Axis Y ღერძი @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` ასახელებს `{other}`-ს, რომელიც ამაზე ადრე გამოცხადებული პარამეტრი არ არის @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` ასახელებს არაუმეტეს {MAX_CONDITIONS} პარამეტრს @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` იღებს `{other}`-ის მნიშვნელობებს, მოსანიშნი ველის ან არჩევანისას +@msg `step` is only for a parameter with a slider `step` მხოლოდ სლაიდერიანი პარამეტრისთვისაა +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} სლაიდერს სჭირდება `min`, რომელიც `max`-ზე ნაკლებია, ხოლო `int` სლაიდერს დიაპაზონი ±{EXACT_INT}-ის ფარგლებში +@msg a slider is only for `number` and `int` parameters სლაიდერი მხოლოდ `number` და `int` პარამეტრებისთვისაა +@msg `step` must be a number above 0 and at most `max` minus `min` `step` უნდა იყოს 0-ზე მეტი რიცხვი და არაუმეტეს `max` მინუს `min` +@msg an `int` parameter's `step` must be a whole number `int` პარამეტრის `step` მთელი რიცხვი უნდა იყოს @msg `visible` must be true or false `visible` უნდა იყოს true ან false @msg `{key}` must be a number from {_1} to {_2} `{key}` უნდა იყოს რიცხვი {_1}-დან {_2}-მდე @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` უნდა იყოს მასივი, არაუმეტეს {MAX_ITEMS} ელემენტით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..c6342c4d2a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6953,6 +6953,11 @@ axis Y Axis Y축 @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen`이 지정한 `{other}`은(는) 이 매개변수보다 앞에 선언된 매개변수가 아닙니다 @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen`에는 매개변수를 최대 {MAX_CONDITIONS}개까지 지정할 수 있습니다 @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen`은 확인란 또는 선택 항목인 `{other}`의 값을 받습니다 +@msg `step` is only for a parameter with a slider `step`은 슬라이더가 있는 매개변수에만 쓸 수 있습니다 +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} 슬라이더에는 `max`보다 작은 `min`이 필요하며, `int` 슬라이더의 범위는 ±{EXACT_INT} 이내여야 합니다 +@msg a slider is only for `number` and `int` parameters 슬라이더는 `number` 및 `int` 매개변수에만 쓸 수 있습니다 +@msg `step` must be a number above 0 and at most `max` minus `min` `step`은 0보다 크고 `max`에서 `min`을 뺀 값 이하인 숫자여야 합니다 +@msg an `int` parameter's `step` must be a whole number `int` 매개변수의 `step`은 정수여야 합니다 @msg `visible` must be true or false `visible`은(는) true 또는 false여야 합니다 @msg `{key}` must be a number from {_1} to {_2} `{key}`은(는) {_1}에서 {_2} 사이의 숫자여야 합니다 @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}`은(는) 항목이 최대 {MAX_ITEMS}개인 배열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..4955b377ad 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -436,6 +436,11 @@ liquify-list-end {0}, {1} {0} en {1} @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` noemt `{other}`, dat geen parameter is die vóór deze is gedeclareerd @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` noemt maximaal {MAX_CONDITIONS} parameters @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` neemt de waarden van `{other}`, een selectievakje of een keuzelijst +@msg `step` is only for a parameter with a slider `step` geldt alleen voor een parameter met een schuifregelaar +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} een schuifregelaar vereist dat `min` kleiner is dan `max`, en een `int`-schuifregelaar een bereik binnen ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters een schuifregelaar geldt alleen voor `number`- en `int`-parameters +@msg `step` must be a number above 0 and at most `max` minus `min` `step` moet een getal groter dan 0 zijn en hoogstens `max` min `min` +@msg an `int` parameter's `step` must be a whole number de `step` van een `int`-parameter moet een geheel getal zijn @msg `visible` must be true or false `visible` moet true of false zijn @msg `{key}` must be a number from {_1} to {_2} `{key}` moet een getal van {_1} tot {_2} zijn @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` moet een array van maximaal {MAX_ITEMS} items zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..9063b84bfb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7214,6 +7214,11 @@ axis Y Axis Oś Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` wskazuje `{other}`, który nie jest parametrem zadeklarowanym przed tym @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` wskazuje co najwyżej {MAX_CONDITIONS} parametrów @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` przyjmuje wartości `{other}`, czyli pola wyboru lub listy opcji +@msg `step` is only for a parameter with a slider `step` dotyczy tylko parametru z suwakiem +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} suwak wymaga `min` mniejszego niż `max`, a suwak `int` zakresu w granicach ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters suwak jest tylko dla parametrów `number` i `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` musi być liczbą większą od 0 i co najwyżej równą `max` minus `min` +@msg an `int` parameter's `step` must be a whole number `step` parametru `int` musi być liczbą całkowitą @msg `visible` must be true or false `visible` musi mieć wartość true lub false @msg `{key}` must be a number from {_1} to {_2} `{key}` musi być liczbą od {_1} do {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` musi być tablicą o co najwyżej {MAX_ITEMS} elementach diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..f20f0d9004 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7258,6 +7258,11 @@ axis Y Axis Eixo Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` nomeia `{other}`, que não é um parâmetro declarado antes deste @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` nomeia no máximo {MAX_CONDITIONS} parâmetros @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` aceita os valores de `{other}`, de uma caixa de seleção ou de uma escolha +@msg `step` is only for a parameter with a slider `step` só vale para um parâmetro com controle deslizante +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} um controle deslizante precisa de `min` menor que `max`, e um de `int` de um intervalo dentro de ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters um controle deslizante só vale para parâmetros `number` e `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` deve ser um número maior que 0 e no máximo `max` menos `min` +@msg an `int` parameter's `step` must be a whole number o `step` de um parâmetro `int` deve ser um número inteiro @msg `visible` must be true or false `visible` deve ser true ou false @msg `{key}` must be a number from {_1} to {_2} `{key}` deve ser um número de {_1} a {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` deve ser uma matriz de no máximo {MAX_ITEMS} entradas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..1657ca8814 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6981,6 +6981,11 @@ axis Y Axis Ось Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` указывает `{other}`, но это не параметр, объявленный раньше этого @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` указывает не более {MAX_CONDITIONS} параметров @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` принимает значения `{other}`, флажка или списка вариантов +@msg `step` is only for a parameter with a slider `step` допустим только для параметра с ползунком +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} ползунку нужен `min` меньше `max`, а ползунку `int` диапазон в пределах ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters ползунок допустим только для параметров `number` и `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` должен быть числом больше 0 и не больше `max` минус `min` +@msg an `int` parameter's `step` must be a whole number `step` параметра `int` должен быть целым числом @msg `visible` must be true or false `visible` должно быть true или false @msg `{key}` must be a number from {_1} to {_2} `{key}` должно быть числом от {_1} до {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` должно быть массивом не более чем из {MAX_ITEMS} элементов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..cd3840d1e6 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7371,6 +7371,11 @@ axis Y Axis Y-axel @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` anger `{other}`, som inte är en parameter som deklarerats före den här @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` anger högst {MAX_CONDITIONS} parametrar @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` tar värden från `{other}`, en kryssruta eller ett val +@msg `step` is only for a parameter with a slider `step` gäller bara en parameter med skjutreglage +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} ett skjutreglage kräver att `min` är mindre än `max`, och ett `int`-skjutreglage ett intervall inom ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters ett skjutreglage gäller bara `number`- och `int`-parametrar +@msg `step` must be a number above 0 and at most `max` minus `min` `step` måste vara ett tal över 0 och högst `max` minus `min` +@msg an `int` parameter's `step` must be a whole number `step` för en `int`-parameter måste vara ett heltal @msg `visible` must be true or false `visible` måste vara true eller false @msg `{key}` must be a number from {_1} to {_2} `{key}` måste vara ett tal från {_1} till {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` måste vara en array med högst {MAX_ITEMS} poster diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..57a4c47f81 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7431,6 +7431,11 @@ axis Y Axis Y ekseni @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` `{other}` adını veriyor, ancak bu, bundan önce bildirilmiş bir parametre değil @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` en fazla {MAX_CONDITIONS} parametre adı verir @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen`, bir onay kutusu veya seçim olan `{other}` parametresinin değerlerini alır +@msg `step` is only for a parameter with a slider `step` yalnızca kaydırıcısı olan bir parametre içindir +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} bir kaydırıcı için `min`, `max` değerinden küçük olmalı; bir `int` kaydırıcının aralığı ise ±{EXACT_INT} içinde olmalıdır +@msg a slider is only for `number` and `int` parameters kaydırıcı yalnızca `number` ve `int` parametreleri içindir +@msg `step` must be a number above 0 and at most `max` minus `min` `step`, 0'dan büyük ve en fazla `max` eksi `min` olan bir sayı olmalıdır +@msg an `int` parameter's `step` must be a whole number bir `int` parametresinin `step` değeri tam sayı olmalıdır @msg `visible` must be true or false `visible` true veya false olmalıdır @msg `{key}` must be a number from {_1} to {_2} `{key}` {_1} ile {_2} arasında bir sayı olmalıdır @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` en fazla {MAX_ITEMS} öğeli bir dizi olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..01a0c98178 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6963,6 +6963,11 @@ axis Y Axis Вісь Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` указує `{other}`, але це не параметр, оголошений раніше за цей @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` указує не більше {MAX_CONDITIONS} параметрів @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` приймає значення `{other}`, прапорця або списку варіантів +@msg `step` is only for a parameter with a slider `step` допустимий лише для параметра з повзунком +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} повзунку потрібен `min`, менший за `max`, а повзунку `int` діапазон у межах ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters повзунок допустимий лише для параметрів `number` і `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` має бути числом, більшим за 0 і не більшим за `max` мінус `min` +@msg an `int` parameter's `step` must be a whole number `step` параметра `int` має бути цілим числом @msg `visible` must be true or false `visible` має бути true або false @msg `{key}` must be a number from {_1} to {_2} `{key}` має бути числом від {_1} до {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` має бути масивом не більше ніж із {MAX_ITEMS} елементів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..dd3c11a1fd 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7010,6 +7010,11 @@ axis Y Axis Trục Y @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` nêu `{other}`, nhưng đó không phải là tham số được khai báo trước tham số này @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` nêu tối đa {MAX_CONDITIONS} tham số @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` nhận giá trị của `{other}`, là một hộp kiểm hoặc một lựa chọn +@msg `step` is only for a parameter with a slider `step` chỉ dành cho tham số có thanh trượt +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} thanh trượt cần `min` nhỏ hơn `max`, và thanh trượt `int` cần phạm vi trong khoảng ±{EXACT_INT} +@msg a slider is only for `number` and `int` parameters thanh trượt chỉ dành cho tham số `number` và `int` +@msg `step` must be a number above 0 and at most `max` minus `min` `step` phải là số lớn hơn 0 và tối đa bằng `max` trừ `min` +@msg an `int` parameter's `step` must be a whole number `step` của tham số `int` phải là số nguyên @msg `visible` must be true or false `visible` phải là true hoặc false @msg `{key}` must be a number from {_1} to {_2} `{key}` phải là một số từ {_1} đến {_2} @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` phải là một mảng có tối đa {MAX_ITEMS} mục diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..6fab818bd8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7191,6 +7191,11 @@ axis Y Axis Y 轴 @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` 指定了 `{other}`,但它不是在此参数之前声明的参数 @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` 最多指定 {MAX_CONDITIONS} 个参数 @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` 接受 `{other}` 的值,该参数须为复选框或选项 +@msg `step` is only for a parameter with a slider `step` 仅适用于带滑块的参数 +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} 滑块需要 `min` 小于 `max`,`int` 滑块的范围须在 ±{EXACT_INT} 以内 +@msg a slider is only for `number` and `int` parameters 滑块仅适用于 `number` 和 `int` 参数 +@msg `step` must be a number above 0 and at most `max` minus `min` `step` 必须是大于 0 且不超过 `max` 减 `min` 的数 +@msg an `int` parameter's `step` must be a whole number `int` 参数的 `step` 必须是整数 @msg `visible` must be true or false `visible` 必须是 true 或 false @msg `{key}` must be a number from {_1} to {_2} `{key}` 必须是 {_1} 到 {_2} 之间的数字 @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` 必须是最多 {MAX_ITEMS} 项的数组 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..63003da6b7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7012,6 +7012,11 @@ axis Y Axis Y 軸 @msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` 指定了 `{other}`,但它不是在此參數之前宣告的參數 @msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` 最多指定 {MAX_CONDITIONS} 個參數 @msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` 接受 `{other}` 的值,該參數須為核取方塊或選項 +@msg `step` is only for a parameter with a slider `step` 僅適用於帶滑桿的參數 +@msg a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT} 滑桿需要 `min` 小於 `max`,`int` 滑桿的範圍須在 ±{EXACT_INT} 以內 +@msg a slider is only for `number` and `int` parameters 滑桿僅適用於 `number` 和 `int` 參數 +@msg `step` must be a number above 0 and at most `max` minus `min` `step` 必須是大於 0 且不超過 `max` 減 `min` 的數 +@msg an `int` parameter's `step` must be a whole number `int` 參數的 `step` 必須是整數 @msg `visible` must be true or false `visible` 必須是 true 或 false @msg `{key}` must be a number from {_1} to {_2} `{key}` 必須是介於 {_1} 到 {_2} 之間的數字 @msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` 必須是最多 {MAX_ITEMS} 項的陣列 diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 52b36b4535..8976502aa4 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -1377,6 +1377,7 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let t = Tokens::get(ui.ctx()); let params = editor_params(e); let mut change: Option<(String, Value)> = None; + let mut slid: Option<(String, Value, widgets::Live)> = None; let mut edit = false; let built_in = built_in_effect(&e.id); // A plug-in effect's parameters are labelled, measured and shown as its manifest says. @@ -1451,6 +1452,18 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } return; } + // A plug-in's number that asks for a slider shows it before the number, as its + // dialog does; the number shows the value a drag in progress reached. + let dragged; + let v = match manifest.and_then(|m| m.param(key)).and_then(|p| Some((p, p.ui.slider_range(&p.spec)?))) { + Some((p, range)) => { + let (shown, edit) = param_slider_edit(ui, (item, k, key.as_str()), p, v, range); + slid = edit.map(|(value, phase)| (key.clone(), value, phase)).or(slid.take()); + dragged = shown; + &dragged + } + None => v, + }; match v { Value::Bool(b) => { if widgets::check_box(ui, &label, *b, true) { @@ -1461,11 +1474,13 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let (x, id) = (n.as_f64().unwrap_or(0.0), ("fx", item, k, key.as_str())); let suffix = ui_keys.and_then(|u| u.unit.as_deref()).map(crate::dialogs::unit_suffix).unwrap_or_default(); let nx = if vectorcraft_effects::is_length(&e.id, key, relative) { - widgets::num_field(ui, id, Some(x), unit, 70.0) + widgets::num_field(ui, id, Some(x), unit, NUMBER_W) } else if let Some(range) = vectorcraft_effects::raster_px_range(&e.id, key) { - widgets::range_field_named(ui, id, None, x, range, &crate::dialogs::unit_suffix("px"), 2, 70.0) + widgets::range_field_named(ui, id, None, x, range, &crate::dialogs::unit_suffix("px"), 2, NUMBER_W) } else { - widgets::plain_field(ui, id, x, &suffix, 2, 70.0) + // A plug-in number with a slider shows the places its slider moves to. + let places = manifest.and_then(|m| m.param(key)).map_or(2, crate::dialogs::field_places); + widgets::plain_field(ui, id, x, &suffix, places, NUMBER_W) }; if let Some(nx) = nx { change = Some((key.clone(), json!(nx))); @@ -1496,11 +1511,71 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: if let Some((key, v)) = change { app.run("effect.setParams", aligned(app, json!({"item": item, "index": k, "params": {key: v}}))).ok(); } + if let Some((key, v, phase)) = slid { + let p = aligned(app, json!({"item": item, "index": k, "params": {key: v}})); + super::live_run(app, "Effect Options", "effect.setParams", p, phase); + } if edit { app.run("effect.dialog", aligned(app, json!({"effect": e.id, "index": k, "item": item}))).ok(); } } +/// Width of a number field in [`effect_editor`]. +const NUMBER_W: f32 = 70.0; + +/// The narrowest a plug-in parameter's slider gets in [`effect_editor`]. +const SLIDER_MIN_W: f32 = 24.0; + +/// What a drag on the slider of a plug-in effect's parameter in [`effect_editor`] keeps between +/// frames: the value it reached, and when it last previewed. +#[derive(Clone, Debug, Default)] +struct ParamSlide { + value: Option, + preview: crate::dialogs::SlidePreview, +} + +/// The slider of plug-in parameter `p` with value `v`, which asks for one, over `range`, in the row +/// `id` (appearance item, effect index and parameter name) → the value the row's number shows (a +/// drag's in progress, else `v`) and the edit to run with its phase ([`super::live_run`]): a click +/// or key as one undo step, and a drag previewed on the canvas about ten times a second +/// ([`crate::dialogs::SlidePreview`]) and kept as one undo step when it ends. +fn param_slider_edit( + ui: &mut Ui, + id: (Option, usize, &str), + p: &vectorcraft_plugins::Param, + v: &Value, + range: std::ops::RangeInclusive, +) -> (Value, Option<(Value, widgets::Live)>) { + let memory = egui::Id::unique(("fx-slide", id)); + let mut slide: ParamSlide = ui.data(|d| d.get_temp(memory)).unwrap_or_default(); + let cur = slide.value.clone().unwrap_or_else(|| v.clone()); + // The slider takes the room the row has left after the number field after it, so a narrow + // panel keeps both in view. + let room = ui.available_width() - NUMBER_W - 2.0 * ui.spacing().item_spacing.x; + let width = room.clamp(SLIDER_MIN_W, crate::dialogs::PARAM_SLIDER_WIDTH); + let (new, resp) = crate::dialogs::plugin_slider(ui, ("fx-slider", id), &p.spec, &cur, range, p.ui.step, width); + let edit = if resp.drag_stopped() { + // The value the drag ended on, kept even when its last preview waited. + new.or(std::mem::take(&mut slide).value).map(|value| (value, widgets::Live::Released)) + } else if resp.dragged() { + let changed = new.is_some(); + slide.value = new.or(slide.value.take()); + let due = slide.preview.due_now(ui, true, changed) == Some(true); + slide.value.clone().filter(|_| due).map(|value| (value, widgets::Live::Dragging)) + } else { + new.map(|value| (value, widgets::Live::Released)) + }; + let shown = slide.value.clone().unwrap_or(cur); + ui.data_mut(|d| { + if slide.value.is_some() { + d.insert_temp(memory, slide); + } else { + d.remove_temp::(memory); + } + }); + (shown, edit) +} + /// The values [`effect_editor`] lists: the effect's own values over its defaults, with earlier keys /// in their current form (Scribble's one `variation` as its Path Overlap and Spacing variations). fn editor_params(e: &Effect) -> serde_json::Map { diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 4816d0838d..8efe31adfb 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -461,6 +461,98 @@ fn a_plug_in_effect_s_editor_follows_its_manifest() { app.run("plugin.remove", json!({"id": "test.ui.inlinekeys"})).unwrap(); } +/// A plug-in effect's number that asks for a slider shows one in the editor. A drag previews on +/// the canvas while it lasts, fewer times than it has frames, and ends as one undo step with the +/// value it reached; an arrow key then moves the value by one step as another undo step. +#[test] +fn a_plug_in_slider_in_the_editor_previews_a_drag_and_keeps_it_as_one_step() { + use egui::accesskit::Role; + use vectorcraft_plugins::wat as tpl; + let params = r#"{"amount":{"type":"number","min":0,"max":100,"default":10,"label":"Amount","widget":"slider"}, + "count":{"type":"int","min":0,"max":20,"default":4,"label":"Count","widget":"slider","step":2}, + "odd":{"type":"number","min":0,"max":100,"default":12,"label":"Odd","widget":"slider","step":5}}"#; + let src = tpl::module(&tpl::manifest("test.ui.inlineslider", "effect", params), tpl::ECHO, "", 1); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.inlineslider"})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ap-fx-open-None-0", true); + // Frames a sixtieth of a second apart, which a drag's previews are coarser than. + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let params = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params.clone(); + let (undo, applied) = (app.session.doc().unwrap().history.undo.len(), params(&app)); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + // Showing the sliders leaves the effect alone, its value off Odd's grid included. + assert_eq!((app.session.doc().unwrap().history.undo.len(), params(&app)), (undo, applied), "drawing the editor changed the effect"); + let sliders: Vec<_> = nodes.iter().filter(|(_, n)| n.role() == Role::Slider).map(|(_, n)| n.clone()).collect(); + assert_eq!(sliders.len(), 3, "every number that asks for one has a slider"); + // Each slider is named by its row's label. + let label_of = + |l: &egui::accesskit::NodeId| nodes.iter().find(|(nid, _)| nid == l).and_then(|(_, n)| n.label().or(n.value())).unwrap_or_default(); + for name in ["Amount", "Count", "Odd"] { + let named = sliders.iter().any(|n| n.labelled_by().iter().any(|l| label_of(l).starts_with(name))); + assert!(named, "no slider is named by {name}"); + } + // The number fields after the sliders stay inside the 320-point panel. + let fields: Vec<_> = nodes.iter().filter(|(_, n)| n.role() != Role::Slider && matches!(n.value(), Some("10" | "4" | "12"))).collect(); + assert!(fields.len() >= 3, "every number has a field"); + for (_, n) in fields { + let right = n.bounds().expect("the field is laid out").x1; + assert!(right <= 320.0, "the {:?} field ends at {right}, past the panel", n.value()); + } + let amount = sliders.iter().find(|n| n.numeric_value() == Some(10.0)).expect("Amount's slider shows its value"); + let rail = amount.bounds().expect("the slider is laid out"); + let at = |x: f64| egui::pos2((rail.x0 + x * (rail.x1 - rail.x0)) as f32, ((rail.y0 + rail.y1) / 2.0) as f32); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, vec![egui::Event::PointerMoved(at(0.1))]); + frame(&mut app, vec![button(at(0.1), true)]); + // Thirty frames of dragging right, each to a new value. + let mut seen = vec![]; + for i in 1..=30 { + frame(&mut app, vec![egui::Event::PointerMoved(at(0.1 + 0.025 * i as f64))]); + let shown = params(&app)["amount"].clone(); + if seen.last() != Some(&shown) { + seen.push(shown); + } + } + assert!(seen.len() > 2 && seen.len() < 15, "the canvas showed {} values in 30 frames: {seen:?}", seen.len()); + frame(&mut app, vec![button(at(0.85), false)]); + frame(&mut app, vec![]); + let kept = params(&app)["amount"].as_f64().unwrap(); + assert!(kept > 70.0 && kept <= 100.0, "the value the drag ended on: {kept}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "the drag is one undo step"); + assert!(!app.session.in_interaction(), "the drag's interaction ended"); + // Count's slider: focused, an arrow moves it by its step of 2, as one more undo step. + let nodes = frame(&mut app, vec![]); + let count = nodes.iter().find(|(_, n)| n.role() == Role::Slider && n.numeric_value() == Some(4.0)).map(|(nid, _)| *nid).unwrap(); + let focus = egui::accesskit::ActionRequest { + action: egui::accesskit::Action::Focus, + target_tree: egui::accesskit::TreeId::ROOT, + target_node: count, + data: None, + }; + frame(&mut app, vec![egui::Event::AccessKitActionRequest(focus)]); + frame(&mut app, vec![]); + let right = egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![right]); + frame(&mut app, vec![]); + assert_eq!(params(&app)["count"], json!(6)); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2); + app.run("plugin.remove", json!({"id": "test.ui.inlineslider"})).unwrap(); +} + /// Glass with a loaded texture lists Loaded Texture in its Texture menu, as its dialog does. #[test] fn the_effect_editor_lists_a_loaded_glass_texture() { diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..eabd0d9235 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -600,10 +600,18 @@ declares them still installs there: | `help` | Shows what the parameter does when the pointer rests on its label (1–1,000 characters; line breaks allowed). | | `helpUrl` | Opens this `https://` page (at most 512 bytes) from a button after the field. | | `visibleWhen` | `{"pattern": ["lines", "crosshatch"], "outline": [true]}` shows the parameter only while each parameter it names (a checkbox or a choice declared before it) has one of the values listed and is shown itself. | +| `widget` | `"slider"` shows a slider over `min..max` before the number field of a `number` or `int` parameter. Its range needs `min` below `max`, and an `int`'s range lies within ±9,007,199,254,740,992. On any other parameter, or with another value, the manifest is refused at install. | +| `step` | How far the slider moves the value at a time, counted from `min`: a number above 0 and at most `max` minus `min`, and a whole number for an `int`. Without it, a slider moves a `number` to two decimal places (more when `max` minus `min` is under 1) and an `int` by 1. The number field shows as many decimal places as the slider moves to, from 2 to 6. A value off the slider's steps, typed in the field or set by a script, is kept until the slider is moved. `step` without `"widget": "slider"` is refused. | A hidden parameter still goes to the plug-in with its value: what the dialog showed never changes a run. The filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's -parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the parameters without sections or help buttons. +parameters uses `label`, `unit`, `help`, `visibleWhen`, `widget` and `step`, and lists the parameters without +sections or help buttons. + +The arrow keys move a slider by its `step`, or by 1 for an `int` without one, and screen readers read it as a slider +named by the parameter's label. While a slider is dragged, the preview of a filter or live effect runs the plug-in +at most about ten times a second, on the latest value, and the value the drag ends on always previews. In the +Appearance panel, a drag is one undo step. ### Input diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..1c313ba64f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2647,6 +2647,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. +- **Plug-in number parameters as sliders (G17):** a `number` or `int` parameter with `"widget": "slider"` shows a slider over its range before its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor, moving by an optional `step` counted from `min`; the manifest is refused at install when the parameter cannot have one. A drag previews the plug-in about ten times a second and ends on its last value, as one undo step in the Appearance panel. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance/tests.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. - **Live-effect plug-ins before a fill's or stroke's own 3D effect:** a live effect listed before a fill's or stroke's own Extrude & Bevel, Inflate or Rotate effect is given `_context.item` for that fill or stroke (`{"fill": i}` or `{"stroke": i}`), not `"object"`, in the drawn art, in the 3D meshes and in Expand as Wireframes; a deferred stage there is listed at that fill's or stroke's place. Regressions: `crates/effects/src/tests/solidcontext.rs`. Scores and hours unchanged. - **Filter plug-ins set effects and stroke styles (G17):** a filter is given each object's effect records and its strokes' `join`, `cap` and `miterLimit`, and may return them; the records are admitted as `effect.apply` admits them (a known effect or installed live-effect plug-in, parameters it takes, one 3D effect that fits, no texture read from a file), and one refused refuses the output. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. From 8e3e7239aed7ed02cb9e8d616078b6c6f8a6bf18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:23:05 -0800 Subject: [PATCH 018/107] Corners: a relative radius is a percentage of each corner's own maximum With Relative chosen, OK in Corners turned the percentage into a length from the first picked corner's maximum and sent that one length for every picked corner. object.setLiveShape then stored it as a fraction of each corner's own maximum, so corners with a different maximum (a star's points and its inner corners) were rounded more or less than the percentage shown. OK now works out the length for each corner from its own maximum. Corners that get the same length share one object.setLiveShape; when they differ, the calls run as one command.batch, a single undo step. The ui.corners params text and docs/mcp.md name the relativeRadii field and the percentage. --- crates/ui-egui/src/dialogs/corners.rs | 93 +++++++++++++++++++++---- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 +- 3 files changed, 82 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index e5300fe5e4..7b95c05685 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -129,23 +129,53 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(v) = d.fields.get("relativeRadii") { p["relativeRadii"] = v.clone(); } - if d.fields.contains_key("radius") { - let relative = d.fields.get("relativeRadii").and_then(|v| v.as_bool()).unwrap_or(false); - let mut r = d.f64("radius", 0.0); - if relative { - let id = NodeId(d.fields.get("id").and_then(|v| v.as_u64()).unwrap_or(0)); - let st = app.session.active().ok_or("no document")?; - if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) { - let corners: BTreeSet = serde_json::from_value(d.fields.get("corners").cloned().unwrap_or(json!([]))).unwrap_or_default(); - if let Some(k) = corners.iter().next() { - let max = lc.corner(*k).map(|c| c.max_radius()).unwrap_or(0.0); - r = (r / 100.0).clamp(0.0, 1.0) * max; - } + if !d.fields.contains_key("radius") { + return run_and_close(app, "object.setLiveShape", p); + } + let relative = d.fields.get("relativeRadii").and_then(|v| v.as_bool()).unwrap_or(false); + let r = d.f64("radius", 0.0); + if !relative { + p["radius"] = json!(r); + return run_and_close(app, "object.setLiveShape", p); + } + // Relative: the percentage is of each corner's own maximum, so corners with different + // maximums (a star's points and its inner corners) get different lengths. Corners of the + // same length share one `object.setLiveShape`; several run as one undo step. + let id = NodeId(d.fields.get("id").and_then(|v| v.as_u64()).unwrap_or(0)); + let st = app.session.active().ok_or("no document")?; + let mut lengths: Vec<(f64, Vec)> = vec![]; + if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) { + let corners: BTreeSet = serde_json::from_value(d.fields.get("corners").cloned().unwrap_or(json!([]))).unwrap_or_default(); + for k in corners { + let len = (r / 100.0).clamp(0.0, 1.0) * lc.corner(k).map(|c| c.max_radius()).unwrap_or(0.0); + match lengths.iter_mut().find(|(l, _)| (*l - len).abs() < 1e-9) { + Some((_, ks)) => ks.push(k), + None => lengths.push((len, vec![k])), } } - p["radius"] = json!(r); } - run_and_close(app, "object.setLiveShape", p) + match &lengths[..] { + [] => { + p["radius"] = json!(r); + run_and_close(app, "object.setLiveShape", p) + } + [(len, _)] => { + p["radius"] = json!(len); + run_and_close(app, "object.setLiveShape", p) + } + _ => { + let commands: Vec = lengths + .iter() + .map(|(len, ks)| { + let mut step = p.clone(); + step["corners"] = json!(ks); + step["radius"] = json!(len); + json!({"command": "object.setLiveShape", "params": step}) + }) + .collect(); + run_and_close(app, "command.batch", json!({"label": "Live Shape", "commands": commands})) + } + } } #[cfg(test)] @@ -290,4 +320,39 @@ mod tests { assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))); assert_eq!(crate::panels::corner_radius(&app, &n), Some(5.0)); } + + /// Relative rounding gives each corner the percentage of its own maximum: a star's point and + /// the inner corner beside it differ, and OK rounds both as one undo step. + #[test] + fn relative_radius_is_a_percentage_of_each_corners_own_maximum() { + let (mut app, _) = app(); + let id = app.run("shape.star", json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("object.setLiveShape", json!({"id": id, "radius": 1})).unwrap(); + let lc = |app: &VectorcraftApp| { + let n = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().clone(); + let c = LiveCorners::of(&n).unwrap(); + (c.radii_relative(), c.radius(0), c.radius(1), c.corner(0).unwrap().max_radius(), c.corner(1).unwrap().max_radius()) + }; + let (_, _, _, max0, max1) = lc(&app); + assert!((max0 - max1).abs() > 1.0, "the corners' maximums differ: {max0} and {max1}"); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let n = steps(&app); + app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("relativeRadii".into(), json!(true)); + d.fields.insert("radius".into(), json!(50)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let (relative, f0, f1, _, _) = lc(&app); + assert!(relative); + assert!((f0 - 0.5).abs() < 1e-9 && (f1 - 0.5).abs() < 1e-9, "stored fractions: {f0} and {f1}"); + assert_eq!(steps(&app), n + 1, "one undo step"); + // The same values again change nothing and record no step. + app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(50)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), n + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(!lc(&app).0, "undo brings back absolute radii"); + } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..bee7c08663 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1533,7 +1533,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.corners", "Corners…", "", - "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), relativeRadii (bool), radius (pt, or with relativeRadii a percentage of each corner's own maximum); double-clicking a corner widget opens it too): OK runs object.setLiveShape, as one command.batch undo step when relative radii give the corners different lengths", ), ( "ui.simplifyAuto", diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..1b2c4d7945 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7793,7 +7793,8 @@ the Direct Selection tool those of any path. `rectanglesOnly: true` sets them on alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the selection, so an action that records them acts on the rectangles selected when it plays). Several objects each with their own corners are one call: `items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`, -dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). +dialog `corners`: `kind`, `relativeRadii`, `radius`, a percentage of each corner's own maximum with `relativeRadii`; OK runs +`object.setLiveShape`, as one undo step for corners whose maximums differ). `view.shapeWidgets {on?}` (desktop app, the Hide Shape Widgets and Show Shape Widgets button in the Control bar of the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools) hides or shows the corner widgets of selected live rectangles and polygons, the pie widgets of live ellipses and the side widget of a live polygon, for the Selection tool From ed50dd06f46547e753d60a9289537d8f67175782 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:24:01 -0800 Subject: [PATCH 019/107] Plug-ins: filters at API level 3 change type, images and symbol instances A filter's manifest may list `writes`, the kinds among its `inputs` it may change, at `api` 3 with `doc.write` in `permissions`. Such a filter returns those objects with the fields it changes: type's runs and paragraph styles, an image's transform and opacity, an instance's transform and symbol (one already in the document), and each one's name. Every value is checked as the input's limits and a path's paints are; any other changed field, or a value out of range, refuses the run naming the object and the field, and the document stays as it was. The changes of one run are one undo step, and an output that changes nothing records no undo step for any filter. Images are now also given with their opacity. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/plugin.rs | 65 +++-- crates/engine/src/tests/plugins.rs | 123 +++++++++- crates/plugins/src/manifest.rs | 115 ++++++++- crates/plugins/src/objects.rs | 88 +++++-- crates/plugins/src/objects/tests.rs | 293 +++++++++++++++++++++++ crates/plugins/src/objects/writes.rs | 342 +++++++++++++++++++++++++++ crates/plugins/src/permissions.rs | 7 +- crates/ui-egui/src/dialogs/tests.rs | 1 + docs/mcp.md | 7 +- docs/plugins.md | 63 ++++- docs/target-app-parity.md | 1 + 11 files changed, 1045 insertions(+), 60 deletions(-) create mode 100644 crates/plugins/src/objects/writes.rs diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..6b34d42eea 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -42,12 +42,14 @@ //! //! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type, //! images or symbol instances of those kinds, to read only: its output must return each of them -//! unchanged ([`objects::decode_output_with`]). +//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds +//! among them it may change: type's runs and paragraph styles, an image's transform and opacity, +//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]). use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{Effect, Node}; +use vectorcraft_doc::{Effect, Node, NodeKind}; use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode}; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; @@ -101,6 +103,9 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.writes.is_empty() { + v["writes"] = json!(m.writes); + } if m.paint_output { v["paintOutput"] = json!(true); } @@ -330,11 +335,12 @@ impl FilterRun { /// Applies the plug-in's `output` to the active document as one undo step: its objects, and what /// it keeps with the document from now on. An output its permissions don't allow, and one that /// changes or leaves out a read-only object it was given, is refused, and the document stays as - /// it was. + /// it was. An output that changes nothing records no undo step; one that only selects other + /// objects selects them without one. fn finish(self, s: &mut Session, output: &[u8]) -> Result { let m = self.plugin.manifest(); let may = m.permissions(); - let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?; + let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?; if out.document_data.is_some() && !may.contains(&Permission::State) { return Err(not_granted(&m.name, Permission::State)); } @@ -342,18 +348,41 @@ impl FilterRun { // A command's undo step is named after the command. let label = self.label(); let (inputs, parent) = (self.inputs, self.parent); - let ids = s.edit(&label, |d, sel| { - let before = (!may_write).then(|| d.layers.clone()); - let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; - if before.is_some_and(|b| b != d.layers) { - return Err(not_granted(&m.name, Permission::DocWrite)); - } - if let Some(data) = out.document_data { - d.set_plugin_data(&m.id, data); - } - sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable))); - Ok(ids) - })?; + // Typing in progress is kept first, as `s.edit` keeps it, so the copy below holds it. + if !s.previewing && super::typing_in_progress(s) { + super::settle_interaction(s)?; + } + let st = s.doc()?; + let mut d = (*st.doc).clone(); + let mut sel = st.selection.clone(); + let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; + if !may_write && d.layers != st.doc.layers { + return Err(not_granted(&m.name, Permission::DocWrite)); + } + // Type whose text the output changed is laid out again. + let retyped: Vec = ids + .iter() + .copied() + .filter(|&id| match (d.node(id).map(|n| &n.kind), st.doc.node(id).map(|n| &n.kind)) { + (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, + _ => false, + }) + .collect(); + super::typecmd::refresh_bounds_of(&mut d, &retyped); + if let Some(data) = out.document_data { + d.set_plugin_data(&m.id, data); + } + sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable))); + let (changed, reselected) = (d != *st.doc, sel != st.selection); + if changed { + s.edit(&label, |doc, selection| { + *doc = d; + *selection = sel; + Ok(()) + })?; + } else if reselected { + s.select(|_, selection| *selection = sel)?; + } let mut out = json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::>()}); if let Some(cmd) = &self.command { out["command"] = json!(cmd.id); @@ -1270,7 +1299,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1288,7 +1317,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs and 256 KiB of text; a style of its own needs a font family and a size of 0.1 to 1296 pt) and text.paragraphs (one style per paragraph), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. An output that changes nothing records no undo step. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", has_doc, run ), diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..dbb864b3b9 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3858,6 +3858,116 @@ fn read_only_kind_field_and_omission_refuse_without_undo() { assert!(e.contains("`inputs` needs `api` 2"), "{e}"); } +/// A filter at `api` 3 that lists type, images and symbol instances in `writes` changes a type +/// object's characters, an image's transform and opacity and the symbol an instance shows, as one +/// undo step that undo takes back and redo gives again, and the changes are kept when the document +/// is saved and opened. An echo records no undo step; a refused write, and a write by a filter that +/// lists the kinds in `inputs` alone, leave the document and the history as they were. +#[test] +fn a_filter_that_writes_type_images_and_instances_is_one_undo_step() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeKind, Symbol}; + use vectorcraft_geom::Affine; + let mut s = session(); + let r = rect(&mut s, 10.0, "#ff0000"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap()); + let (mut image, mut inst) = (NodeId(0), NodeId(0)); + s.edit("Set up", |d, _| { + for name in ["Sun", "Moon"] { + let art = Arc::new(Node::path(d.alloc_id(), triangle(), Appearance::default())); + d.symbols.push(Symbol { name: name.into(), art, dynamic: false }); + } + let layer = d.layers[0].id; + let im = vectorcraft_doc::ImageObject { + key: "none".into(), + width: 4, + height: 2, + xf: Affine::translate((100.0, 20.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + image = d.insert(Some(layer), usize::MAX, n).unwrap(); + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Sun".into(), xf: Affine::translate((200.0, 20.0)) }); + inst = d.insert(Some(layer), usize::MAX, n).unwrap(); + Ok(()) + }) + .unwrap(); + let manifest = |id: &str, writes: &str| { + format!( + r#"{{"id":"{id}","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"]{writes}}}"# + ) + }; + let all = r#","writes":["type","image","symbolInstance"]"#; + let put = |s: &mut Session, src: &str| { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) + }; + let p = |id: &str| json!({"id": id, "ids": [r.0, t.0, image.0, inst.0]}); + let style = match &node(&s, t).kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let edits = json!({"objects": [ + {"id": r.0}, + {"id": t.0, "text": {"runs": [{"text": "Bye now", "style": style}]}}, + {"id": image.0, "transform": [2, 0, 0, 2, 50, 60], "opacity": 0.25}, + {"id": inst.0, "symbolId": "Moon"}, + ]}); + let writer = "test.engine.writes.revise"; + let listed = put(&mut s, &tpl::returning(&manifest(writer, all), &edits.to_string())); + assert_eq!((&listed["api"], &listed["writes"]), (&json!(3), &json!(["type", "image", "symbolInstance"]))); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + assert_eq!(run(&mut s, "plugin.run", p(writer))["ids"], json!([r.0, t.0, image.0, inst.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let check = |d: &vectorcraft_doc::Document| { + let NodeKind::Text(x) = &d.node(t).unwrap().kind else { panic!("type") }; + assert_eq!(x.plain_text(), "Bye now"); + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("image") }; + assert_eq!((im.xf, d.node(image).unwrap().opacity), (Affine::new([2.0, 0.0, 0.0, 2.0, 50.0, 60.0]), 0.25)); + assert!( + matches!(&d.node(inst).unwrap().kind, NodeKind::SymbolInstance { symbol, xf } if symbol == "Moon" && *xf == Affine::translate((200.0, 20.0))) + ); + }; + let after = s.doc().unwrap().doc.clone(); + check(&after); + assert!(matches!(&after.node(t).unwrap().kind, NodeKind::Text(x) if x.cached_bounds.is_some()), "the type is laid out again"); + assert_eq!(s.doc().unwrap().selection.objects, [r, t, image, inst]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc().unwrap().doc.layers, after.layers); + check(&vectorcraft_format::load(&vectorcraft_format::save(&after, false)).unwrap()); + // An echo changes nothing and records no undo step. + let echo = "test.engine.writes.echo"; + put(&mut s, &tpl::module(&manifest(echo, all), tpl::ECHO, "", 1)); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + run(&mut s, "plugin.run", p(echo)); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "an echo records no undo step"); + // Refused writes leave the document and the history as they were. + let bad = "test.engine.writes.bad"; + for (writes, output, says) in [ + ( + all, + json!({"objects": [{"id": r.0}, {"id": t.0}, {"id": image.0}, {"id": inst.0, "symbolId": "Nowhere"}]}), + format!("objects[3] (id {}).symbolId: 'Nowhere' is not a symbol in this document", inst.0), + ), + ( + all, + json!({"objects": [{"id": r.0}, {"id": t.0}, {"id": image.0, "opacity": 1.5}, {"id": inst.0}]}), + format!("objects[2] (id {}).opacity: must be a number from 0 to 1", image.0), + ), + ("", edits.clone(), format!("objects[1] (id {}): read-only field 'text.kind' changed", t.0)), + ] { + put(&mut s, &tpl::returning(&manifest(bad, writes), &output.to_string())); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p(bad)).unwrap_err().to_string(); + assert!(e.contains(&says), "{says}: {e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "{output}"); + } +} + /// A run past its memory budget fails before the plug-in starts, with the document and undo /// history as they were: a read-only object whose other fields don't fit, a path and a compound /// path that don't fit, and parameters past the input's half of the cap, with objects selected or @@ -5299,13 +5409,14 @@ fn deferred_move(s: &mut Session) -> NodeId { r } -/// The rectangle a run named `label` during [`deferred_move`] left: moved, with the interaction -/// ended and the move an undo step of its own before the run's. -fn assert_moved_once(s: &Session, r: NodeId, label: &str) { +/// The rectangle an echoing run during [`deferred_move`] left: moved, with the interaction ended and +/// the move the last undo step, since the run handed the rectangle back as it was and so records +/// none. +fn assert_moved_once(s: &Session, r: NodeId) { assert!(!s.in_interaction()); assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle"); let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); - assert_eq!(labels, [label, "Move"]); + assert_eq!(labels, ["Move", "Rectangle"]); } /// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies @@ -5317,7 +5428,7 @@ fn a_filter_that_calls_commands_is_given_a_deferred_move() { install_echo_calling(&mut s, id, "[]"); let r = deferred_move(&mut s); run(&mut s, "plugin.run", json!({"id": id})); - assert_moved_once(&s, r, &format!("Test {id}")); + assert_moved_once(&s, r); run(&mut s, "plugin.remove", json!({"id": id})); } @@ -5330,6 +5441,6 @@ fn a_plugin_command_that_calls_commands_is_given_a_deferred_move() { install_echo_calling(&mut s, id, r#"[{"id":"same","label":"Same"}]"#); let r = deferred_move(&mut s); run(&mut s, &format!("plugin.{id}.same"), json!({})); - assert_moved_once(&s, r, "Same"); + assert_moved_once(&s, r); run(&mut s, "plugin.remove", json!({"id": id})); } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..6aafef6779 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; -use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; +use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission, WRITES_API}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -326,6 +326,11 @@ pub struct Manifest { /// lists them. Left out or empty, it is given paths and compound paths alone. #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")] pub inputs: Vec, + /// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at + /// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or + /// empty, every kind it reads stays read-only. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "write_names")] + pub writes: Vec, /// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest. #[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")] pub params: Vec<(String, Param)>, @@ -377,6 +382,7 @@ impl Manifest { api: 1, permissions: None, inputs: Vec::new(), + writes: Vec::new(), params: Vec::new(), extensions: Vec::new(), budget: Budget::Light, @@ -422,6 +428,7 @@ impl Manifest { return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}"))); } self.validate_inputs()?; + self.validate_writes()?; if self.paint_output && (self.kind != Kind::Effect || self.api < 2) { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } @@ -518,6 +525,37 @@ impl Manifest { Ok(()) } + /// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at + /// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`. + fn validate_writes(&self) -> Result<()> { + if self.writes.is_empty() { + return Ok(()); + } + if self.kind != Kind::Filter { + return Err(Error::Manifest("only a filter declares `writes`".into())); + } + for (i, name) in self.writes.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if InputKind::parse(name).is_none() { + return Err(Error::Manifest(format!("`writes` names an unknown object kind `{shown}`: use type, image or symbolInstance"))); + } + if self.writes.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`writes` lists `{shown}` twice"))); + } + if !self.inputs.contains(name) { + return Err(Error::Manifest(format!("`writes` lists `{shown}`, which `inputs` doesn't list"))); + } + } + if self.api < WRITES_API { + return Err(Error::Manifest(format!("`writes` needs `api` {WRITES_API} or later"))); + } + let listed = |p: Permission| self.permissions.as_ref().is_some_and(|names| names.iter().any(|n| n == p.name())); + if !listed(Permission::DocWrite) { + return Err(Error::Manifest("`writes` needs the permission `doc.write`".into())); + } + Ok(()) + } + /// A filter or a live effect lists at most [`MAX_COMMANDS`] commands, each with a distinct /// id, a printable label and parameters declared as the manifest's own are. A heavy filter /// lists none. The error names the command: its id, or its place in the list. @@ -564,6 +602,11 @@ impl Manifest { self.inputs.iter().filter_map(|n| InputKind::parse(n)).collect() } + /// The kinds among those it reads that it may change (`writes`). + pub fn write_kinds(&self) -> Vec { + self.writes.iter().filter_map(|n| InputKind::parse(n)).collect() + } + /// An exporter or an importer lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16 /// lower-case letters and digits; other kinds list none. fn validate_extensions(&self) -> Result<()> { @@ -733,6 +776,16 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads the `commands` list one entry at a time from the manifest itself, so each command's /// `params` keep their declaration order and a repeated parameter is refused. A malformed entry /// is an error that names it (its id when the id comes before the fault, otherwise its place in @@ -1119,7 +1172,7 @@ mod tests { (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"), - (r#"{"id":"a","name":"x","kind":"filter","api":3}"#, "`api` is 3"), + (r#"{"id":"a","name":"x","kind":"filter","api":4}"#, "`api` is 4"), (r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"), (r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"), ] { @@ -1175,6 +1228,64 @@ mod tests { assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice")); } + /// A filter at `api` 3 may change the kinds it reads that it lists in `writes`, each once, with + /// `doc.read` and `doc.write`. Left out or empty, everything it reads stays read-only and the key + /// isn't written back. Anything else is refused naming `writes`. + #[test] + fn a_filter_at_api_3_lists_the_kinds_it_writes() { + let m = Manifest::parse( + br#"{"id":"org.example.revise","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"],"writes":["type","image","symbolInstance"]}"#, + ) + .unwrap(); + assert_eq!(m.write_kinds(), InputKind::ALL); + assert_eq!(serde_json::to_value(&m).unwrap()["writes"], json!(["type", "image", "symbolInstance"])); + let some = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["image","type"],"writes":["image"]}"#, + ) + .unwrap(); + assert_eq!((some.input_kinds(), some.write_kinds()), (vec![InputKind::Image, InputKind::Type], vec![InputKind::Image])); + for none in [ + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"inputs":["type"]}"#, + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":[]}"#, + r#"{"id":"a","name":"x","kind":"filter","writes":null}"#, + ] { + let m = Manifest::parse(none.as_bytes()).unwrap(); + assert!(m.write_kinds().is_empty(), "{none}"); + assert!(serde_json::to_value(&m).unwrap().get("writes").is_none(), "{none}"); + } + let rw = r#""permissions":["doc.read","doc.write"]"#; + for (bad, says) in [ + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["text"]}}"#), + "`writes` names an unknown object kind `text`", + ), + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["type","type"]}}"#), + "`writes` lists `type` twice", + ), + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["image"]}}"#), + "`writes` lists `image`, which `inputs` doesn't list", + ), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"writes":["image"]}}"#), "which `inputs` doesn't list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":"type"}}"#), "`writes` must be a list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":[1]}}"#), "`writes` must be a list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,{rw},"inputs":["type"],"writes":["type"]}}"#), "`writes` needs `api` 3"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":["type"]}"#.into(), + "`writes` needs the permission `doc.write`", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"inputs":["type"],"writes":["type"]}"#.into(), + "`inputs` needs the permission `doc.read`", + ), + (r#"{"id":"a","name":"x","kind":"effect","api":3,"writes":["type"]}"#.into(), "only a filter declares `writes`"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A live effect at `api` 2 may declare `"paintOutput": true`, and only that value; any other /// kind or level, and `false`, `null` or another type, is refused naming the key. Without the /// key, at any level, the effect returns geometry only. diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 19a90500ce..3f58ef4573 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -80,6 +80,10 @@ pub struct OutObject { /// A read-only input object (type, an image or a symbol instance) returned as it was given: /// it stays as it is, and new objects listed after it go above it. pub kept: bool, + /// A type object, an image or a symbol instance of a kind the filter may change (`writes`) + /// returned with changes: the fields it changes, by their names in the input, checked when + /// they are applied ([`apply_output`]). + pub edit: Option>, } /// One stroke of an [`OutObject`]. `None` fields keep the stroke's value (a new stroke's @@ -293,7 +297,7 @@ fn affine_json(xf: Affine) -> Value { /// paragraphs: [style]}` with the native character and paragraph attributes, one paragraph style /// for each paragraph, and `truncated`: true, with no runs or paragraphs, past [`MAX_INPUT_TEXT`] /// or [`MAX_INPUT_RUNS`]; -/// - an image (`"image"`): `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`, +/// - an image (`"image"`): `opacity` (0 to 1), `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`, /// `linked`, `pixelsOmitted`, and for an embedded image of at most [`MAX_INPUT_PIXELS`] /// `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top (a CMYK image's inks /// through the working CMYK profile, as sRGB). A linked image's file and path are never read or @@ -330,6 +334,7 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left if let Some(q) = n.image_quad() { o["corners"] = json!(q.map(|p| [p.x, p.y])); } + o["opacity"] = json!(n.opacity); o["pixelSize"] = json!([im.width, im.height]); o["colorMode"] = json!(doc.image_blob(im).map_or("unknown", color_mode)); o["linked"] = json!(im.link.is_some()); @@ -670,6 +675,15 @@ fn decode_paint(v: &Value, at: &str) -> Result { Ok(p) } +/// An object's name from plug-in output (`null`: no name), without control characters and at most +/// 256 of them. +fn decode_name(n: &Value, at: &str) -> Result { + Ok(match n { + Value::Null => String::new(), + n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(), + }) +} + fn opt<'a>(o: &'a serde_json::Map, key: &str) -> Option<&'a Value> { o.get(key).filter(|v| !v.is_null()) } @@ -691,11 +705,7 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result }); } if let Some(n) = o.get("name") { - let name = match n { - Value::Null => String::new(), - n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(), - }; - out.name = Some(name); + out.name = Some(decode_name(n, at)?); } if let Some(p) = opt(o, "path") { out.path = Some(decode_path(p, &format!("{at}.path"), anchors)?); @@ -809,8 +819,18 @@ pub fn decode_output(bytes: &[u8]) -> Result { /// differs, before anything changes. Each object is parsed from `input` only to compare it, one at /// a time, and an object that can't be read from there is an error. pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) -> Result { + decode_output_writing(bytes, input, read_only, &[]) +} + +/// [`decode_output_with`] for a filter that may change the objects of kinds `writes` among them +/// (its manifest's `writes`): such an object is still listed exactly once, and an entry for it may +/// leave fields out, which keep their values, and give its name, its transform, and type's +/// `text.runs` and `text.paragraphs`, an image's `opacity` or an instance's `symbolId` changed. +/// Such an entry is [`OutObject::edit`] with the fields it changes; one that changes nothing is +/// [`OutObject::kept`]. Any other field must be as given, and the error names the first that isn't. +pub fn decode_output_writing(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result { let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; - let objects = decode_objects(&v, input, read_only)?; + let objects = decode_objects(&v, input, read_only, writes)?; let document_data = match v.get_mut("documentData").map(Value::take) { None => None, Some(Value::Null) => Some(None), @@ -829,12 +849,12 @@ pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) /// declined (the message reaches the user). A live effect's other keys don't matter. pub fn decode(bytes: &[u8]) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; - decode_objects(&v, &[], &HashMap::new()) + decode_objects(&v, &[], &HashMap::new(), &[]) } /// The objects of output `v`, or its decline; entries for `read_only` objects as -/// [`decode_output_with`] reads them. -fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result> { +/// [`decode_output_writing`] reads them, those of kinds `writes` changeable. +fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result> { if let Some(e) = declined(v) { return Err(e); } @@ -843,6 +863,8 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result< return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len()))); } let mut anchors = 0; + // Bytes of type text the output writes, over all its objects. + let mut text = 0; let mut returned: HashSet = HashSet::new(); let out = objects .iter() @@ -853,12 +875,19 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result< if !returned.insert(id) { return Err(out_err(&at, "is listed twice")); } + let kept = OutObject { id: Some(id), kept: true, ..OutObject::default() }; // `{"id": …}` alone keeps the object, so there is nothing to compare it with. - if o.as_object().is_none_or(|m| m.len() != 1) { - let given = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?; + let Some(entry) = o.as_object().filter(|m| m.len() != 1) else { return Ok(kept) }; + let given: Value = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?; + let kind = given.get("type").and_then(Value::as_str).and_then(InputKind::parse).filter(|k| writes.contains(k)); + let Some(kind) = kind else { check_unchanged(o, &given, &at)?; - } - Ok(OutObject { id: Some(id), kept: true, ..OutObject::default() }) + return Ok(kept); + }; + Ok(match writes::changes(entry, &given, kind, &at, &mut text)? { + Some(edit) => OutObject { id: Some(id), edit: Some(edit), ..OutObject::default() }, + None => kept, + }) } None => decode_object(o, &format!("objects[{i}]"), &mut anchors), }) @@ -899,13 +928,17 @@ fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> { }; match changed.or_else(|| first_difference(o, given, "")) { None => Ok(()), - Some(field) => { - let field = crate::permissions::display_text(&field, crate::permissions::MAX_SHOWN_FIELD); - Err(out_err(at, format!("read-only field '{field}' changed"))) - } + Some(field) => Err(read_only_changed(at, &field)), } } +/// The error for an entry at `at` that changes read-only `field`, which is shown as +/// [`crate::permissions::display_text`] shows a manifest string. +fn read_only_changed(at: &str, field: &str) -> Error { + let field = crate::permissions::display_text(field, crate::permissions::MAX_SHOWN_FIELD); + out_err(at, format!("read-only field '{field}' changed")) +} + /// The path of the first place `a` and `b` differ (`""`: they differ as a whole), `None` when they /// are the same JSON with numbers compared by value. fn first_difference(a: &Value, b: &Value, at: &str) -> Option { @@ -1233,7 +1266,9 @@ impl Plan { /// input object, just below the first one listed after them (at the first input object's place /// when the output keeps none; on top of `parent` when there were no inputs). Input objects missing /// from the output are deleted. An object's effect records replace its own once `admit` lets them -/// in. Returns the resulting objects in output order (to select). +/// in. Type, images and symbol instances stay as they are, or take the changes of their +/// [`OutObject::edit`] once each value is checked. Returns the resulting objects in output order +/// (to select). pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec, parent: Option, admit: AdmitEffects) -> Result> { let wanted: HashSet = inputs.iter().copied().collect(); let mut originals: HashMap = HashMap::new(); @@ -1258,12 +1293,15 @@ pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec, out_err(&at, format!("{} is not the id of an input object", id.0)) } })?; - // Type, images and symbol instances are only read: writing one would make it a path. - if input_kind(&n).is_some() && !o.kept { - return Err(out_err(&at, format!("{} is read-only", id.0))); - } + // Type, images and symbol instances change only through the fields a filter that + // may write them returns: writing one as a path would make it a path. let kept = o.kept; - if !kept { + if input_kind(&n).is_some() && !kept { + let Some(edit) = &o.edit else { return Err(out_err(&at, format!("{} is read-only", id.0))) }; + writes::apply(doc, &mut n, edit, &format!("{at} (id {})", id.0))?; + } else if o.edit.is_some() { + return Err(out_err(&at, format!("{} is not type, an image or a symbol instance", id.0))); + } else if !kept { write(doc, &mut n, o, &at, admit)?; } if !run.is_empty() { @@ -1320,5 +1358,7 @@ pub fn output_geometry(objects: Vec) -> PathData { PathData::new(objects.into_iter().filter_map(|o| o.path).flat_map(|p| p.subpaths).collect()) } +mod writes; + #[cfg(test)] mod tests; diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 58159c3370..bd35136dde 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1151,6 +1151,299 @@ fn read_only_kind_field_and_omission_refuse() { assert_eq!(d, before); } +/// [`mixed`] with a second symbol, "Moon", and its targets and input for a filter that reads and may +/// change every kind. +fn writable() -> (Document, Vec, Vec, ReadOnlySpans, [NodeId; 5]) { + let (mut d, _, layer, extra) = mixed(); + let art = Arc::new(Node::path(d.alloc_id(), square(5.0), Appearance::default())); + d.symbols.push(vectorcraft_doc::Symbol { name: "Moon".into(), art, dynamic: false }); + let targets = filter_targets_with(&d, &[layer], &InputKind::ALL); + let (bytes, read_only) = encode_input_with(&d, &targets, &InputKind::ALL, usize::MAX).unwrap(); + (d, targets, bytes, read_only, extra) +} + +/// Decodes `out` for [`writable`]'s input with `writes` and applies it to `d`. +fn write_out( + d: &mut Document, + targets: &[NodeId], + bytes: &[u8], + read_only: &ReadOnlySpans, + writes: &[InputKind], + out: &Value, +) -> Result> { + let out = decode_output_writing(out.to_string().as_bytes(), bytes, read_only, writes)?; + apply_output(d, targets, out.objects, None, &keep) +} + +/// A filter that may write type, images and symbol instances changes type's runs and character +/// attributes, an image's transform and opacity, and the symbol and transform of an instance, +/// with entries that give only the fields they change. What it writes reads back the same. An +/// exact echo, `{"id": …}` alone and fields given as they were (numbers by value) change nothing. +#[test] +fn writable_kinds_take_type_runs_image_placement_and_instance_symbols() { + use vectorcraft_doc::{CharStyle, ParaStyle}; + let (mut d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable(); + let before = d.clone(); + let all = &InputKind::ALL; + let echo = decode_output_writing(&bytes, &bytes, &read_only, all).unwrap(); + assert!(echo.objects.iter().all(|o| o.edit.is_none())); + apply_output(&mut d, &targets, echo.objects, None, &keep).unwrap(); + assert_eq!(d, before, "an exact echo changes nothing"); + let ro = |id: NodeId| json!({"id": id.0}); + let paths: Vec = targets.iter().filter(|id| !read_only.contains_key(id)).map(|id| ro(*id)).collect(); + let with = |entries: Vec| { + let objects = [paths.clone(), entries].concat(); + json!({ "objects": objects }) + }; + let same = with(vec![ + json!({"id": text.0, "transform": [1, 0, 0, 1, 5, 50], "name": "T"}), + json!({"id": embedded.0, "opacity": 1}), + ro(linked), + json!({"id": star.0, "symbolId": "Star"}), + ro(ghost), + ]); + let out = decode_output_writing(same.to_string().as_bytes(), &bytes, &read_only, all).unwrap(); + assert!(out.objects.iter().all(|o| o.edit.is_none())); + assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5, "fields given as they were change nothing"); + // The changes, each entry giving only what it changes. + let big = CharStyle { size: 24.0, ..CharStyle::default() }; + let runs = json!([{"text": "Bye\n", "style": CharStyle::default()}, {"text": "now", "style": big}]); + let out = with(vec![ + json!({"id": text.0, "name": "Renamed", "text": {"runs": runs}}), + json!({"id": embedded.0, "transform": [1, 0, 0, 1, 10, 20], "opacity": 0.5}), + ro(linked), + json!({"id": star.0, "symbolId": "Moon", "transform": [1, 0, 0, 1, 50, 0]}), + ro(ghost), + ]); + let made = write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap(); + assert_eq!(made.len(), targets.len()); + let node = |id: NodeId| d.node(id).unwrap().clone(); + let NodeKind::Text(t) = &node(text).kind else { panic!("type") }; + assert_eq!((t.plain_text().as_str(), t.runs[1].style.size), ("Bye\nnow", 24.0)); + assert_eq!(t.para_at(1).space_before, 6.0, "paragraphs keep their styles"); + assert_eq!(t.para_at(0), &ParaStyle::default()); + assert_eq!(node(text).name.as_deref(), Some("Renamed")); + let NodeKind::Image(im) = &node(embedded).kind else { panic!("image") }; + assert_eq!((im.xf, node(embedded).opacity), (Affine::new([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), 0.5)); + assert_eq!(node(star).kind, NodeKind::SymbolInstance { symbol: "Moon".into(), xf: Affine::translate((50.0, 0.0)) }); + for id in [linked, ghost] { + assert_eq!(d.node(id), before.node(id), "objects returned by id stay as they were"); + } + // Read again, the changed objects give what was written. + let read = |id: NodeId| encode_read_only(&d, d.node(id).unwrap()).unwrap(); + assert_eq!(read(text)["text"]["runs"], runs); + assert_eq!((&read(embedded)["transform"], &read(embedded)["opacity"]), (&json!([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), &json!(0.5))); + assert_eq!((&read(star)["symbolId"], &read(star)["transform"]), (&json!("Moon"), &json!([1.0, 0.0, 0.0, 1.0, 50.0, 0.0]))); + assert!(read(star).get("missing").is_none()); + // An instance of a symbol the document lacks can point to one it has. + let mut d = before.clone(); + let out = with(vec![ro(text), ro(embedded), ro(linked), ro(star), json!({"id": ghost.0, "symbolId": "Star"})]); + write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap(); + assert!(matches!(&d.node(ghost).unwrap().kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Star")); +} + +/// An entry that changes a field its kind can't change, a kind the manifest doesn't list in +/// `writes`, or gives a value out of range is refused naming the object and the field, before +/// anything changes. +#[test] +fn bad_writes_are_refused_naming_the_object_and_the_field() { + use vectorcraft_doc::CharStyle; + let (d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable(); + let input: Value = serde_json::from_slice(&bytes).unwrap(); + let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap(); + let style = serde_json::to_value(CharStyle::default()).unwrap(); + let styled = |f: &dyn Fn(&mut Value)| { + let mut s = style.clone(); + f(&mut s); + json!([{"text": "Hi\nthere", "style": s}]) + }; + let (t, e, l, s) = (text.0, embedded.0, linked.0, star.0); + let (ti, ei, si) = (at(text), at(embedded), at(star)); + let cases: Vec<(NodeId, Value, &[InputKind], String)> = vec![ + (text, json!({"text": {"kind": "area"}}), &InputKind::ALL, format!("objects[{ti}] (id {t}): read-only field 'text.kind' changed")), + (text, json!({"text": {"x": 1}}), &InputKind::ALL, format!("(id {t}): read-only field 'text.x' changed")), + (text, json!({"bounds": [0, 0, 1, 1]}), &InputKind::ALL, format!("(id {t}): read-only field 'bounds[0]' changed")), + (text, json!({"opacity": 0.5}), &InputKind::ALL, format!("(id {t}): read-only field 'opacity' changed")), + (text, json!({"text": {"runs": []}}), &InputKind::ALL, "text.runs: type needs at least one run".into()), + ( + text, + json!({"text": {"runs": styled(&|s| s["fontSzie"] = json!(9))}}), + &InputKind::ALL, + "text.runs[0].style: unknown attribute 'fontSzie'".into(), + ), + ( + text, + json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}), + &InputKind::ALL, + "text.runs[0].style.size: must be 0.1 to 1296 pt".into(), + ), + (text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()), + ( + text, + json!({"text": {"runs": styled(&|s| s["font_family"] = json!(" "))}}), + &InputKind::ALL, + "font_family: must be 1-256 printable characters".into(), + ), + (text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()), + ( + text, + json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}), + &InputKind::ALL, + "holds the character of an inline graphic".into(), + ), + (text, json!({"text": {"paragraphs": [{}]}}), &InputKind::ALL, "text.paragraphs: expected 2 paragraph styles, one per paragraph".into()), + (text, json!({"transform": [1, 0, 0, 0, 0, 0]}), &InputKind::ALL, format!("objects[{ti}] (id {t}).transform: flattens the object")), + (text, json!({"transform": [1, 0, 0, 1, 1e9, 0]}), &InputKind::ALL, "transform: a number is out of range".into()), + (text, json!({"transform": [1, 0, null, 0, 1, 10, 20]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()), + (text, json!({"transform": [1, 0, 0, 1, 10]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()), + (text, json!({"transform": [1, 0, 0, 1]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()), + (embedded, json!({"pixelSize": [3, 1]}), &InputKind::ALL, format!("(id {e}): read-only field 'pixelSize[0]' changed")), + (embedded, json!({"opacity": 2}), &InputKind::ALL, format!("objects[{ei}] (id {e}).opacity: must be a number from 0 to 1")), + (embedded, json!({"opacity": "half"}), &InputKind::ALL, "opacity: must be a number from 0 to 1".into()), + (linked, json!({"linked": false}), &InputKind::ALL, format!("(id {l}): read-only field 'linked' changed")), + (embedded, json!({"opacity": 0.5}), &[InputKind::Type, InputKind::SymbolInstance], format!("(id {e}): read-only field 'opacity' changed")), + ( + star, + json!({"symbolId": "Nowhere"}), + &InputKind::ALL, + format!("objects[{si}] (id {s}).symbolId: 'Nowhere' is not a symbol in this document"), + ), + (star, json!({"symbolId": 7}), &InputKind::ALL, "symbolId: must be the name of a symbol".into()), + (star, json!({"overrides": {"a": 1}}), &InputKind::ALL, format!("(id {s}): read-only field 'overrides.a' changed")), + (ghost, json!({"missing": false}), &InputKind::ALL, "read-only field 'missing' changed".into()), + (star, json!({"symbolId": "Moon"}), &[InputKind::Type], format!("(id {s}): read-only field 'symbolId' changed")), + ]; + for (id, entry, writes, says) in cases { + let mut out = input.clone(); + let mut e = entry.clone(); + e["id"] = json!(id.0); + out["objects"][at(id)] = e; + let mut doc = d.clone(); + let err = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string(); + assert!(err.contains(&says), "{entry}: {says}: {err}"); + assert_eq!(doc, d, "{entry}: nothing changed"); + } + // Leaving a writable object out is still refused: it isn't deleted. + let mut out = input.clone(); + out["objects"].as_array_mut().unwrap().remove(at(star)); + let e = write_out(&mut d.clone(), &targets, &bytes, &read_only, &InputKind::ALL, &out).unwrap_err().to_string(); + assert!(e.contains(&format!("objects (id {s}): a read-only object was left out")), "{e}"); +} + +/// The text a filter writes to one type object is held to [`MAX_INPUT_TEXT`] bytes and +/// [`MAX_INPUT_RUNS`] runs and paragraphs, as the text it is given; type given as `truncated` +/// keeps its text, though it can still move. +#[test] +fn written_text_is_held_to_the_input_limits_and_truncated_type_keeps_its_text() { + use vectorcraft_doc::{CharStyle, TextObject}; + let (mut d, _, layer, [text, ..]) = mixed(); + let long = Node::new( + d.alloc_id(), + NodeKind::Text(Box::new(TextObject::point(Point::new(0.0, 0.0), &"x".repeat(MAX_INPUT_TEXT + 1), CharStyle::default()))), + ); + let long = d.insert(Some(layer), usize::MAX, long).unwrap(); + let targets = filter_targets_with(&d, &[layer], &[InputKind::Type]); + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let input: Value = serde_json::from_slice(&bytes).unwrap(); + let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap(); + assert_eq!(input["objects"][at(long)]["truncated"], json!(true)); + let style = serde_json::to_value(CharStyle::default()).unwrap(); + let run = |s: String| json!({"text": s, "style": style}); + let writes = &[InputKind::Type]; + for (id, text_v, says) in [ + (text, json!({"runs": [run("x".repeat(MAX_INPUT_TEXT + 1))]}), format!("bytes of text (limit {MAX_INPUT_TEXT})")), + (text, json!({"runs": vec![run("x".into()); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")), + (text, json!({"paragraphs": vec![json!({}); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")), + (long, json!({"runs": [run("short".into())]}), "the text of type given as `truncated` can't be changed".to_string()), + ] { + let mut out = input.clone(); + out["objects"][at(id)] = json!({"id": id.0, "text": text_v}); + let mut doc = d.clone(); + let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string(); + assert!(e.contains(&says), "{says}: {e}"); + assert_eq!(doc, d); + } + // At the limit the text is written; truncated type still moves. + let mut out = input.clone(); + out["objects"][at(text)] = json!({"id": text.0, "text": {"runs": [run("x".repeat(MAX_INPUT_TEXT))]}}); + out["objects"][at(long)] = json!({"id": long.0, "transform": [1, 0, 0, 1, 3, 4]}); + write_out(&mut d, &targets, &bytes, &read_only, writes, &out).unwrap(); + assert!(matches!(&d.node(text).unwrap().kind, NodeKind::Text(t) if t.plain_text().len() == MAX_INPUT_TEXT)); + assert!( + matches!(&d.node(long).unwrap().kind, NodeKind::Text(t) if t.xf == Affine::translate((3.0, 4.0)) && t.plain_text().len() == MAX_INPUT_TEXT + 1) + ); +} + +/// An inline graphic in type stays as it was, in its place among the inline graphics: the runs +/// around it can change, and adding, removing or changing one is refused. +#[test] +fn inline_graphics_in_written_type_stay_as_they_were() { + use vectorcraft_doc::{CharStyle, InlineArt, TextObject, TextRun}; + let (mut d, _, layer, _) = mixed(); + let mut t = TextObject::point(Point::new(0.0, 0.0), "A", CharStyle::default()); + t.runs = vec![ + TextRun::new("A", CharStyle::default()), + TextRun::inline(InlineArt::new("Star"), CharStyle::default()), + TextRun::new("B", CharStyle::default()), + ]; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let input: Value = serde_json::from_slice(&bytes).unwrap(); + let runs = input["objects"][0]["text"]["runs"].clone(); + let writes = &[InputKind::Type]; + let with = |runs: Value| json!({"objects": [{"id": id.0, "text": {"runs": runs}}]}); + let mut changed = runs.clone(); + changed[0]["text"] = json!("Before "); + changed[2]["text"] = json!(" after"); + let mut doc = d.clone(); + write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(changed)).unwrap(); + let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.plain_text(), "Before \u{FFFC} after"); + assert_eq!(t.runs[1].inline.as_ref().map(|a| a.symbol.as_str()), Some("Star")); + let mut moved = runs.clone(); + moved[1]["inline"]["symbol"] = json!("Moon"); + let without = json!([runs[0], runs[2]]); + let doubled = json!([runs[0], runs[1], runs[1], runs[2]]); + for bad in [moved, without, doubled] { + let mut doc = d.clone(); + let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(bad.clone())).unwrap_err().to_string(); + assert!(e.contains("inline graphics can't be added, removed, reordered or changed"), "{bad}: {e}"); + assert_eq!(doc, d); + } +} + +/// Runs written without `paragraphs` keep each paragraph's style when the number of paragraphs +/// stays the same, and otherwise move the styles with the text as typing the same change would: a +/// paragraph added before others takes the style of the one it splits and the others keep theirs, +/// and joining two paragraphs keeps the first one's style. +#[test] +fn written_runs_without_paragraphs_keep_each_paragraph_s_style() { + use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject}; + let (mut d, _, layer, _) = mixed(); + let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB\nC", CharStyle::default()); + let styled = |justify| ParaStyle { justify, ..ParaStyle::default() }; + t.set_paragraph_styles(vec![styled(Justify::Left), styled(Justify::Center), styled(Justify::Right)]); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let justified = |text: &str| { + let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]}); + let mut doc = d.clone(); + write_out(&mut doc, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.plain_text(), text); + (0..t.paragraph_count()).map(|i| t.para_at(i).justify).collect::>() + }; + assert_eq!(justified("X\nA\nB\nC"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right]); + assert_eq!(justified("A\nBé\nC"), [Justify::Left, Justify::Center, Justify::Right]); + assert_eq!(justified("One\nTwo\nThree"), [Justify::Left, Justify::Center, Justify::Right]); + assert_eq!(justified("AB\nC"), [Justify::Left, Justify::Right]); + assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]); +} + /// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON /// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output. #[test] diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs new file mode 100644 index 0000000000..3ecd48bbb1 --- /dev/null +++ b/crates/plugins/src/objects/writes.rs @@ -0,0 +1,342 @@ +//! What a filter whose manifest lists `writes` may change about the type, images and symbol +//! instances it was given: each one's name and transform; type's runs, with their character +//! attributes, and its paragraph styles; an image's opacity; and the symbol an instance shows. +//! Every other field stays read-only, and every value is checked before anything changes. + +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; +use vectorcraft_doc::text::INLINE_CHAR; +use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, ParaStyle, TextObject, TextRun}; +use vectorcraft_geom::Affine; + +use super::{ + MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err, + read_only_changed, +}; +use crate::{InputKind, Result}; + +/// The smallest and largest font size a filter may set, in points (as the Character panel's). +const FONT_SIZE: std::ops::RangeInclusive = 0.1..=1296.0; +/// The longest font family name a filter may set, in characters. +const MAX_FAMILY: usize = 256; +/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object. +const MIN_DETERMINANT: f64 = 1e-12; + +/// The fields of an object of `kind` a filter that lists the kind in `writes` may change. +fn writable(kind: InputKind) -> &'static [&'static str] { + match kind { + InputKind::Type => &["name", "transform", "text"], + InputKind::Image => &["name", "transform", "opacity"], + InputKind::SymbolInstance => &["name", "transform", "symbolId"], + } +} + +/// The changes entry `o` of a filter's output makes to object `given` of `kind` (as the input gave +/// it), `None` when it changes nothing. Fields it leaves out keep their values; a field it gives +/// that isn't [`writable`] must be as given. Changed type text counts toward `text`, the bytes of +/// text written over the whole output. The changes are keyed `name`, `transform`, `opacity`, +/// `symbolId`, `runs` and `paragraphs`; their values are checked when they are applied ([`apply`]). +pub(super) fn changes(o: &Map, given: &Value, kind: InputKind, at: &str, text: &mut usize) -> Result>> { + let mut keys: Vec<&String> = o.keys().filter(|k| *k != "id").collect(); + keys.sort(); + let mut out = Map::new(); + for k in keys { + let v = &o[k]; + let was = given.get(k); + if !writable(kind).contains(&k.as_str()) { + if let Some(field) = was.map_or_else(|| Some(k.clone()), |w| first_difference(v, w, k)) { + return Err(read_only_changed(at, &field)); + } + continue; + } + match (k.as_str(), was) { + ("text", Some(was)) => text_changes(v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?, + ("name", None) if v.is_null() => {} + (_, Some(was)) if first_difference(v, was, "").is_none() => {} + _ => { + out.insert(k.clone(), v.clone()); + } + } + } + Ok((!out.is_empty()).then_some(out)) +} + +/// The `runs` and `paragraphs` of type text `v` that differ from `was` (the text the input gave), +/// into `out`; its other fields must be as given, and type given as `truncated` keeps its text. A +/// changed list is held to [`MAX_INPUT_RUNS`] entries, and changed runs to [`MAX_INPUT_TEXT`] bytes +/// of text, which count toward `total`, held to [`MAX_INPUT_TEXT_TOTAL`]. +fn text_changes(v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map) -> Result<()> { + let t = v.as_object().ok_or_else(|| out_err(at, "`text` must be an object"))?; + let mut keys: Vec<&String> = t.keys().collect(); + keys.sort(); + for k in keys { + let field = format!("text.{k}"); + let given = was.get(k); + let differs = given.is_none_or(|g| first_difference(&t[k], g, "").is_some()); + if !matches!(k.as_str(), "runs" | "paragraphs") { + if differs { + let shown = given.and_then(|g| first_difference(&t[k], g, &field)).unwrap_or_else(|| field.clone()); + return Err(read_only_changed(at, &shown)); + } + continue; + } + if !differs { + continue; + } + if truncated { + return Err(out_err(&format!("{at}.{field}"), "the text of type given as `truncated` can't be changed")); + } + let list = t[k].as_array().filter(|l| l.len() <= MAX_INPUT_RUNS); + let list = list.ok_or_else(|| out_err(&format!("{at}.{field}"), format!("must be a list of at most {MAX_INPUT_RUNS} entries")))?; + if k == "runs" { + if list.is_empty() { + return Err(out_err(&format!("{at}.{field}"), "type needs at least one run")); + } + let bytes = list.iter().fold(0usize, |n, r| n.saturating_add(r.get("text").and_then(Value::as_str).map_or(0, str::len))); + if bytes > MAX_INPUT_TEXT { + return Err(out_err(&format!("{at}.{field}"), format!("{bytes} bytes of text (limit {MAX_INPUT_TEXT})"))); + } + *total = total.saturating_add(bytes); + if *total > MAX_INPUT_TEXT_TOTAL { + return Err(out_err(&format!("{at}.{field}"), format!("more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output"))); + } + } + out.insert(k.clone(), t[k].clone()); + } + Ok(()) +} + +/// Every attribute name `T` reads, including those its JSON leaves out at their defaults: the field +/// names serde's derive hands `deserialize_struct`. +fn attr_names() -> &'static [&'static str] { + use serde::de::{Error as _, Visitor, value::Error}; + + struct Names<'a>(&'a mut &'static [&'static str]); + impl<'de> serde::Deserializer<'de> for Names<'_> { + type Error = Error; + fn deserialize_any>(self, _: V) -> std::result::Result { + Err(Error::custom("not a struct")) + } + fn deserialize_struct>(self, _: &'static str, fields: &'static [&'static str], _: V) -> std::result::Result { + *self.0 = fields; + Err(Error::custom("field names only")) + } + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit + unit_struct newtype_struct seq tuple tuple_struct map enum identifier ignored_any + } + } + + let mut fields: &'static [&'static str] = &[]; + // Always an error: the probe only records the names. + let _ = T::deserialize(Names(&mut fields)); + fields +} + +/// `v` as a `T` whose attributes are all ones `T` reads: an unknown key, as an ill-typed value, is +/// an error at `at`. +fn strict(v: &Value, at: &str, what: &str) -> Result { + let o = v.as_object().ok_or_else(|| out_err(at, format!("{what} must be an object")))?; + let names = attr_names::(); + if let Some(k) = o.keys().find(|k| !names.contains(&k.as_str())) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(at, format!("unknown attribute '{k}'"))); + } + serde_json::from_value(v.clone()).map_err(|e| out_err(at, e)) +} + +/// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't +/// flatten the object. +fn decode_transform(v: &Value, at: &str) -> Result { + let c: Option> = v.as_array().and_then(|a| a.iter().map(Value::as_f64).collect()); + let c: [f64; 6] = c.and_then(|c| c.try_into().ok()).ok_or_else(|| out_err(at, "must be a list of 6 numbers"))?; + if !c.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) { + return Err(out_err(at, format!("a number is out of range (limit ±{MAX_COORD})"))); + } + let xf = Affine::new(c); + if xf.determinant().abs() < MIN_DETERMINANT { + return Err(out_err(at, "flattens the object to a line or a point")); + } + Ok(xf) +} + +/// The transform object `n` is given with: type's and an instance's own, an image's (for a +/// distorted image, the placement nearest its corners at its middle). +fn given_transform(n: &Node) -> Option { + match &n.kind { + NodeKind::Text(t) => Some(t.xf), + NodeKind::Image(im) => Some(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)), + NodeKind::SymbolInstance { xf, .. } => Some(*xf), + _ => None, + } +} + +/// Applies `changes` ([`changes`]) to `n`, an input object of `doc`; `at` names it in errors. Each +/// value is checked first, and an error leaves `n` to be dropped. +pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map, at: &str) -> Result<()> { + if let Some(v) = changes.get("transform") { + let at = format!("{at}.transform"); + let new = decode_transform(v, &at)?; + let old = given_transform(n).filter(|xf| xf.determinant().abs() >= MIN_DETERMINANT); + let old = old.ok_or_else(|| out_err(&at, "an object flattened to a line or a point can't be placed again"))?; + // Everything the object carries moves with it: a distorted image's corners, its gradients. + n.transform(new * old.inverse(), false); + let distorted = n.is_distorted_image(); + match &mut n.kind { + NodeKind::Text(t) => t.xf = new, + NodeKind::SymbolInstance { xf, .. } => *xf = new, + NodeKind::Image(im) if !distorted => im.xf = new, + _ => {} + } + } + if let Some(v) = changes.get("opacity") { + let op = v.as_f64().filter(|o| (0.0..=1.0).contains(o)); + n.opacity = op.ok_or_else(|| out_err(&format!("{at}.opacity"), "must be a number from 0 to 1"))? as f32; + } + if let Some(v) = changes.get("symbolId") { + let at = format!("{at}.symbolId"); + let name = v.as_str().ok_or_else(|| out_err(&at, "must be the name of a symbol"))?; + if !doc.symbols.iter().any(|s| s.name == name) { + let shown = crate::permissions::display_text(name, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(&at, format!("'{shown}' is not a symbol in this document"))); + } + let other = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol != name); + if let NodeKind::SymbolInstance { symbol, .. } = &mut n.kind { + *symbol = name.to_string(); + } + // An edited part's path names an object of the old symbol's art, as Replace Symbol finds. + if other && !n.extras().symbol_overrides.is_empty() { + n.extras_mut().symbol_overrides.clear(); + } + } + if changes.contains_key("runs") || changes.contains_key("paragraphs") { + let story = doc.story_of(n.id).len(); + let NodeKind::Text(t) = &mut n.kind else { return Err(out_err(at, "only type has text")) }; + set_text(doc, t, story > 1, changes.get("runs"), changes.get("paragraphs"), at)?; + } + if let Some(v) = changes.get("name") { + n.name = Some(decode_name(v, at)?).filter(|s| !s.trim().is_empty()); + } + Ok(()) +} + +/// Gives type `t` the runs `runs` and paragraph styles `paragraphs` a filter returned (`threaded`: +/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an +/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they +/// were, in the same order, and the characters of threaded type or type with ruby stay as they +/// were. A run whose style isn't one of the type's own has a font family and a size in +/// [`FONT_SIZE`], and its paints are checked as an object's are. Paragraph styles are one per +/// paragraph. With runs alone, each paragraph keeps its style when the number of paragraphs stays +/// the same, and otherwise the styles move with the text as typing the change moves them. +fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> { + if let Some(runs) = runs { + let at = format!("{at}.text.runs"); + let list = runs.as_array().map(Vec::as_slice).unwrap_or_default(); + let own: Vec = t.runs.iter().map(|r| serde_json::to_value(&r.style).unwrap_or(Value::Null)).collect(); + let mut new = Vec::with_capacity(list.len()); + for (i, v) in list.iter().enumerate() { + let at = format!("{at}[{i}]"); + let o = v.as_object().ok_or_else(|| out_err(&at, "a run must be {\"text\", \"style\", \"inline\"?}"))?; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "text" | "style" | "inline")) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(&at, format!("unknown key '{k}'"))); + } + let text = o.get("text").and_then(Value::as_str).ok_or_else(|| out_err(&at, "`text` must be a string"))?; + let style_v = o.get("style").unwrap_or(&Value::Null); + let mut style: CharStyle = strict(style_v, &format!("{at}.style"), "`style`")?; + let inline = match o.get("inline") { + None | Some(Value::Null) => None, + Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?), + }; + if inline.is_none() { + if text.contains(INLINE_CHAR) { + return Err(out_err(&at, "`text` holds the character of an inline graphic")); + } + if !own.contains(style_v) { + check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?; + } + } + new.push(TextRun { text: text.to_string(), style, inline }); + } + // Inline graphics are compared as saved (their measured bounds aren't), and keep those. + let saved = |r: &&TextRun| serde_json::to_value(r).ok(); + let old_inline: Vec<&TextRun> = t.runs.iter().filter(|r| r.inline.is_some()).collect(); + let new_inline: Vec<&TextRun> = new.iter().filter(|r| r.inline.is_some()).collect(); + if old_inline.len() != new_inline.len() || old_inline.iter().zip(&new_inline).any(|(a, b)| saved(a) != saved(b)) { + return Err(out_err(&at, "inline graphics can't be added, removed, reordered or changed")); + } + let mut kept = old_inline.into_iter().cloned().collect::>().into_iter(); + for r in new.iter_mut().filter(|r| r.inline.is_some()) { + if let Some(old) = kept.next() { + *r = old; + } + } + let plain: String = new.iter().map(|r| r.text.as_str()).collect(); + let old = t.plain_text(); + if plain != old { + if threaded { + return Err(out_err(&at, "the characters of threaded type can't be changed")); + } + if !t.ruby.is_empty() { + return Err(out_err(&at, "the characters of type with ruby can't be changed")); + } + let breaks = |s: &str| s.bytes().filter(|&b| b == b'\n').count(); + if paragraphs.is_none() && breaks(&plain) != breaks(&old) { + // Paragraphs added or joined: the styles follow the text as typing the change would + // move them. With as many paragraphs as before, each keeps its style. + let (start, old_end, new_end) = changed_range(&old, &plain); + t.splice_paras(start, old_end, plain.get(start..new_end).unwrap_or_default()); + } + } + t.runs = new; + } + match paragraphs { + Some(v) => { + let at = format!("{at}.text.paragraphs"); + let list = v.as_array().map(Vec::as_slice).unwrap_or_default(); + let count = t.paragraph_count(); + if list.len() != count { + return Err(out_err(&at, format!("expected {count} paragraph styles, one per paragraph"))); + } + let styles = + list.iter().enumerate().map(|(i, p)| strict::(p, &format!("{at}[{i}]"), "a paragraph style")).collect::>()?; + t.set_paragraph_styles(styles); + } + None => t.normalize_paras(), + } + // The layout is measured again before the type is drawn. + t.cached_bounds = None; + t.cached_baselines.clear(); + t.cached_ink = None; + Ok(()) +} + +/// The bytes that differ between `old` and `new` once their common start and end are taken away, +/// on character boundaries: `old[start..old_end]` became `new[start..new_end]`. +fn changed_range(old: &str, new: &str) -> (usize, usize, usize) { + let start = old.char_indices().zip(new.chars()).find(|((_, a), b)| a != b).map_or(old.len().min(new.len()), |((i, _), _)| i); + let (old_rest, new_rest) = (old.get(start..).unwrap_or_default(), new.get(start..).unwrap_or_default()); + let same: usize = old_rest.chars().rev().zip(new_rest.chars().rev()).take_while(|(a, b)| a == b).map(|(c, _)| c.len_utf8()).sum(); + (start, old.len() - same, new.len() - same) +} + +/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before): +/// its font family is 1 to [`MAX_FAMILY`] printable characters, its size is in [`FONT_SIZE`], and +/// its fill and stroke are admitted as an object's paints are. +fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> { + let family = s.font_family.trim(); + if family.is_empty() || family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) { + return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters"))); + } + if !FONT_SIZE.contains(&s.size) { + return Err(out_err(&format!("{at}.size"), format!("must be {} to {} pt", FONT_SIZE.start(), FONT_SIZE.end()))); + } + let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| { + let at = format!("{at}.{key}"); + let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?; + admit_paint(doc, decode_paint(&v, &at)?, was, &at) + }; + s.fill = paint(&s.fill, was.map(|w| &w.fill), "fill")?; + s.stroke = paint(&s.stroke, was.map(|w| &w.stroke), "stroke")?; + Ok(()) +} diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..32055f44f1 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -15,8 +15,8 @@ use crate::{Error, Kind, Result}; /// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most /// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput` -/// ([`crate::painted`]). -pub const API_LEVEL: u32 = 2; +/// ([`crate::painted`]); level 3 a filter's `writes` ([`WRITES_API`]). +pub const API_LEVEL: u32 = 3; /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, /// `settings`, `cache` and `commands` permissions they need. @@ -25,6 +25,9 @@ pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). pub const INPUTS_API: u32 = 2; +/// The API level that adds a filter's `writes`: the kinds among its `inputs` it may change. +pub const WRITES_API: u32 = 3; + /// Most permissions a manifest may list. pub const MAX_PERMISSIONS: usize = 16; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..dbbcd819da 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -714,6 +714,7 @@ impl PluginIntField { api: 1, permissions: None, inputs: Vec::new(), + writes: Vec::new(), params: vec![("seed".into(), vectorcraft_plugins::ParamSpec::Int { min, max, default: 0 }.into())], extensions: Vec::new(), budget: Default::default(), diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..176625a7af 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13256,7 +13256,12 @@ fit makes `plugin.run` return a memory-budget error naming the object and its si memory-budget error `the selection is too large to hand over`, and more than 100,000 of these objects make it return an object-budget error. Its output returns each of them as `{"id": …}` or exactly as given, otherwise `plugin.run` returns an error naming the object and the -field, and the document and undo history are unchanged. A filter at plug-in API level 2 whose manifest lists the +field, and the document and undo history are unchanged. A filter at plug-in API level 3 whose manifest also lists some of +those kinds in `writes` (with `doc.write`; `writes` in its `plugin.list` entry) may return an object of such a kind with +only the fields it changes: its name and `transform`, type's `text.runs` and `text.paragraphs`, an image's `opacity` and +an instance's `symbolId`, which must name a symbol in the document. Any other changed field, or a value out of range, +makes `plugin.run` return an error naming the object and the field, with nothing changed (docs/plugins.md, "Writing +type, images and symbols"). An output that changes nothing records no undo step. A filter at plug-in API level 2 whose manifest lists the `commands` permission and a `commandAllowlist` (both in its `plugin.list` entry) runs the commands that list names while it runs, through `vc_call`: the calls and its output are one undo step, and a run that fails or makes a call that fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..a80de821d8 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -324,10 +324,11 @@ capability model proposed for PhotoCraft plug-ins - The host enforces the grant on a filter run and a command run: without `doc.read` the filter is given no objects; without `state` its `documentData` is `null` and an output that sets it is refused; without `doc.write` an output that changes the document is refused. A refused output leaves the document as it was. -- `api` is the plug-in API level the manifest is written for: `1` (the default) or `2`, which adds the [host +- `api` is the plug-in API level the manifest is written for: `1` (the default), `2`, which adds the [host imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and - symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects). A higher one - is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for + symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects), or `3`, which + adds a filter's `writes` ([writing type, images and symbols](#writing-type-images-and-symbols)). A higher one is + refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the user to grant them. A level 2 effect that declares `paintOutput` needs no other permission than `doc.read` and `effect.render`. @@ -556,6 +557,11 @@ the module's start function, in a run that isn't a filter's run on a document, o filter gets paths and compound paths alone, as before. An unknown, repeated or wrongly typed entry, `inputs` on another kind, below `api` 2, or without a `permissions` list that holds `doc.read`, is refused when the plug-in is installed, and so is `api` 2 on hosts from before it. +- `writes` (filters at `api` 3 only): the kinds among `inputs` the filter may change ([writing type, images and + symbols](#writing-type-images-and-symbols)), each at most once (`"writes": ["type"]`). Left out or `[]`, everything + the filter reads stays read-only. An unknown, repeated or wrongly typed entry, a kind `inputs` doesn't list, `writes` + on another kind, below `api` 3, or without `doc.write` in `permissions`, is refused when the plug-in is installed, and + hosts from before it refuse `api` 3. - `paintOutput` (live effects at `api` 2 only): `true` makes the effect return [painted pieces](#painted-live-effects) instead of geometry alone. `true` is the only value the key takes; `false`, `null`, another type, another kind or `api` 1 is refused when the module is installed, and the error names `paintOutput`. Without the key the effect returns @@ -677,7 +683,7 @@ every attribute: "runs": [{"text": "Hello\nthere", "style": {"font_family": "Source Sans 3", "size": 12}}], "paragraphs": [{"justify": "Left"}, {"justify": "Center"}]}, "truncated": false}, - {"id": 18, "type": "image", "bounds": [0, 0, 4, 2], "transform": [2, 0, 0, 2, 0, 0], "pixelSize": [2, 1], + {"id": 18, "type": "image", "bounds": [0, 0, 4, 2], "transform": [2, 0, 0, 2, 0, 0], "opacity": 1, "pixelSize": [2, 1], "colorMode": "rgb", "linked": false, "pixelsOmitted": false, "pixelsBase64": "AAAegGQAHoA="}, {"id": 19, "type": "symbolInstance", "bounds": [100, 0, 110, 10], "transform": [1, 0, 0, 1, 100, 0], "symbolId": "Star", "overrides": {}} @@ -691,7 +697,7 @@ every attribute: true` and empty `runs` and `paragraphs`. The runs and paragraphs of all the type in one input take at most 16 MiB of JSON: type whose runs and paragraphs don't fit what the type before it in paint order left comes with `truncated: true` too. -- An image (`"image"`): `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or +- An image (`"image"`): `opacity` is its opacity, 0 to 1; `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or `"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape that is not a parallelogram also has `corners`, its pixel rectangle's corners on the page (top left, top right, bottom right, bottom left), and its `transform` is then the affine placement nearest them, the one that matches the @@ -728,6 +734,49 @@ the objects after it are written. An output lists at most 100,000 objects, so a objects fails with `plug-in exceeded its object budget (more than 100000 read-only objects)`. An echo of them counts toward the 64 MiB output cap. +### Writing type, images and symbols + +A filter at `api` 3 whose manifest lists some of its `inputs` kinds in `writes`, with `doc.write` in its +`permissions`, may change the objects of those kinds it is given. It returns such an object as `{"id": 17}` alone, +exactly as given, or with the fields it changes; a field it leaves out keeps its value. Each kind takes these fields: + +| Kind | Fields a filter may change | +|------|----------------------------| +| `type` | `name`, `transform`, `text.runs`, `text.paragraphs` | +| `image` | `name`, `transform`, `opacity` | +| `symbolInstance` | `name`, `transform`, `symbolId` | + +```json +{"objects": [ + {"id": 17, "text": {"runs": [{"text": "Goodbye", "style": {"font_family": "Source Sans 3", "size": 14}}]}}, + {"id": 18, "transform": [2, 0, 0, 2, 50, 60], "opacity": 0.5}, + {"id": 19, "symbolId": "Moon"} +]} +``` + +- `name` is a string, or `null` for no name. +- `transform` is six finite numbers, each within ±4,000,000, that don't flatten the object to a line. The object moves + by the change from its given transform, so an image's distorted corners move with it. +- `text.runs` replaces the type's runs: each is `{text, style, inline?}` with the character attributes as the native + file stores them, and an attribute the host doesn't know is refused. There is at least one run, at most 4,096, and at + most 256 KiB of UTF-8 text; the runs written in one output take at most 16 MiB. A style that none of the type's runs + has needs a font family of 1 to 256 printable characters, a size from 0.1 to 1296 pt, and fills and strokes that a + path's appearance would take. Inline graphics stay where they were: the runs keep each `inline` run as it was given, + in the same order. The characters of threaded type, and of type with ruby, can't change, though their attributes can. + The runs and paragraphs of type given with `truncated: true` can't change. +- `text.paragraphs` holds one paragraph style per paragraph of the new text. With `text.runs` alone, each paragraph + keeps its style when the number of paragraphs stays the same; runs that add or join paragraphs move the styles with + the text, as typing the same change does. +- `opacity` is a number from 0 to 1. +- `symbolId` names a symbol in the document. An instance that shows another symbol loses its overrides, as Replace + Symbol does. + +Every other field, including `type`, `bounds`, `text.kind` and an image's pixels, stays read-only, and objects of these +kinds can't be added or left out. A changed read-only field or a value out of range refuses the whole output, naming +the object and the field (`objects[2] (id 18).opacity: must be a number from 0 to 1`), and the document and undo history +stay as they were. The changes of one run are one undo step, with the type laid out again; an output that changes +nothing records no undo step. The host never reads or gives a linked image's file when a filter writes. + ### Parameters `params` points at `params_len` bytes of UTF-8 JSON: the validated parameters, plus `_context`: @@ -889,6 +938,6 @@ per change of their input, parameters or paints (results are cached), not per fr importers that place files (File › Place reads only the built-in formats) or make type, images, layers or artboards. - Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces - it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see - [`inputs`](#reading-type-images-and-symbols)). + it returns), filters that add or delete type, images or symbol instances or change their pixels and other fields + (a filter at `api` 3 changes [some of their fields](#writing-type-images-and-symbols)). - Apply Last Effect and Last Effect work for plug-in effects; there is no "last filter" for object filters yet. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..7840e02eba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2662,6 +2662,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Bulk memory fuzz cases use the host's fuel constants:** `crates/engine/tests/plugin_fuzz.rs` samples runs around one slice of the instruction budget and lengths around the bytes one unit of fuel pays for with `vectorcraft_plugins`' own `FUEL_SLICE` and `BYTES_COPIED_PER_FUEL`, so the sampled cases move when either value changes. Regressions: `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in permissions (G17):** a manifest may list `permissions` (`doc.read`, `doc.write`, `state`, `effect.render`, `export.write`; the first three follow storytold/photocraft#662) and an `api` level; without the list a plug-in gets what its kind implies and installs as before. Install Plug-in… and File › Open show the name, id, version, file SHA-256 and each permission in plain words, with control and bidirectional characters escaped, and install nothing on Cancel; for a plug-in that lists permissions, `plugin.install` needs `grant` and folders install it only when it is granted. The grant is kept with the module's hash, a module asking for more asks again, and a filter run refuses output its permissions don't allow. Regressions: `crates/plugins/src/permissions.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. +- **Filter plug-ins change type, images and symbol instances (G17):** a filter at plug-in API level 3 lists in `writes` the kinds among its `inputs` it may change, with `doc.write` in its `permissions`, and may return those objects with changed fields: type's runs (characters and character attributes, inline graphics kept as they were) and paragraph styles, an image's transform and opacity, an instance's transform and the symbol it shows (one already in the document; its overrides are cleared as Replace Symbol clears them), and each one's name. Runs are held to the input's limits (4,096 runs and 256 KiB of text a type object, 16 MiB over the output), a style of the filter's own needs a font family and a size of 0.1 to 1296 pt and its paints are checked as a path's are, and the characters of threaded type and type with ruby stay as they were. Any other changed field, or a value out of range, refuses the run naming the object and the field, with the document unchanged. The changes are one undo step, and an output that changes nothing, for every filter, records none. Images now also come with their `opacity`. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. From 039728372749971baf5da5c17df7e150f901a738 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:50:07 -0800 Subject: [PATCH 020/107] MCP: regenerate the UI catalog for the Corners relative radii `cargo xtask ui-commands` copies the ui.corners description from crates/ui-egui/src/menus/ui_commands.rs into crates/mcp/src/ui_catalog.rs, so the headless MCP catalog now lists relativeRadii and the batch undo step. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..21cea6890a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.corners", "Corners…", "", - "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), relativeRadii (bool), radius (pt, or with relativeRadii a percentage of each corner's own maximum); double-clicking a corner widget opens it too): OK runs object.setLiveShape, as one command.batch undo step when relative radii give the corners different lengths", ), ( "ui.simplifyAuto", From 6280006e801d01b8b87e2347423b8a70ed3bb11f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:57:38 -0800 Subject: [PATCH 021/107] Plug-ins: a slider drag in the Appearance panel stays with its objects The Appearance panel kept a plug-in slider's drag value under the row's appearance item, effect index and parameter name only. When the selection changed while the button was down and the drag ended off the editor, the value stayed behind: the next object with the same effect, or the same object selected again, showed it in place of its own. The drag's interaction also stayed open, since the slider never saw its release. The kept value now carries the document and selection it was made for and the UI pass that last drew its row, and it is dropped when either changes or a pass does not draw the row. A drag that a pass did not draw (its row or the panel closed), or that ended with no value to keep, keeps what it previewed as one undo step and ends its interaction. The app checks this at the end of every pass, after the panels, as it does for the 3D panel's drags. Any other interaction is left open. The inline slider test now ends its drag on a value the canvas had not previewed yet, and checks that the drag keeps that exact value. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/panels/appearance.rs | 89 ++++++++++++-- crates/ui-egui/src/panels/appearance/tests.rs | 112 +++++++++++++++++- 3 files changed, 191 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..7e7a3f9328 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -654,6 +654,7 @@ impl VectorcraftApp { crate::toasts::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); + crate::panels::appearance::end_stale_slide(self, &ctx); if self.custom_titlebar { titlebar::resize_zones(ui); } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 8976502aa4..5287aa0f4d 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -16,7 +16,7 @@ //! fills/strokes for Duplicate and Delete. Delete on a selected Opacity row sets it back to //! Default (100%, Normal). -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, OnceLock, Weak}; use egui::{Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -555,6 +555,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // An empty spacer row at the end of the list. ui.allocate_exact_size(vec2(ui.available_width(), 10.0), Sense::hover()); }); + end_stale_slide(app, ui.ctx()); bottom(app, ui, node.as_deref(), sel); delete_key(app, ui); // A row's popup, beside the panel (in the same window when the panel floats). @@ -1378,6 +1379,8 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let params = editor_params(e); let mut change: Option<(String, Value)> = None; let mut slid: Option<(String, Value, widgets::Live)> = None; + // The objects a slider drag edits: the editor shows a drag's value for these alone. + let target = app.session.active().map(|d| (d.uid, d.selection.subjects().to_vec())); let mut edit = false; let built_in = built_in_effect(&e.id); // A plug-in effect's parameters are labelled, measured and shown as its manifest says. @@ -1457,7 +1460,7 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let dragged; let v = match manifest.and_then(|m| m.param(key)).and_then(|p| Some((p, p.ui.slider_range(&p.spec)?))) { Some((p, range)) => { - let (shown, edit) = param_slider_edit(ui, (item, k, key.as_str()), p, v, range); + let (shown, edit) = param_slider_edit(ui, (item, k, key.as_str()), &target, p, v, range); slid = edit.map(|(value, phase)| (key.clone(), value, phase)).or(slid.take()); dragged = shown; &dragged @@ -1513,7 +1516,9 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } if let Some((key, v, phase)) = slid { let p = aligned(app, json!({"item": item, "index": k, "params": {key: v}})); - super::live_run(app, "Effect Options", "effect.setParams", p, phase); + super::live_run(app, SLIDE_LABEL, "effect.setParams", p, phase); + let owner = if phase == widgets::Live::Dragging { slide_interaction(app) } else { None }; + set_pstate(ui.ctx(), SLIDE_OWNER, owner); } if edit { app.run("effect.dialog", aligned(app, json!({"effect": e.id, "index": k, "item": item}))).ok(); @@ -1526,28 +1531,91 @@ const NUMBER_W: f32 = 70.0; /// The narrowest a plug-in parameter's slider gets in [`effect_editor`]. const SLIDER_MIN_W: f32 = 24.0; +/// The UI pass that last drew a drag on a plug-in parameter's slider in [`effect_editor`] that has +/// not ended with a value to keep ([`end_stale_slide`]). +const SLIDE_LIVE: &str = "ap-fx-slide-live"; + +/// The interaction that a drag on a plug-in parameter's slider in [`effect_editor`] previews in +/// ([`slide_interaction`]). +const SLIDE_OWNER: &str = "ap-fx-slide-owner"; + +/// The undo step a drag on a plug-in parameter's slider in [`effect_editor`] is kept as. +const SLIDE_LABEL: &str = "Effect Options"; + +/// An interaction: its document's uid and the selection snapshot it previews from, which each +/// interaction makes anew when it begins and keeps while it lasts. +type SlideOwner = (u64, Weak); + +/// The interaction open in the active document, when it is one a plug-in parameter's slider starts. +fn slide_interaction(app: &VectorcraftApp) -> Option { + let d = app.session.active()?; + d.interaction.as_ref().filter(|it| it.label == SLIDE_LABEL).map(|it| (d.uid, Arc::downgrade(&it.selection))) +} + +/// A drag on a plug-in parameter's slider that this pass did not draw (its row closed, the +/// selection changed so the row is gone, or the panel closed), or that ended with no value to +/// keep, reports no release: the preview it made in its own interaction is kept as one undo step +/// and the interaction ends. Any other interaction is left alone. The panel runs this after its +/// rows, and the app at the end of every pass, after the panels. +pub(crate) fn end_stale_slide(app: &mut VectorcraftApp, ctx: &egui::Context) { + if pstate::>(ctx, SLIDE_LIVE).is_some_and(|pass| pass != root_pass(ctx)) { + let owner = pstate::>(ctx, SLIDE_OWNER); + let ours = match (owner, slide_interaction(app)) { + (Some((uid, snapshot)), Some((open, now))) => uid == open && snapshot.ptr_eq(&now), + _ => false, + }; + if ours { + if let Err(e) = app.session.commit_interaction() { + app.status(e.to_string()); + } + app.sync_views(); + } + set_pstate(ctx, SLIDE_LIVE, None::); + set_pstate(ctx, SLIDE_OWNER, None::); + } +} + +/// The main window's pass in progress. A floating window draws inside it and counts its own +/// passes, so the slider's marks use this one wherever the panel draws. +fn root_pass(ctx: &egui::Context) -> u64 { + ctx.cumulative_pass_nr_for(egui::ViewportId::ROOT) +} + /// What a drag on the slider of a plug-in effect's parameter in [`effect_editor`] keeps between -/// frames: the value it reached, and when it last previewed. +/// frames: the value it reached, and when it last previewed, for the objects (document and +/// selection) it edits, as of the UI pass that last drew it. #[derive(Clone, Debug, Default)] struct ParamSlide { value: Option, preview: crate::dialogs::SlidePreview, + target: Option<(u64, Vec)>, + pass: u64, } /// The slider of plug-in parameter `p` with value `v`, which asks for one, over `range`, in the row -/// `id` (appearance item, effect index and parameter name) → the value the row's number shows (a -/// drag's in progress, else `v`) and the edit to run with its phase ([`super::live_run`]): a click -/// or key as one undo step, and a drag previewed on the canvas about ten times a second -/// ([`crate::dialogs::SlidePreview`]) and kept as one undo step when it ends. +/// `id` (appearance item, effect index and parameter name) of the objects `target` (document and +/// selection) → the value the row's number shows (a drag's in progress, else `v`) and the edit to +/// run with its phase ([`super::live_run`]): a click or key as one undo step, and a drag previewed +/// on the canvas about ten times a second ([`crate::dialogs::SlidePreview`]) and kept as one undo +/// step when it ends. A drag's value is dropped when the selection or the document changes, or +/// after a pass that did not draw the row, so it never shows on or goes to other objects; a drag in +/// progress is noted under [`SLIDE_LIVE`] until it ends with a value to keep. fn param_slider_edit( ui: &mut Ui, id: (Option, usize, &str), + target: &Option<(u64, Vec)>, p: &vectorcraft_plugins::Param, v: &Value, range: std::ops::RangeInclusive, ) -> (Value, Option<(Value, widgets::Live)>) { let memory = egui::Id::unique(("fx-slide", id)); + let pass = root_pass(ui.ctx()); let mut slide: ParamSlide = ui.data(|d| d.get_temp(memory)).unwrap_or_default(); + if slide.target != *target || slide.pass.saturating_add(1) < pass { + slide = ParamSlide::default(); + } + slide.target.clone_from(target); + slide.pass = pass; let cur = slide.value.clone().unwrap_or_else(|| v.clone()); // The slider takes the room the row has left after the number field after it, so a narrow // panel keeps both in view. @@ -1565,6 +1633,11 @@ fn param_slider_edit( } else { new.map(|value| (value, widgets::Live::Released)) }; + if matches!(edit, Some((_, widgets::Live::Released))) { + set_pstate(ui.ctx(), SLIDE_LIVE, None::); + } else if resp.dragged() { + set_pstate(ui.ctx(), SLIDE_LIVE, Some(pass)); + } let shown = slide.value.clone().unwrap_or(cur); ui.data_mut(|d| { if slide.value.is_some() { diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 8efe31adfb..28945cf076 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -528,10 +528,18 @@ fn a_plug_in_slider_in_the_editor_previews_a_drag_and_keeps_it_as_one_step() { } } assert!(seen.len() > 2 && seen.len() < 15, "the canvas showed {} values in 30 frames: {seen:?}", seen.len()); - frame(&mut app, vec![button(at(0.85), false)]); + // One more move, too soon after the last preview to preview, then the release: the drag keeps + // the value it ended on, which the canvas had not shown yet. + let nodes = frame(&mut app, vec![egui::Event::PointerMoved(at(0.95))]); + let ended = nodes + .iter() + .find(|(_, n)| n.role() == Role::Slider && n.labelled_by().iter().any(|l| label_of(l).starts_with("Amount"))) + .and_then(|(_, n)| n.numeric_value()) + .expect("Amount's slider shows the value the drag reached"); + assert_ne!(params(&app)["amount"].as_f64(), Some(ended), "the last move previewed at once"); + frame(&mut app, vec![button(at(0.95), false)]); frame(&mut app, vec![]); - let kept = params(&app)["amount"].as_f64().unwrap(); - assert!(kept > 70.0 && kept <= 100.0, "the value the drag ended on: {kept}"); + assert_eq!(params(&app)["amount"].as_f64(), Some(ended), "the value the drag ended on"); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "the drag is one undo step"); assert!(!app.session.in_interaction(), "the drag's interaction ended"); // Count's slider: focused, an arrow moves it by its step of 2, as one more undo step. @@ -553,6 +561,104 @@ fn a_plug_in_slider_in_the_editor_previews_a_drag_and_keeps_it_as_one_step() { app.run("plugin.remove", json!({"id": "test.ui.inlineslider"})).unwrap(); } +/// A drag on a plug-in slider whose end the editor did not see, because the selection changed +/// while the button was down, keeps what it previewed as its undo step, ends its interaction and +/// leaves no value behind: the editor then shows each object's own value, for another object with +/// the same effect and for the object the drag started on. +#[test] +fn a_plug_in_slider_drag_s_value_stays_with_its_drag() { + use egui::accesskit::Role; + use vectorcraft_plugins::wat as tpl; + let params = r#"{"amount":{"type":"number","min":0,"max":100,"default":10,"label":"Amount","widget":"slider"}}"#; + let src = tpl::module(&tpl::manifest("test.ui.slideselection", "effect", params), tpl::ECHO, "", 1); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let add = |app: &mut VectorcraftApp, x: f64| { + let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.slideselection"})).unwrap(); + id + }; + let (a, b) = (add(&mut app, 0.0), add(&mut app, 40.0)); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ap-fx-open-None-0", true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let amount = + |app: &VectorcraftApp, id: u64| app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params["amount"].as_f64(); + let slider = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)]| { + nodes.iter().find(|(_, n)| n.role() == Role::Slider).and_then(|(_, n)| Some((n.numeric_value()?, n.bounds()?))) + }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for (back, name) in [(a, "the object the drag started on"), (b, "another object")] { + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + let (_, rail) = slider(&frame(&mut app, vec![])).expect("the slider shows"); + let at = |x: f64| egui::pos2((rail.x0 + x * (rail.x1 - rail.x0)) as f32, ((rail.y0 + rail.y1) / 2.0) as f32); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + // The first move previews at once; the next comes too soon and waits. + frame(&mut app, vec![egui::Event::PointerMoved(at(0.4))]); + let (reached, _) = slider(&frame(&mut app, vec![egui::Event::PointerMoved(at(0.7))])).expect("the slider shows"); + let previewed = amount(&app, a); + assert_ne!(previewed, Some(reached), "the second move previewed at once"); + assert!(app.session.in_interaction(), "the drag previews"); + // With the button still down, nothing is selected, and the button comes up off the editor: + // the drag keeps what it previewed, and its interaction ends. + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![button(at(0.7), false)]); + assert!(!app.session.in_interaction(), "{name}: the drag's interaction is still open"); + assert_eq!(amount(&app, a), previewed, "{name}: the drag did not keep its preview"); + app.run("select.set", json!({"ids": [back]})).unwrap(); + frame(&mut app, vec![]); + let (shown, _) = slider(&frame(&mut app, vec![])).expect("the slider shows"); + assert_eq!(Some(shown), amount(&app, back), "{name} shows the drag's value"); + } + // A drag whose interaction another one replaced, of the same name on the same document, leaves + // that one open when its row goes. + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + let (_, rail) = slider(&frame(&mut app, vec![])).expect("the slider shows"); + let at = |x: f64| egui::pos2((rail.x0 + x * (rail.x1 - rail.x0)) as f32, ((rail.y0 + rail.y1) / 2.0) as f32); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.5))]); + assert!(app.session.in_interaction(), "the drag previews"); + app.session.cancel_interaction().unwrap(); + app.session.begin_interaction("Effect Options").unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![button(at(0.5), false)]); + assert!(app.session.in_interaction(), "the other interaction was ended"); + app.session.cancel_interaction().unwrap(); + // A drag whose panel closes keeps what it previewed at the end of the first pass that does not + // draw the panel, as the app checks after its panels. + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.6))]); + let previewed = amount(&app, a); + assert!(app.session.in_interaction(), "the drag previews"); + for events in [vec![], vec![button(at(0.6), false)]] { + time += 1.0 / 60.0; + let input = egui::RawInput { events, time: Some(time), ..Default::default() }; + let _ = ctx.run_ui(input, |ui| crate::panels::appearance::end_stale_slide(&mut app, ui.ctx())); + assert!(!app.session.in_interaction(), "the drag's interaction is still open after the panel closed"); + } + assert_eq!(amount(&app, a), previewed, "the drag did not keep its preview"); + app.run("plugin.remove", json!({"id": "test.ui.slideselection"})).unwrap(); +} + /// Glass with a loaded texture lists Loaded Texture in its Texture menu, as its dialog does. #[test] fn the_effect_editor_lists_a_loaded_glass_texture() { From e53a643c86804abc933e75537040e06aa9dbfdc2 Mon Sep 17 00:00:00 2001 From: centy Date: Sun, 22 Nov 2026 08:42:40 -0500 Subject: [PATCH 022/107] 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 cbfc785886e29bbd91e9ebdaee2626a8e492f7ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:49:55 -0800 Subject: [PATCH 023/107] Plug-ins: a slider drag previews only in its own interaction - A drag on a plug-in parameter's slider in the Appearance panel notes the interaction it begins and previews and keeps values only in that one. An interaction that was open before the drag, or that replaced the drag's own while its row stays in view, is left as it is. - The slider is a widget of its own for each document and selection, so a release in the same pass as a change of selection does not reach the objects selected now. The objects the drag began on keep its last preview as one undo step. - A switch to another document during the drag keeps what it previewed as one undo step in the document it began in, instead of canceling it (Session::keep_interaction_on_switch). --- crates/engine/src/interaction.rs | 3 + crates/engine/src/session/documents.rs | 6 +- crates/engine/src/session/edit.rs | 10 ++ crates/ui-egui/src/panels/appearance.rs | 84 +++++++++- crates/ui-egui/src/panels/appearance/tests.rs | 156 ++++++++++++++++++ 5 files changed, 248 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 06cc86859e..d6b572535c 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -33,6 +33,9 @@ pub struct Interaction { /// The bounding box of `selection` in `doc`, measured once for a move drag /// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move. pub(crate) move_box: std::sync::OnceLock>, + /// A switch to another document keeps the preview as one undo step instead of canceling it + /// ([`crate::Session::keep_interaction_on_switch`]). + pub(crate) keep_on_switch: bool, } /// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]). diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..804ef2f494 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -218,9 +218,11 @@ impl Session { let _ = self.give_back_tool(view); let _ = self.deactivate_tool(view); // A batch leaves its interaction open in the document it leaves, to keep or roll back with - // the rest of the batch; anything else in progress (a drag) is cancelled. + // the rest of the batch; anything else in progress (a drag) is cancelled, except a drag on a + // panel's slider, which keeps its preview as one undo step there. if self.batch_stash.is_none() { - let _ = self.cancel_interaction(); + let keep = self.active().and_then(|d| d.interaction.as_ref()).is_some_and(|it| it.keep_on_switch); + let _ = if keep { self.commit_interaction() } else { self.cancel_interaction() }; } self.keep_tool_settings(); self.tool = self.make_tool(self.tool.id()); diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index e2ba1715b9..95827f0ff6 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -312,6 +312,7 @@ impl Session { plane_placed: false, copies: None, move_box: std::sync::OnceLock::new(), + keep_on_switch: false, }); Ok(()) } @@ -508,6 +509,15 @@ impl Session { Ok(()) } + /// Keep the open interaction's preview as one undo step, instead of canceling it, when another + /// document becomes active: a drag on a panel's slider, which keeps what it previewed when it + /// ends without a release. + pub fn keep_interaction_on_switch(&mut self) { + if let Some(it) = self.active_mut().and_then(|d| d.interaction.as_mut()) { + it.keep_on_switch = true; + } + } + pub fn in_interaction(&self) -> bool { self.active().is_some_and(|d| d.interaction.is_some()) } diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 5287aa0f4d..af504e8dac 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -1516,9 +1516,36 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } if let Some((key, v, phase)) = slid { let p = aligned(app, json!({"item": item, "index": k, "params": {key: v}})); - super::live_run(app, SLIDE_LABEL, "effect.setParams", p, phase); - let owner = if phase == widgets::Live::Dragging { slide_interaction(app) } else { None }; - set_pstate(ui.ctx(), SLIDE_OWNER, owner); + let hold = match pstate::(ui.ctx(), SLIDE_OWNER) { + // A drag that previewed goes on only in the interaction it began. + SlideHold::Live(owner) => { + if slide_interaction(app).is_some_and(|now| same_slide(&owner, &now)) { + SlideHold::Live(owner) + } else { + SlideHold::Lost + } + } + SlideHold::Lost => SlideHold::Lost, + SlideHold::Idle => begin_slide(app), + }; + match hold { + SlideHold::Live(owner) => { + super::live_run(app, SLIDE_LABEL, "effect.setParams", p, phase); + let next = if phase == widgets::Live::Dragging { SlideHold::Live(owner) } else { SlideHold::Idle }; + set_pstate(ui.ctx(), SLIDE_OWNER, next); + } + // The slider's own interaction could not begin: a click or a key still runs its edit. + SlideHold::Idle => { + if phase == widgets::Live::Released { + app.run("effect.setParams", p).ok(); + } + } + // Another interaction is open, or replaced the drag's own: the drag leaves it alone. + SlideHold::Lost => { + let next = if phase == widgets::Live::Dragging { SlideHold::Lost } else { SlideHold::Idle }; + set_pstate(ui.ctx(), SLIDE_OWNER, next); + } + } } if edit { app.run("effect.dialog", aligned(app, json!({"effect": e.id, "index": k, "item": item}))).ok(); @@ -1536,9 +1563,22 @@ const SLIDER_MIN_W: f32 = 24.0; const SLIDE_LIVE: &str = "ap-fx-slide-live"; /// The interaction that a drag on a plug-in parameter's slider in [`effect_editor`] previews in -/// ([`slide_interaction`]). +/// ([`SlideHold`]). const SLIDE_OWNER: &str = "ap-fx-slide-owner"; +/// Where a drag on a plug-in parameter's slider in [`effect_editor`] previews. +#[derive(Clone, Debug, Default)] +enum SlideHold { + /// No drag has previewed yet. + #[default] + Idle, + /// The drag previews in the interaction it began ([`slide_interaction`]). + Live(SlideOwner), + /// Another interaction was open when the drag began, or replaced the one it began: the drag + /// previews nothing and keeps nothing until it ends. + Lost, +} + /// The undo step a drag on a plug-in parameter's slider in [`effect_editor`] is kept as. const SLIDE_LABEL: &str = "Effect Options"; @@ -1552,6 +1592,30 @@ fn slide_interaction(app: &VectorcraftApp) -> Option { d.interaction.as_ref().filter(|it| it.label == SLIDE_LABEL).map(|it| (d.uid, Arc::downgrade(&it.selection))) } +/// Whether two [`SlideOwner`]s are the same interaction. +fn same_slide(a: &SlideOwner, b: &SlideOwner) -> bool { + a.0 == b.0 && a.1.ptr_eq(&b.1) +} + +/// Begin the interaction a drag on a plug-in parameter's slider previews in → [`SlideHold::Live`] +/// with it; [`SlideHold::Lost`] when another interaction is open, which beginning leaves as it is; +/// [`SlideHold::Idle`] when it could not begin (a script runs). A switch to another document during +/// the drag keeps what it previewed as one undo step in the document it began in. +fn begin_slide(app: &mut VectorcraftApp) -> SlideHold { + let open: Option = app.session.active().and_then(|d| d.interaction.as_ref().map(|it| (d.uid, Arc::downgrade(&it.selection)))); + if app.begin_interaction(SLIDE_LABEL).is_err() { + return SlideHold::Idle; + } + match slide_interaction(app) { + // One that was open before the drag, of the same name, is not the drag's own. + Some(now) if !open.is_some_and(|o| same_slide(&o, &now)) => { + app.session.keep_interaction_on_switch(); + SlideHold::Live(now) + } + _ => SlideHold::Lost, + } +} + /// A drag on a plug-in parameter's slider that this pass did not draw (its row closed, the /// selection changed so the row is gone, or the panel closed), or that ended with no value to /// keep, reports no release: the preview it made in its own interaction is kept as one undo step @@ -1559,9 +1623,8 @@ fn slide_interaction(app: &VectorcraftApp) -> Option { /// rows, and the app at the end of every pass, after the panels. pub(crate) fn end_stale_slide(app: &mut VectorcraftApp, ctx: &egui::Context) { if pstate::>(ctx, SLIDE_LIVE).is_some_and(|pass| pass != root_pass(ctx)) { - let owner = pstate::>(ctx, SLIDE_OWNER); - let ours = match (owner, slide_interaction(app)) { - (Some((uid, snapshot)), Some((open, now))) => uid == open && snapshot.ptr_eq(&now), + let ours = match (pstate::(ctx, SLIDE_OWNER), slide_interaction(app)) { + (SlideHold::Live(owner), Some(now)) => same_slide(&owner, &now), _ => false, }; if ours { @@ -1571,7 +1634,7 @@ pub(crate) fn end_stale_slide(app: &mut VectorcraftApp, ctx: &egui::Context) { app.sync_views(); } set_pstate(ctx, SLIDE_LIVE, None::); - set_pstate(ctx, SLIDE_OWNER, None::); + set_pstate(ctx, SLIDE_OWNER, SlideHold::Idle); } } @@ -1621,7 +1684,10 @@ fn param_slider_edit( // panel keeps both in view. let room = ui.available_width() - NUMBER_W - 2.0 * ui.spacing().item_spacing.x; let width = room.clamp(SLIDER_MIN_W, crate::dialogs::PARAM_SLIDER_WIDTH); - let (new, resp) = crate::dialogs::plugin_slider(ui, ("fx-slider", id), &p.spec, &cur, range, p.ui.step, width); + // The slider is a widget of its own for each document and selection, so a drag on it ends when + // they change and sends no more values: the objects the drag began on keep what it previewed + // ([`end_stale_slide`]), and the others stay as they are. + let (new, resp) = crate::dialogs::plugin_slider(ui, ("fx-slider", id, target), &p.spec, &cur, range, p.ui.step, width); let edit = if resp.drag_stopped() { // The value the drag ended on, kept even when its last preview waited. new.or(std::mem::take(&mut slide).value).map(|value| (value, widgets::Live::Released)) diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 28945cf076..df827eba40 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -659,6 +659,162 @@ fn a_plug_in_slider_drag_s_value_stays_with_its_drag() { app.run("plugin.remove", json!({"id": "test.ui.slideselection"})).unwrap(); } +/// A drag on a plug-in slider ends when another object with the same effect is selected while the +/// button is down: the object the drag began on keeps what the drag previewed, as one undo step, and +/// the other object stays selected and unchanged, also when the button comes up in the same pass. +/// A drag also leaves alone an interaction that it did not begin: one that replaced its own while +/// its row stays in view, and one that was open before it began. +#[test] +fn a_plug_in_slider_drag_ends_on_another_object_and_leaves_other_interactions_alone() { + use egui::accesskit::Role; + use vectorcraft_plugins::wat as tpl; + let params = r#"{"amount":{"type":"number","min":0,"max":100,"default":10,"label":"Amount","widget":"slider"}}"#; + let src = tpl::module(&tpl::manifest("test.ui.slideswitch", "effect", params), tpl::ECHO, "", 1); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let add = |app: &mut VectorcraftApp, x: f64| { + let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.slideswitch"})).unwrap(); + id + }; + let (a, b) = (add(&mut app, 0.0), add(&mut app, 40.0)); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ap-fx-open-None-0", true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let amount = + |app: &VectorcraftApp, id: u64| app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params["amount"].as_f64(); + let slider = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)]| { + nodes.iter().find(|(_, n)| n.role() == Role::Slider).and_then(|(_, n)| n.bounds()) + }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let open_preview = |app: &VectorcraftApp| app.session.doc().unwrap().interaction.as_ref().map(|it| it.preview.is_some()); + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + let rail = slider(&frame(&mut app, vec![])).expect("the slider shows"); + let at = |x: f64| egui::pos2((rail.x0 + x * (rail.x1 - rail.x0)) as f32, ((rail.y0 + rail.y1) / 2.0) as f32); + // B is selected while the button is down, and the button comes up in the next pass. + let steps = undo(&app); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.4))]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.7))]); + let previewed = amount(&app, a); + assert_ne!(previewed, Some(10.0), "the drag previews"); + app.run("select.set", json!({"ids": [b]})).unwrap(); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.9)), button(at(0.9), false)]); + frame(&mut app, vec![]); + assert!(!app.session.in_interaction(), "the drag's interaction is still open"); + assert_eq!(amount(&app, a), previewed, "the drag did not keep only what it previewed"); + assert_eq!(amount(&app, b), Some(10.0), "the drag changed the other object"); + let sel = &app.session.doc().unwrap().selection; + assert!(sel.len() == 1 && sel.contains(NodeId(b)), "the other object is no longer the selection"); + assert_eq!(undo(&app), steps + 1, "the drag is one undo step"); + // A drag whose interaction another one replaced, of the same name, while its row stays in view. + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let before = amount(&app, a); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.5))]); + assert_eq!(open_preview(&app), Some(true), "the drag previews"); + app.session.cancel_interaction().unwrap(); + app.session.begin_interaction("Effect Options").unwrap(); + for i in 1..=12 { + frame(&mut app, vec![egui::Event::PointerMoved(at(0.5 + 0.03 * i as f64))]); + } + frame(&mut app, vec![button(at(0.9), false)]); + frame(&mut app, vec![]); + assert_eq!(open_preview(&app), Some(false), "the drag previewed in, or ended, the interaction that replaced it"); + assert_eq!(amount(&app, a), before, "the drag changed the object"); + app.session.cancel_interaction().unwrap(); + // A drag that begins while another interaction is open. + app.session.begin_interaction("Move").unwrap(); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + for i in 1..=12 { + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2 + 0.05 * i as f64))]); + } + frame(&mut app, vec![button(at(0.8), false)]); + frame(&mut app, vec![]); + assert_eq!(open_preview(&app), Some(false), "the drag previewed in, or ended, the interaction open before it"); + assert_eq!(amount(&app, a), before, "the drag changed the object"); + app.session.cancel_interaction().unwrap(); + // A drag after them previews and keeps its value again. + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.6))]); + frame(&mut app, vec![button(at(0.6), false)]); + frame(&mut app, vec![]); + assert!(!app.session.in_interaction(), "the drag's interaction is still open"); + assert_ne!(amount(&app, a), before, "the drag kept nothing"); + app.run("plugin.remove", json!({"id": "test.ui.slideswitch"})).unwrap(); +} + +/// A drag on a plug-in slider keeps what it previewed as one undo step in its own document when +/// another document becomes active while the button is down (as the keyboard switches documents). +#[test] +fn a_plug_in_slider_drag_keeps_its_preview_when_another_document_becomes_active() { + use egui::accesskit::Role; + use vectorcraft_plugins::wat as tpl; + let params = r#"{"amount":{"type":"number","min":0,"max":100,"default":10,"label":"Amount","widget":"slider"}}"#; + let src = tpl::module(&tpl::manifest("test.ui.slidedoc", "effect", params), tpl::ECHO, "", 1); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + assert!(app.session.set_active(0)); + let a = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.slidedoc"})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ap-fx-open-None-0", true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 1.0 / 60.0; + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let amount = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(NodeId(a)).unwrap().appearance.effects[0].params["amount"].as_f64(); + let slider = |nodes: &[(egui::accesskit::NodeId, egui::accesskit::Node)]| { + nodes.iter().find(|(_, n)| n.role() == Role::Slider).and_then(|(_, n)| n.bounds()) + }; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, vec![]); + let rail = slider(&frame(&mut app, vec![])).expect("the slider shows"); + let at = |x: f64| egui::pos2((rail.x0 + x * (rail.x1 - rail.x0)) as f32, ((rail.y0 + rail.y1) / 2.0) as f32); + let steps = app.session.doc().unwrap().history.undo.len(); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.2))]); + frame(&mut app, vec![button(at(0.2), true)]); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.6))]); + let previewed = amount(&app); + assert_ne!(previewed, Some(10.0), "the drag previews"); + assert!(app.session.set_active(1)); + frame(&mut app, vec![egui::Event::PointerMoved(at(0.8))]); + frame(&mut app, vec![button(at(0.8), false)]); + assert!(!app.session.in_interaction(), "the other document has an interaction open"); + assert!(app.session.set_active(0)); + assert!(!app.session.in_interaction(), "the drag's interaction is still open"); + assert_eq!(amount(&app), previewed, "the drag did not keep its preview"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the drag is not one undo step"); + app.run("plugin.remove", json!({"id": "test.ui.slidedoc"})).unwrap(); +} + /// Glass with a loaded texture lists Loaded Texture in its Texture menu, as its dialog does. #[test] fn the_effect_editor_lists_a_loaded_glass_texture() { From 0d4780e33cd241866b1e13b7304fd51ce0396c1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:03:49 -0800 Subject: [PATCH 024/107] Export: GIF and PNG-8 take the Transparency Dither settings document.export reads transparencyDither (none, diffusion, pattern or noise) and transparencyDitherAmount (0 to 100) for GIF and PNG-8 with the same ids as Save for Web, and refuses an unknown method or an amount outside 0 to 100. Other formats do not read the keys, and the warnings name them as not used. GIF and PNG-8 Options show Transparency Dither and, for Diffusion, its Amount, disabled while Transparency is off. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/encode.rs | 28 +++++++ crates/engine/src/cmd/fileio/formats.rs | 16 ++++ crates/engine/src/cmd/fileio/tests_palette.rs | 78 ++++++++++++++++++- crates/ui-egui/src/dialogs/png_options.rs | 34 +++++++- .../src/dialogs/tests_raster_formats.rs | 57 ++++++++++++++ docs/mcp.md | 7 ++ docs/target-app-parity.md | 1 + 8 files changed, 219 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a41831b200..0b22c40962 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 23b7a1c13f..b308f874ab 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -256,6 +256,11 @@ struct RasterOptions { dither: Option, dither_amount: Option, transparency: Option, + /// GIF and PNG-8 with `transparency`: none, diffusion, pattern or noise, read by + /// [`RasterOptions::transparency_dither`] (other formats do not check it). + transparency_dither: Option, + /// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is. + transparency_dither_amount: Option, matte: Option, lossless: Option, lzw: Option, @@ -295,6 +300,26 @@ impl RasterOptions { } } + /// GIF and PNG-8: `transparencyDither` (absent: none, which cuts at half opacity, not + /// `Dither`'s own default) and `transparencyDitherAmount` (0–100, default 100), or an error. + fn transparency_dither(&self) -> Result<(Dither, u8)> { + const IDS: &str = "none, diffusion, pattern or noise"; + let method = match &self.transparency_dither { + None | Some(Value::Null) => PaletteOptions::default().transparency_dither, + Some(Value::String(s)) => parse(Some(s), Dither::from_id, "transparencyDither", IDS)?, + Some(v) => return Err(bad(C, format!("transparencyDither must be {IDS}, not {v}"))), + }; + let amount = match &self.transparency_dither_amount { + None | Some(Value::Null) => 100, + Some(v) => v + .as_u64() + .filter(|n| *n <= 100) + .and_then(|n| u8::try_from(n).ok()) + .ok_or_else(|| bad(C, format!("transparencyDitherAmount must be a whole number from 0 to 100, not {v}")))?, + }; + Ok((method, amount)) + } + /// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set. fn pixel_size(&self) -> Result> { let checked = |key: &str, n: f64| { @@ -1159,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { { return Err(bad(C, format!("quality {q}: WebP quality is 0–100"))); } + if matches!(format, RasterFormat::Gif | RasterFormat::Png8) { + (settings.palette.transparency_dither, settings.palette.transparency_dither_amount) = o.transparency_dither()?; + } check_options(format, &settings)?; // Use Artboards: one file per chosen artboard (default all); else the one chosen. let chosen = match use_artboards { diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 0db990ad4c..92a417d7d2 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -195,6 +195,20 @@ const TRANSPARENCY: FormatOption = FormatOption { description: "pixels under half opacity become one transparent entry (false: everything is blended over the matte)", }; +const TRANSPARENCY_DITHER: FormatOption = FormatOption { + name: "transparencyDither", + ty: "string", + default: "\"none\"", + description: "with transparency, how partly transparent pixels are split between the transparent entry and their color: none (cut at half opacity), diffusion, pattern (8×8 ordered) or noise", +}; + +const TRANSPARENCY_DITHER_AMOUNT: FormatOption = FormatOption { + name: "transparencyDitherAmount", + ty: "integer", + default: "100", + description: "the diffusion transparency dither's strength 0–100 (0 cuts at half opacity; more than 100 is refused)", +}; + const MATTE: FormatOption = FormatOption { name: "matte", ty: "string", @@ -235,6 +249,8 @@ const PALETTE_OPTIONS: &[FormatOption] = &[ DITHER, DITHER_AMOUNT, TRANSPARENCY, + TRANSPARENCY_DITHER, + TRANSPARENCY_DITHER_AMOUNT, MATTE, ]; diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs index e54aababec..d27166e5da 100644 --- a/crates/engine/src/cmd/fileio/tests_palette.rs +++ b/crates/engine/src/cmd/fileio/tests_palette.rs @@ -86,6 +86,80 @@ fn png8_and_gif_export_palettes() { } } +/// The shares of opaque pixels in the left and right halves of a 40×30 image file. +fn opaque_halves(file: &[u8]) -> [f64; 2] { + let img = craft_image_codecs::decode(file).unwrap(); + assert_eq!(img.dimensions(), (40, 30)); + let alpha: Vec = img.to_rgba8().chunks(4).map(|p| p[3]).collect(); + [0, 20].map(|x0| (0..30).flat_map(|y| (x0..x0 + 20).map(move |x| y * 40 + x)).filter(|&i| alpha[i] == 255).count() as f64 / 600.0) +} + +/// GIF and PNG-8 exports take Save for Web's `transparencyDither` and `transparencyDitherAmount`. +#[test] +fn palette_exports_take_the_transparency_dither() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 30})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 25})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 20, "height": 30})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 75})).unwrap(); + for format in ["gif", "png8"] { + let mut file = |extra: Value| { + let p = merge(json!({"format": format, "background": "transparent", "antiAlias": "none"}), extra); + b64(&s.execute("document.export", &p).unwrap()) + }; + // By default the pixels under half opacity are transparent and the others opaque. + let none = file(json!({})); + assert_eq!(opaque_halves(&none), [0.0, 1.0], "{format}"); + assert_eq!(file(json!({"transparencyDither": "none"})), none, "{format}"); + assert_eq!(file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}"); + for method in ["diffusion", "pattern", "noise"] { + let dithered = file(json!({"transparencyDither": method})); + let [left, right] = opaque_halves(&dithered); + assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file"); + // Without transparency the dither does nothing. + let opaque = file(json!({"transparencyDither": method, "transparency": false})); + assert_eq!(opaque, file(json!({"transparency": false})), "{format} {method}"); + } + let weaker = opaque_halves(&file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40}))); + assert!(weaker[0] < 0.25 && weaker[1] > 0.75, "{format}: {weaker:?}"); + // null is the same as leaving a key out. + assert_eq!(file(json!({"transparencyDither": null, "transparencyDitherAmount": null})), none, "{format}"); + for bad in [ + json!({"transparencyDither": "spray"}), + json!({"transparencyDither": 3}), + json!({"transparencyDitherAmount": 101}), + json!({"transparencyDitherAmount": -1}), + json!({"transparencyDitherAmount": "50"}), + json!({"transparencyDitherAmount": 50.5}), + ] { + assert!(s.execute("document.export", &merge(json!({"format": format}), bad.clone())).is_err(), "{format} {bad}"); + } + let e = s.execute("document.export", &json!({"format": format, "transparencyDitherAmount": 101})).unwrap_err().to_string(); + assert!(e.contains("transparencyDitherAmount must be a whole number from 0 to 100, not 101"), "{e}"); + let e = s.execute("document.export", &json!({"format": format, "transparencyDither": "spray"})).unwrap_err().to_string(); + assert!(e.contains("transparencyDither `spray`: none, diffusion, pattern or noise"), "{e}"); + let e = s.execute("document.export", &json!({"format": format, "transparencyDither": 3})).unwrap_err().to_string(); + assert!(e.contains("transparencyDither must be none, diffusion, pattern or noise, not 3"), "{e}"); + } + // Formats without a palette do not read the keys: their values are not checked, and the + // warnings name them. + for format in ["png", "jpg", "tiff"] { + for keys in [ + json!({"transparencyDither": "spray", "transparencyDitherAmount": 101}), + json!({"transparencyDither": 3, "transparencyDitherAmount": "50"}), + ] { + let r = s.execute("document.export", &merge(json!({"format": format}), keys.clone())); + let w = r.unwrap_or_else(|e| panic!("{format} {keys}: {e}"))["warnings"].to_string(); + assert!(w.contains("`transparencyDither` was not used") && w.contains("`transparencyDitherAmount` was not used"), "{format}: {w}"); + } + } +} + #[test] fn palette_formats_reach_export_as_and_screens() { let mut s = session(); @@ -94,7 +168,9 @@ fn palette_formats_reach_export_as_and_screens() { let f = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone(); assert_eq!((f("png8")["extensions"][0].as_str(), f("png8")["read"].as_bool()), (Some("png"), Some(false))); assert_eq!(f("gif")["write"], true); - for k in ["colors", "reduction", "dither", "ditherAmount", "transparency", "matte", "interlaced"] { + for k in + ["colors", "reduction", "dither", "ditherAmount", "transparency", "transparencyDither", "transparencyDitherAmount", "matte", "interlaced"] + { assert!(f("gif")["options"].get(k).is_some() && f("png8")["options"].get(k).is_some(), "{k}"); } assert_eq!(format_for_name("a.png").unwrap().id, "png"); diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index ae70d682c4..1799a62373 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -1,7 +1,7 @@ //! The raster export options: PNG Options (resolution, background, anti-aliasing, interlaced), //! JPEG Options (no transparency; colour model, quality 0–10, method and scans, profile, image //! map), WebP Options (lossless, or lossy at a quality 0–100), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither, -//! transparency and matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options +//! transparency and its dither, matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options //! ([`super::psd_options`]). Fields //! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the //! dialog's. @@ -13,6 +13,7 @@ use vectorcraft_render::AntiAlias; use vectorcraft_render::encode::jpeg::{self, ColorModel, Method}; use vectorcraft_render::encode::quantize::{Dither, PaletteOptions, Reduction}; +use super::save_for_web::TRANSPARENCY_DITHERS; use super::{DialogSpec, form, psd_options, tiff_bmp_tga}; use crate::state::Dialog; use crate::theme::Tokens; @@ -113,6 +114,8 @@ pub(super) fn defaults(app: &VectorcraftApp, f: &Format) -> Map { ("dither".into(), json!(p.dither.id())), ("ditherAmount".into(), json!(p.dither_amount)), ("transparency".into(), json!(p.transparency)), + ("transparencyDither".into(), json!(p.transparency_dither.id())), + ("transparencyDitherAmount".into(), json!(p.transparency_dither_amount)), ("matte".into(), json!(MATTES[1])), ("interlaced".into(), json!(false)), ]); @@ -297,7 +300,7 @@ fn method_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, & } /// The PNG-8 and GIF Options rows: the palette (reduction, colours, dither and amount), -/// transparency and matte, interlacing. +/// transparency and matte, interlacing, and Transparency Dither with its amount. fn palette_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { label(ui, tl!("Color Reduction:")); choice(ui, d, "reduction", &Reduction::ALL.map(Reduction::id), &Reduction::ALL.map(Reduction::label)); @@ -346,6 +349,33 @@ fn palette_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, form::check(ui, d, "interlaced", tl!("Interlaced")); }); ui.end_row(); + + // Disabled while Transparency is off, keeping its values. The dropdown is named by the row's + // label, and the amount field by its own Amount label. + let name = crate::i18n::colon(tl!("Transparency Dither")); + label(ui, &name); + ui.add_enabled_ui(d.bool("transparency"), |ui| { + ui.horizontal(|ui| { + let labels = TRANSPARENCY_DITHERS.map(|(_, label)| label); + let cur = d.str("transparencyDither"); + let at = TRANSPARENCY_DITHERS.iter().position(|(id, _)| id.eq_ignore_ascii_case(&cur)).unwrap_or(0); + if let Some((id, _)) = + widgets::dropdown_named(ui, ("ro", "transparencyDither"), Some(&name), labels.get(at).copied().unwrap_or_default(), &labels, 150.0) + .and_then(|i| TRANSPARENCY_DITHERS.get(i)) + { + d.fields.insert("transparencyDither".into(), json!(id)); + } + if Dither::from_id(&d.str("transparencyDither")) == Some(Dither::Diffusion) { + widgets::dim_label(ui, "Amount:"); + if let Some(amount) = + widgets::range_field(ui, "transparencyDitherAmount", d.f64("transparencyDitherAmount", 100.0), 0.0..=100.0, "%", 0, 52.0) + { + d.fields.insert("transparencyDitherAmount".into(), json!(amount as u8)); + } + } + }); + }); + ui.end_row(); } /// A colour button bound to `d.fields[key]` (`"#rrggbb"`; grey when unset). diff --git a/crates/ui-egui/src/dialogs/tests_raster_formats.rs b/crates/ui-egui/src/dialogs/tests_raster_formats.rs index 4e4061ca75..704757cfd1 100644 --- a/crates/ui-egui/src/dialogs/tests_raster_formats.rs +++ b/crates/ui-egui/src/dialogs/tests_raster_formats.rs @@ -79,6 +79,63 @@ fn palette_options_reduce_the_colours() { assert_eq!(png[25], 3, "indexed"); } +/// GIF and PNG-8 Options start with No Transparency Dither at amount 100 and send the chosen +/// method and amount, which change the file of partly transparent art. +#[test] +fn palette_options_send_the_transparency_dither() { + let (mut app, written) = app(1); + app.run("transparency.set", json!({"opacity": 40})).unwrap(); + let export = |app: &mut VectorcraftApp, format: &str, fields: &[(&str, serde_json::Value)]| { + app.run("file.exportAs", json!({"format": format})).unwrap(); + confirm(app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("transparencyDither"), d.f64("transparencyDitherAmount", 0.0)), ("none".into(), 100.0), "{format}"); + for (k, v) in fields { + set(app, k, v.clone()); + } + frame(app); + confirm(app).unwrap(); + written.borrow().last().unwrap().1.clone() + }; + for format in ["gif", "png8"] { + let none = export(&mut app, format, &[]); + let diffusion = export(&mut app, format, &[("transparencyDither", json!("diffusion")), ("transparencyDitherAmount", json!(100))]); + assert_ne!(diffusion, none, "{format}"); + assert_eq!(export(&mut app, format, &[("transparencyDither", json!("diffusion")), ("transparencyDitherAmount", json!(0))]), none, "{format}"); + assert_ne!(export(&mut app, format, &[("transparencyDither", json!("pattern"))]), none, "{format}"); + // With Transparency off the rows are disabled, keep their values and change nothing. + let opaque = export(&mut app, format, &[("transparency", json!(false))]); + assert_eq!(export(&mut app, format, &[("transparency", json!(false)), ("transparencyDither", json!("noise"))]), opaque, "{format}"); + } +} + +/// The Transparency Dither dropdown is named by its row, and Diffusion's amount field by its +/// Amount label. +#[test] +fn palette_options_name_the_transparency_dither_controls() { + use egui::accesskit::Role; + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png8"})).unwrap(); + confirm(&mut app).unwrap(); + set(&mut app, "transparencyDither", json!("diffusion")); + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let mut nodes = vec![]; + for time in [0.0, 0.1] { + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(&mut app, ui.ctx())); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + // A label node carries its text as its value. + let label_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + assert!(nodes.iter().any(|(_, n)| n.label() == Some("Transparency Dither:") && n.role() != Role::Label), "a dropdown named by its row"); + let amount = nodes.iter().find(|(_, n)| n.labelled_by().iter().any(|l| label_of(*l).as_deref() == Some("Amount:"))); + assert!(amount.is_some(), "a field labeled Amount:"); +} + #[test] fn text_export_options_write_the_stories() { let (mut app, written) = app(1); diff --git a/docs/mcp.md b/docs/mcp.md index d254c9bfdc..35869c3130 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1435,6 +1435,13 @@ a larger file. A lossy file keeps the alpha exactly when some pixels are not opa that is not a whole number, is refused; a lossless file ignores `quality`. Export for Screens takes both in a WebP row or in `settings.webp`. +GIF and PNG-8 exports take Save for Web's `transparencyDither` (`none`, the default, `diffusion`, `pattern` or `noise`) +and `transparencyDitherAmount` (0 to 100, default 100) next to `dither` and `ditherAmount`, and they change the file as +in `document.exportForWeb`: with `transparency` on, some partly transparent pixels become transparent and the rest keep +their color, and without `transparency` the keys do not change the file. For GIF and PNG-8 an unknown method, or an +amount that is not a whole number from 0 to 100, is refused; other formats do not read the keys, and the warnings name +them. GIF and PNG-8 Options show both as Transparency Dither and its amount, disabled while Transparency is off. + `shape.ellipse` (and `draw_shape` with `shape: "ellipse"`) takes `anchors`, the number of smooth anchors (default 4). Without it, or at 4, it draws a live ellipse. Any other count from 2 to 1000 draws a closed plain path with that many anchors spaced evenly by angle, clockwise from the left one and fitted to `width` × `height`. The Ellipse dialog (a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff412268d1..bc69371014 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1007,6 +1007,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - Save for Web: with Transparency on, GIF and PNG-8 offer Transparency Dither (No Transparency Dither, Diffusion, Pattern and Noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an Amount for Diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is No Transparency Dither with Amount 100; with Pattern, Noise, or Diffusion at Amount 100, about as many pixels stay opaque as their opacity says, and a lower Diffusion Amount comes closer to No Transparency Dither; Pattern uses an 8×8 ordered pattern and Noise a fixed noise, so the same art always gives the same file; Amount 0 gives the same file as No Transparency Dither; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; both rows are disabled while Transparency is off and keep their values; presets and the remembered settings keep them (`transparencyDither`, `transparencyDitherAmount`). + - Export As: GIF and PNG-8 Options offer the same Transparency Dither and Amount as Save for Web, disabled while Transparency is off, and `document.export` takes `transparencyDither` and `transparencyDitherAmount` for GIF and PNG-8 with the same values, refusing an unknown method or an amount that is not a whole number from 0 to 100; other formats do not read the keys, and the warnings name them. Using Save for Web's keys in the other export is VectorCraft's own rule. `crates/engine/src/cmd/fileio/tests_palette.rs` (`palette_exports_take_the_transparency_dither`), `crates/ui-egui/src/dialogs/tests_raster_formats.rs` (`palette_options_send_the_transparency_dither`, `palette_options_name_the_transparency_dither_controls`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). From 945d0a42b07a8934d72007cbcfe769dbdb376dd7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:24:25 -0800 Subject: [PATCH 025/107] Plug-ins: check every number in the type styles a filter writes Type a filter returned went to layout with its character and paragraph styles only parsed, and a style equal to one of the type's runs was not checked at all, so a filter could set leading of 1e9, 100,000 tab stops, a scale of 0 or a Kinsoku set the document does not have. - The ranges the character and paragraph style commands keep each attribute to move to CharStyle::check_ranges and ParaStyle::check_ranges in vectorcraft-doc (text/attr_ranges.rs). charStyle.new, charStyle.edit, charStyle.setAttrs and the paragraph style commands call them, and so does the filter write path, for every run and paragraph style, including one the type already has. - A paragraph style's custom Kinsoku set must name one of the document's sets, and takes that set's characters. - The character style commands now also refuse tracking and kerning outside -1000 to 10000, rotation outside -360 to 360, a miter limit outside 1 to 500, Small Caps outside 1 to 200, negative dash lengths and a variable font axis setting that is not a number. Each refusal names the object and the field, and the document does not change. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md. --- crates/doc/src/text.rs | 4 + crates/doc/src/text/attr_ranges.rs | 215 ++++++++++++++++++++++ crates/doc/src/text/tests.rs | 39 ++++ crates/engine/src/cmd/panelcmds.rs | 2 +- crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/src/cmd/textstyles.rs | 141 ++------------ crates/engine/src/cmd/textstyles/tests.rs | 9 +- crates/plugins/src/objects/tests.rs | 82 ++++++++- crates/plugins/src/objects/writes.rs | 53 ++++-- docs/mcp.md | 6 +- docs/plugins.md | 23 ++- docs/target-app-parity.md | 4 +- 12 files changed, 422 insertions(+), 158 deletions(-) create mode 100644 crates/doc/src/text/attr_ranges.rs diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 107ac1dab9..cb2fa88deb 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -7,6 +7,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2}; use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer}; mod area; +mod attr_ranges; mod char_style; mod composite; mod kinsoku_set; @@ -17,6 +18,9 @@ mod tabs_lists; mod wrap; pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape}; +pub use attr_ranges::{ + AttrRangeError, CHAR_MITER_LIMIT, CHAR_ROTATION, CHAR_SCALE, CHAR_SPACING, FONT_SIZE, LEADING, MAX_BASELINE_SHIFT, MAX_PARA_DISTANCE, +}; use char_style::yes; pub use char_style::{ CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME, diff --git a/crates/doc/src/text/attr_ranges.rs b/crates/doc/src/text/attr_ranges.rs new file mode 100644 index 0000000000..bce0098ac2 --- /dev/null +++ b/crates/doc/src/text/attr_ranges.rs @@ -0,0 +1,215 @@ +//! The ranges the character and paragraph style commands keep each numeric attribute to, checked +//! in one place: the style commands check the attributes a call changes, and type a plug-in +//! returns has every attribute checked. + +use std::fmt; +use std::ops::RangeInclusive; + +use super::{CharStyle, JustificationOptions, ParaStyle, TabStop}; + +/// Font size ([`CharStyle::size`]), in points. +pub const FONT_SIZE: RangeInclusive = 0.1..=1296.0; +/// Leading ([`CharStyle::leading`]) other than Auto, in points. +pub const LEADING: RangeInclusive = 0.1..=5000.0; +/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent. +pub const CHAR_SCALE: RangeInclusive = 1.0..=10000.0; +/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`], +/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em. +pub const CHAR_SPACING: RangeInclusive = -1000.0..=10000.0; +/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points. +pub const MAX_BASELINE_SHIFT: f64 = 1296.0; +/// Character rotation ([`CharStyle::rotation`]), in degrees. +pub const CHAR_ROTATION: RangeInclusive = -360.0..=360.0; +/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]). +pub const CHAR_MITER_LIMIT: RangeInclusive = 1.0..=500.0; +/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points. +pub const MAX_PARA_DISTANCE: f64 = 1296.0; + +/// An attribute outside the range the style commands keep it to. +#[derive(Clone, Debug, PartialEq)] +pub struct AttrRangeError { + /// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`). + pub key: String, + /// What is wrong, naming the attribute. + pub message: String, +} + +impl fmt::Display for AttrRangeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for AttrRangeError {} + +fn out(key: &str, message: String) -> AttrRangeError { + AttrRangeError { key: key.to_string(), message } +} + +/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside). +fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> { + if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) } +} + +impl CharStyle { + /// Checks each numeric attribute `check` names, by its JSON key, against the range the + /// character style commands keep it to: size, leading, scales, tracking, kerning, baseline + /// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert + /// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the + /// variable font axes. The first attribute out of its range is the error. + pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> { + for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] { + if check(key) { + within(key, value, *range.start(), *range.end())?; + } + } + if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) { + let (lo, hi) = (LEADING.start(), LEADING.end()); + return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto"))); + } + let shift = MAX_BASELINE_SHIFT; + for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] { + if check(key) { + within(key, value, -shift, shift)?; + } + } + let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))]; + for (key, value) in spacing { + if check(key) + && let Some(value) = value + { + within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?; + } + } + if check("rotation") { + within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?; + } + for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] { + if check(key) { + within(key, value, 0.0, super::MAX_AKI)?; + } + } + if check("tsume") { + within("tsume", self.tsume, 0.0, super::MAX_TSUME)?; + } + let hi = super::MAX_DIACRITIC_POSITION; + for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] { + if check(key) { + within(key, value, -hi, hi)?; + } + } + let lines = super::WARICHU_LINES; + if check("warichuLines") && !lines.contains(&self.warichu_lines) { + return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); + } + let scale = super::WARICHU_SCALE; + for (key, value, lo, hi) in + [("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())] + { + if check(key) { + within(key, value, lo, hi)?; + } + } + if check("stroke_width") { + within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?; + } + if check("stroke_miter_limit") { + within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?; + } + if check("stroke_dash") + && let Some(dash) = &self.stroke_dash + { + for value in &dash.pattern { + within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?; + } + within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?; + } + if check("small_caps") + && let Some(value) = self.small_caps + { + within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?; + } + if check("fontAxes") + && let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite()) + { + return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number"))); + } + Ok(()) + } +} + +impl ParaStyle { + /// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its + /// field, against the range the paragraph style commands keep it to: the indents and the space + /// before and after, each Hyphenation option, each Justification option in `justification` + /// (the options as given, since reading a paragraph style brings them into range) with + /// Minimum, Desired and Maximum in order, and the number of tab stops with the position and + /// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the + /// error. + pub fn check_ranges( + &self, + justification: Option<&JustificationOptions>, + kept_tabs: &[TabStop], + check: impl Fn(&str, Option<&str>) -> bool, + ) -> Result<(), AttrRangeError> { + for (key, value) in [ + ("left_indent", self.left_indent), + ("right_indent", self.right_indent), + ("first_line_indent", self.first_line_indent), + ("space_before", self.space_before), + ("space_after", self.space_after), + ] { + if check(key, None) { + within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?; + } + } + let h = &self.hyphenation; + for (field, value, lo, hi) in [ + ("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0), + ("after_first", f64::from(h.after_first), 1.0, 15.0), + ("before_last", f64::from(h.before_last), 1.0, 15.0), + ("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0), + ("zone", h.zone, 0.0, MAX_PARA_DISTANCE), + ] { + if check("hyphenation", Some(field)) { + within(&format!("hyphenation.{field}"), value, lo, hi)?; + } + } + if let Some(j) = justification { + for (field, values, (lo, hi)) in [ + ("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING), + ("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING), + ("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING), + ] { + if !check("justification", Some(field)) { + continue; + } + let name = format!("justification.{field}"); + for value in values { + within(&name, value, lo, hi)?; + } + if !(values[0] <= values[1] && values[1] <= values[2]) { + return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); + } + } + if check("justification", Some("auto_leading")) { + let (lo, hi) = JustificationOptions::AUTO_LEADING; + within("justification.auto_leading", j.auto_leading, lo, hi)?; + } + } + if check("tabs", None) { + let max = TabStop::MAX_STOPS; + if self.tabs.len() > max.max(kept_tabs.len()) { + return Err(out("tabs", format!("at most {max} tab stops"))); + } + for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) { + within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?; + let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER); + if stop.leader.chars().count() > max { + return Err(out("tabs.leader", format!("{label} must be at most {max} characters"))); + } + } + } + Ok(()) + } +} diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 1a3229138e..64ab5256fe 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -801,3 +801,42 @@ fn auto_alignment_saves_readable_by_older_builds() { // Files from before the flag keep their alignment. assert_eq!(serde_json::from_str::(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center); } + +/// The default character and paragraph styles are in range, and each number outside its range, +/// one that is not a number included, is the error naming its attribute; an attribute the check +/// is not asked about is not checked. +#[test] +fn style_ranges_name_the_attribute_out_of_range() { + let all = |_: &str| true; + assert_eq!(CharStyle::default().check_ranges(all), Ok(())); + let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key); + let d = CharStyle::default(); + assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into())); + assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into())); + assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into())); + assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into())); + assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into())); + assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into())); + assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into())); + assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into())); + let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect(); + assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into())); + let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false }); + assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into())); + assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(())); + + let all = |_: &str, _: Option<&str>| true; + let p = ParaStyle::default(); + assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(())); + let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key); + assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into())); + let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }; + assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into())); + let far = TabStop { position: -1.0, ..stop.clone() }; + assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into())); + assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop"); + let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() }; + assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into())); + let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() }; + assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into())); +} diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 13f7051223..77cdfdcb7d 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -420,7 +420,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector // ---------- text ---------- /// Largest indent or paragraph spacing (points; Illustrator's limit). -const MAX_PARA: f64 = 1296.0; +const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE; /// `text.setFormat`'s `bullet` values and the bullets they pick. const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [ diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 6b34d42eea..7818ece63b 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1317,7 +1317,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs and 256 KiB of text; a style of its own needs a font family and a size of 0.1 to 1296 pt) and text.paragraphs (one style per paragraph), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. An output that changes nothing records no undo step. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. An output that changes nothing records no undo step. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", has_doc, run ), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..0bc0a34367 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -157,13 +157,13 @@ pub fn specs() -> Vec { "charStyle", "Character Styles", "Character", - "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt" + "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings" ); v.push(spec( "charStyle.edit", "Edit Character Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings", |s, p| edit_style(s, p, Kind::Char), true, )); @@ -636,52 +636,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } let mut st = with_attrs(&CharStyle::default(), m, &c)?; let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); - for (key, value, lo, hi) in - [("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)] - { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) { - return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto")); - } - let shift_max = 1296.0; - for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] { - if changed(key) && !(-shift_max..=shift_max).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max))); - } - } - let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI); - for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME); - if changed(key) && !(lo..=hi).contains(&st.tsume) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; - let lo = -hi; - for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - let lines = vectorcraft_doc::text::WARICHU_LINES; - if changed("warichuLines") && !lines.contains(&st.warichu_lines) { - return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); - } - let scale = vectorcraft_doc::text::WARICHU_SCALE; - for (key, value, lo, hi) in [ - ("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP), - ("warichuScale", st.warichu_scale, *scale.start(), *scale.end()), - ] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } + st.check_ranges(changed).map_err(|e| bad(&c, e.message))?; // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") @@ -693,10 +648,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma style_paint(d, paint, key, &c)?; } } - let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD); - if changed(key) && !(lo..=hi).contains(&st.stroke_width) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } if changed("features") { style_features(&st.features, kept, &c)?; } @@ -753,85 +704,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } } -/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt), -/// as `text.setFormat` keeps them. -const PARA_DISTANCE: f64 = 1296.0; - /// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the -/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each -/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as -/// `attrs` gives them), and the number of tab stops with the position and leader of each stop -/// `kept` does not hold. A value `kept` has is not checked. +/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options +/// as `attrs` gives them. A value `kept` has is not checked. fn para_ranges(st: &ParaStyle, attrs: &Map, kept: Option<&Map>, c: &str) -> Result<()> { - let within = |key: &str, value: f64, lo: f64, hi: f64| { - if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) } - }; let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key); - let nested_changed = |key: &str, field: &str| { - changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)) + let check = |key: &str, field: Option<&str>| match field { + None => changed(key), + Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)), }; - for (key, value) in [ - ("left_indent", st.left_indent), - ("right_indent", st.right_indent), - ("first_line_indent", st.first_line_indent), - ("space_before", st.space_before), - ("space_after", st.space_after), - ] { - if changed(key) { - within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?; - } - } - let h = &st.hyphenation; - for (field, value, lo, hi) in [ - ("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0), - ("after_first", f64::from(h.after_first), 1.0, 15.0), - ("before_last", f64::from(h.before_last), 1.0, 15.0), - ("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0), - ("zone", h.zone, 0.0, PARA_DISTANCE), - ] { - if nested_changed("hyphenation", field) { - within(&format!("hyphenation.{field}"), value, lo, hi)?; - } - } // Read as given: a paragraph's attributes keep justification options in range as they load. - if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) { - let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?; - for (field, values, (lo, hi)) in [ - ("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING), - ("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING), - ("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING), - ] { - if !nested_changed("justification", field) { - continue; - } - let name = format!("justification.{field}"); - for value in values { - within(&name, value, lo, hi)?; - } - if !(values[0] <= values[1] && values[1] <= values[2]) { - return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); - } - } - if nested_changed("justification", "auto_leading") { - let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING; - within("justification.auto_leading", j.auto_leading, lo, hi)?; - } - } - if changed("tabs") { - let kept_tabs = kept_tab_stops(kept); - let max = TabStop::MAX_STOPS; - if st.tabs.len() > max.max(kept_tabs.len()) { - return Err(bad(c, format!("at most {max} tab stops"))); - } - for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) { - within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?; - let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER); - if stop.leader.chars().count() > max { - return Err(bad(c, format!("{label} must be at most {max} characters"))); - } - } - } - Ok(()) + let given = attrs.get("justification").filter(|_| changed("justification")); + let justification: Option = + given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?; + st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message)) } /// The tab stops `kept` holds, each as it reads (a stop that does not read is left out). @@ -1204,7 +1090,8 @@ fn unused(s: &mut Session, kind: Kind) -> Result { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose +/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps, +/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose /// indents, spacing, Hyphenation or Justification options or tab stops are out of the range /// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in /// `src` of those skipped) diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index e8f57aa14f..3b0c872b09 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -401,6 +401,11 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { json!({"tsume": 100.1}), json!({"diacriticHorizontal": -1000.1}), json!({"diacriticVertical": 1000.1}), + json!({"tracking": -1000.1}), + json!({"kerning": 10000.1}), + json!({"rotation": 360.1}), + json!({"stroke_miter_limit": 0.9}), + json!({"small_caps": 200.1}), ] { let key = attrs.as_object().unwrap().keys().next().unwrap(); for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { @@ -425,7 +430,9 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0, "akiLeft": 0.0, "akiRight": 1000.0, "tsume": 100.0, - "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0 + "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0, + "tracking": 10000.0, "kerning": -1000.0, "rotation": -360.0, + "stroke_miter_limit": 500.0, "small_caps": 200.0 }}), ) .unwrap(); diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index bd35136dde..97b755ede0 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1275,7 +1275,7 @@ fn bad_writes_are_refused_naming_the_object_and_the_field() { text, json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}), &InputKind::ALL, - "text.runs[0].style.size: must be 0.1 to 1296 pt".into(), + "text.runs[0].style.size: `size` must be from 0.1 to 1296".into(), ), (text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()), ( @@ -1444,6 +1444,86 @@ fn written_runs_without_paragraphs_keep_each_paragraph_s_style() { assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]); } +/// Every number in the character and paragraph styles a filter writes is checked against the range +/// the style commands keep it to, in a style of the filter's own and in one the type already has, +/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the +/// object and the field, and the document stays as it was. A set of the document's, given by +/// name, takes the document's characters. +#[test] +fn written_style_numbers_are_checked_even_in_a_style_the_type_has() { + use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject}; + let (mut d, _, layer, _) = mixed(); + d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() }); + let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }; + let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() }; + let bad_chars: [(&str, CharStyle, &str); 5] = [ + ("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"), + ("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"), + ("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"), + ("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"), + ("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"), + ]; + let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() }; + let bad_paras: [(&str, ParaStyle, &str); 4] = [ + ("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"), + ("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"), + ( + "hyphenation", + ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() }, + "paragraphs[0].hyphenation.after_first", + ), + ("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"), + ]; + // `own`: the type already has the bad style, and the filter changes only its other run or + // paragraph; otherwise the bad style is the filter's own. + let run = |id: NodeId, own: bool, bad: &CharStyle| { + let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default()); + if own { + t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())]; + } + let mut doc = d.clone(); + let n = Node::new(id, NodeKind::Text(Box::new(t))); + let id = doc.insert(Some(layer), usize::MAX, n).unwrap(); + (doc, id) + }; + let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| { + let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap(); + let mut entry = entry; + entry["id"] = json!(id.0); + let mut changed = doc.clone(); + let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string(); + assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}"); + assert_eq!(&changed, doc, "{what}: nothing changed"); + }; + let fresh = d.clone().alloc_id(); + for (what, bad, says) in &bad_chars { + let (doc, id) = run(fresh, false, bad); + let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]); + check(&doc, id, json!({"text": {"runs": runs}}), says, what); + let (doc, id) = run(fresh, true, bad); + let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]); + check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has")); + } + let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() }; + for (what, bad, says) in &bad_paras { + let (doc, id) = run(fresh, false, &CharStyle::default()); + check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what); + let mut doc = doc; + if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) { + t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]); + } + check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has")); + } + // A set the document has, by name, takes the document's characters. + let (mut doc, id) = run(fresh, false, &CharStyle::default()); + let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap(); + let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() }); + let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]}); + write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、'])); +} + /// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON /// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output. #[test] diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs index 3ecd48bbb1..30bd36c426 100644 --- a/crates/plugins/src/objects/writes.rs +++ b/crates/plugins/src/objects/writes.rs @@ -5,18 +5,16 @@ use serde::de::DeserializeOwned; use serde_json::{Map, Value}; -use vectorcraft_doc::text::INLINE_CHAR; -use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, ParaStyle, TextObject, TextRun}; +use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR}; +use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun}; use vectorcraft_geom::Affine; use super::{ MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err, read_only_changed, }; -use crate::{InputKind, Result}; +use crate::{Error, InputKind, Result}; -/// The smallest and largest font size a filter may set, in points (as the Character panel's). -const FONT_SIZE: std::ops::RangeInclusive = 0.1..=1296.0; /// The longest font family name a filter may set, in characters. const MAX_FAMILY: usize = 256; /// The smallest determinant a transform a filter sets may have: a smaller one flattens the object. @@ -224,9 +222,10 @@ pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map, /// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an /// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they /// were, in the same order, and the characters of threaded type or type with ruby stay as they -/// were. A run whose style isn't one of the type's own has a font family and a size in -/// [`FONT_SIZE`], and its paints are checked as an object's are. Paragraph styles are one per -/// paragraph. With runs alone, each paragraph keeps its style when the number of paragraphs stays +/// were. Every number of every run's style is in the range the character style commands keep it +/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font +/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph +/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays /// the same, and otherwise the styles move with the text as typing the change moves them. fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> { if let Some(runs) = runs { @@ -252,6 +251,8 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va if text.contains(INLINE_CHAR) { return Err(out_err(&at, "`text` holds the character of an inline graphic")); } + // Every number goes to the layout, so it is checked even in a style the type has. + style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?; if !own.contains(style_v) { check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?; } @@ -298,8 +299,7 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va if list.len() != count { return Err(out_err(&at, format!("expected {count} paragraph styles, one per paragraph"))); } - let styles = - list.iter().enumerate().map(|(i, p)| strict::(p, &format!("{at}[{i}]"), "a paragraph style")).collect::>()?; + let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &format!("{at}[{i}]"))).collect::>()?; t.set_paragraph_styles(styles); } None => t.normalize_paras(), @@ -320,17 +320,40 @@ fn changed_range(old: &str, new: &str) -> (usize, usize, usize) { (start, old.len() - same, new.len() - same) } +/// An attribute of the style at `at` out of its range, naming the attribute. +fn range_err(at: &str, e: &AttrRangeError) -> Error { + out_err(&format!("{at}.{}", e.key), &e.message) +} + +/// Paragraph style `v` from a filter's output, at `at`: each attribute one a paragraph reads, each +/// number in the range the paragraph style commands keep it to ([`ParaStyle::check_ranges`], the +/// Justification options as given), and a custom Kinsoku set one of `doc`'s, by name, whose +/// characters it takes. +fn para_style(doc: &Document, v: &Value, at: &str) -> Result { + let mut st: ParaStyle = strict(v, at, "a paragraph style")?; + let justification = match v.get("justification") { + None | Some(Value::Null) => None, + Some(j) => Some(serde_json::from_value::(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?), + }; + st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(at, &e))?; + if let Some(set) = &st.kinsoku_set { + let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| { + let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD); + out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'")) + })?; + st.kinsoku_set = Some(std::sync::Arc::new(found.clone())); + } + Ok(st) +} + /// Checks character style `s`, a filter's own (`was`: the style of the run in its place before): -/// its font family is 1 to [`MAX_FAMILY`] printable characters, its size is in [`FONT_SIZE`], and -/// its fill and stroke are admitted as an object's paints are. +/// its font family is 1 to [`MAX_FAMILY`] printable characters, and its fill and stroke are +/// admitted as an object's paints are. Its numbers are checked for every run ([`set_text`]). fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> { let family = s.font_family.trim(); if family.is_empty() || family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) { return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters"))); } - if !FONT_SIZE.contains(&s.size) { - return Err(out_err(&format!("{at}.size"), format!("must be {} to {} pt", FONT_SIZE.start(), FONT_SIZE.end()))); - } let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| { let at = format!("{at}.{key}"); let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?; diff --git a/docs/mcp.md b/docs/mcp.md index 176625a7af..242d876fde 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13126,8 +13126,10 @@ its features turned off, distinct from unset. not a global swatch of the document, a stroke weight outside 0 to 4000000, more than 256 feature tags and an OpenType feature tag the shaper does not know, unless the style or the text it is made from already has that value. They also reject a size outside 0.1 to 1296, explicit leading outside 0.1 to 5000, horizontal or vertical scale -outside 1 to 10000, and baseline shift or Tate-chu-yoko offsets outside -1296 to 1296. `leading: null` keeps -Auto leading. An invalid value leaves the style, its text, and Undo history unchanged. +outside 1 to 10000, baseline shift or Tate-chu-yoko offsets outside -1296 to 1296, tracking or kerning +outside -1000 to 10000, rotation outside -360 to 360, a stroke miter limit outside 1 to 500, a +stroke dash length outside 0 to 4000000 or offset outside -4000000 to 4000000, Small Caps outside 1 to 200 and a +variable font axis setting that is not a number. `leading: null` keeps Auto leading. An invalid value leaves the style, its text, and Undo history unchanged. The New Character Style dialog accepts the same character fields and starts with the selected text's captured attributes. Without selected text, it starts with the character defaults for the interface language (including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. diff --git a/docs/plugins.md b/docs/plugins.md index a80de821d8..0b870d9e62 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -759,14 +759,21 @@ exactly as given, or with the fields it changes; a field it leaves out keeps its by the change from its given transform, so an image's distorted corners move with it. - `text.runs` replaces the type's runs: each is `{text, style, inline?}` with the character attributes as the native file stores them, and an attribute the host doesn't know is refused. There is at least one run, at most 4,096, and at - most 256 KiB of UTF-8 text; the runs written in one output take at most 16 MiB. A style that none of the type's runs - has needs a font family of 1 to 256 printable characters, a size from 0.1 to 1296 pt, and fills and strokes that a - path's appearance would take. Inline graphics stay where they were: the runs keep each `inline` run as it was given, - in the same order. The characters of threaded type, and of type with ruby, can't change, though their attributes can. - The runs and paragraphs of type given with `truncated: true` can't change. -- `text.paragraphs` holds one paragraph style per paragraph of the new text. With `text.runs` alone, each paragraph - keeps its style when the number of paragraphs stays the same; runs that add or join paragraphs move the styles with - the text, as typing the same change does. + most 256 KiB of UTF-8 text; the runs written in one output take at most 16 MiB. Every number in every run's style is + checked against the range `charStyle.new` keeps it to, including a style one of the type's runs already has: size + 0.1 to 1296 pt, leading 0.1 to 5000 pt, tracking and kerning -1000 to 10000, horizontal and vertical scale 1 to + 10000 %, baseline shift -1296 to 1296 pt, rotation -360 to 360°, and the ranges `docs/mcp.md` gives for + `charStyle.new` for the East Asian, Warichu and stroke attributes. A style that none of the type's runs has also needs a font family of 1 to 256 + printable characters, and fills and strokes that a path's appearance would take. Inline graphics stay where they + were: the runs keep each `inline` run as it was given, in the same order. The characters of threaded type, and of + type with ruby, can't change, though their attributes can. The runs and paragraphs of type given with + `truncated: true` can't change. +- `text.paragraphs` holds one paragraph style per paragraph of the new text, each checked as `paraStyle.new` checks + its attributes: indents and space before and after within ±1296 pt, the Hyphenation and Justification options in + their ranges, at most 256 tab stops at 0 to 100,000 pt, and a custom Kinsoku set only by the name of one of the + document's sets, whose characters the paragraph takes. With `text.runs` alone, each paragraph keeps its style when + the number of paragraphs stays the same; runs that add or join paragraphs move the styles with the text, as typing + the same change does. - `opacity` is a number from 0 to 1. - `symbolId` names a symbol in the document. An instance that shows another symbol loses its overrides, as Replace Symbol does. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7840e02eba..841dc07f6f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -828,7 +828,7 @@ since 2026-10-01. - **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated). - **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). -- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. +- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt, tracking and kerning from -1000 to 10,000, rotation from -360° to 360°, a stroke miter limit from 1 to 500, Small Caps from 1% to 200%, finite stroke dashes and variable font axis settings. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (1% to 10,000%), Baseline Shift (-1296 pt to 1296 pt), the Tate-chu-yoko Settings Up/Down and Left/Right (-1296 pt to 1296 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0 pt, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these seven. Language sets the language the characters are shaped in, not hyphenation or spelling. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html). - **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). @@ -2662,7 +2662,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Bulk memory fuzz cases use the host's fuel constants:** `crates/engine/tests/plugin_fuzz.rs` samples runs around one slice of the instruction budget and lengths around the bytes one unit of fuel pays for with `vectorcraft_plugins`' own `FUEL_SLICE` and `BYTES_COPIED_PER_FUEL`, so the sampled cases move when either value changes. Regressions: `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in permissions (G17):** a manifest may list `permissions` (`doc.read`, `doc.write`, `state`, `effect.render`, `export.write`; the first three follow storytold/photocraft#662) and an `api` level; without the list a plug-in gets what its kind implies and installs as before. Install Plug-in… and File › Open show the name, id, version, file SHA-256 and each permission in plain words, with control and bidirectional characters escaped, and install nothing on Cancel; for a plug-in that lists permissions, `plugin.install` needs `grant` and folders install it only when it is granted. The grant is kept with the module's hash, a module asking for more asks again, and a filter run refuses output its permissions don't allow. Regressions: `crates/plugins/src/permissions.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. -- **Filter plug-ins change type, images and symbol instances (G17):** a filter at plug-in API level 3 lists in `writes` the kinds among its `inputs` it may change, with `doc.write` in its `permissions`, and may return those objects with changed fields: type's runs (characters and character attributes, inline graphics kept as they were) and paragraph styles, an image's transform and opacity, an instance's transform and the symbol it shows (one already in the document; its overrides are cleared as Replace Symbol clears them), and each one's name. Runs are held to the input's limits (4,096 runs and 256 KiB of text a type object, 16 MiB over the output), a style of the filter's own needs a font family and a size of 0.1 to 1296 pt and its paints are checked as a path's are, and the characters of threaded type and type with ruby stay as they were. Any other changed field, or a value out of range, refuses the run naming the object and the field, with the document unchanged. The changes are one undo step, and an output that changes nothing, for every filter, records none. Images now also come with their `opacity`. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Filter plug-ins change type, images and symbol instances (G17):** a filter at plug-in API level 3 lists in `writes` the kinds among its `inputs` it may change, with `doc.write` in its `permissions`, and may return those objects with changed fields: type's runs (characters and character attributes, inline graphics kept as they were) and paragraph styles, an image's transform and opacity, an instance's transform and the symbol it shows (one already in the document; its overrides are cleared as Replace Symbol clears them), and each one's name. Runs are held to the input's limits (4,096 runs and 256 KiB of text a type object, 16 MiB over the output), every number in every run's and paragraph's style is checked against the range `charStyle.new` and `paraStyle.new` keep it to (one shared check, also for a style the type already has), a custom Kinsoku set must be one of the document's, a style of the filter's own needs a font family and its paints are checked as a path's are, and the characters of threaded type and type with ruby stay as they were. Any other changed field, or a value out of range, refuses the run naming the object and the field, with the document unchanged. The changes are one undo step, and an output that changes nothing, for every filter, records none. Images now also come with their `opacity`. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. From 9fe9ad658a62c430e2f4caa0c4b8ab07761ecba1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:51:52 -0800 Subject: [PATCH 026/107] Plug-ins: paragraph styles follow the paragraphs' text when a filter adds or joins paragraphs Runs written without text.paragraphs that change the paragraph count at two separate places gave every paragraph between the first and last change the first one's style. The host now matches the old and new paragraphs by their text: an unchanged paragraph keeps its style, changed paragraphs take the styles of those they replace in order, and an added paragraph takes the style of the one before it (the next one at the start) without a list number. Past 262,144 compared pairs the paragraphs are paired in order. --- crates/plugins/src/objects/tests.rs | 58 +++++++++++++- crates/plugins/src/objects/writes.rs | 113 ++++++++++++++++++++++++--- docs/plugins.md | 7 +- 3 files changed, 161 insertions(+), 17 deletions(-) diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 97b755ede0..5322425ea8 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1415,9 +1415,10 @@ fn inline_graphics_in_written_type_stay_as_they_were() { } /// Runs written without `paragraphs` keep each paragraph's style when the number of paragraphs -/// stays the same, and otherwise move the styles with the text as typing the same change would: a -/// paragraph added before others takes the style of the one it splits and the others keep theirs, -/// and joining two paragraphs keeps the first one's style. +/// stays the same, and otherwise the styles follow the paragraphs' text: a paragraph whose text +/// stays keeps its style, also when changes are made at two places, a paragraph added at the start +/// takes the style of the next one and one added later the style of the one before it, and joining +/// two paragraphs keeps the first one's style. #[test] fn written_runs_without_paragraphs_keep_each_paragraph_s_style() { use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject}; @@ -1442,6 +1443,57 @@ fn written_runs_without_paragraphs_keep_each_paragraph_s_style() { assert_eq!(justified("One\nTwo\nThree"), [Justify::Left, Justify::Center, Justify::Right]); assert_eq!(justified("AB\nC"), [Justify::Left, Justify::Right]); assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]); + // Two separate changes: B and C keep their styles. + assert_eq!(justified("X\nA\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]); + assert_eq!(justified("A\nX\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]); + // A changed paragraph takes the style of the one it replaces; the one added after it, that style. + assert_eq!(justified("A\nB2\nB3\nC"), [Justify::Left, Justify::Center, Justify::Center, Justify::Right]); + assert_eq!(justified("A2\nC"), [Justify::Left, Justify::Right]); +} + +/// A paragraph that a change adds next to a numbered one takes its style without the number, and +/// the numbered paragraph keeps it. +#[test] +fn written_runs_give_an_added_paragraph_no_list_number() { + use vectorcraft_doc::text::ParaList; + use vectorcraft_doc::{CharStyle, ParaStyle, TextObject}; + let (mut d, _, layer, _) = mixed(); + let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default()); + let numbered = ParaStyle { list: Some(ParaList { start: Some(5), ..ParaList::default() }), ..ParaStyle::default() }; + t.set_paragraph_styles(vec![ParaStyle::default(), numbered]); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": "X\nA\nB\nY", "style": CharStyle::default()}]}}]}); + write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") }; + let starts: Vec<_> = (0..t.paragraph_count()).map(|i| t.para_at(i).list.map(|l| l.start)).collect(); + assert_eq!(starts, [None, None, Some(Some(5)), Some(None)]); +} + +/// Past 262,144 pairs of old and new paragraphs to compare, the paragraphs are paired in order. +#[test] +fn written_runs_pair_paragraphs_in_order_past_the_compare_limit() { + use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject}; + let (mut d, _, layer, _) = mixed(); + let paras: Vec = (0..600).map(|i| format!("p{i}")).collect(); + let mut t = TextObject::point(Point::new(0.0, 0.0), ¶s.join("\n"), CharStyle::default()); + let styled = |i: usize| ParaStyle { justify: if i.is_multiple_of(2) { Justify::Left } else { Justify::Right }, ..ParaStyle::default() }; + t.set_paragraph_styles((0..600).map(styled).collect()); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + // 600 old paragraphs times 602 new ones: none starts or ends both texts. + let text = format!("X\n{}\nY", paras.join("\n")); + let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]}); + write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.paragraph_count(), 602); + let got: Vec<_> = (0..602).map(|i| t.para_at(i).justify).collect(); + let want: Vec<_> = (0..602).map(|i| styled(i.min(599)).justify).collect(); + assert_eq!(got, want); } /// Every number in the character and paragraph styles a filter writes is checked against the range diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs index 30bd36c426..54b44b74c8 100644 --- a/crates/plugins/src/objects/writes.rs +++ b/crates/plugins/src/objects/writes.rs @@ -19,6 +19,9 @@ use crate::{Error, InputKind, Result}; const MAX_FAMILY: usize = 256; /// The smallest determinant a transform a filter sets may have: a smaller one flattens the object. const MIN_DETERMINANT: f64 = 1e-12; +/// The most pairs of an old and a new paragraph, past those both texts start and end with, that a +/// change of the paragraph count compares by their text ([`moved_para_styles`]). +const MAX_MATCHED_PAIRS: usize = 1 << 18; /// The fields of an object of `kind` a filter that lists the kind in `writes` may change. fn writable(kind: InputKind) -> &'static [&'static str] { @@ -226,7 +229,7 @@ pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map, /// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font /// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph /// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays -/// the same, and otherwise the styles move with the text as typing the change moves them. +/// the same, and otherwise the styles follow the paragraphs' text ([`moved_para_styles`]). fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> { if let Some(runs) = runs { let at = format!("{at}.text.runs"); @@ -274,6 +277,7 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va } let plain: String = new.iter().map(|r| r.text.as_str()).collect(); let old = t.plain_text(); + let mut moved = None; if plain != old { if threaded { return Err(out_err(&at, "the characters of threaded type can't be changed")); @@ -283,13 +287,15 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va } let breaks = |s: &str| s.bytes().filter(|&b| b == b'\n').count(); if paragraphs.is_none() && breaks(&plain) != breaks(&old) { - // Paragraphs added or joined: the styles follow the text as typing the change would - // move them. With as many paragraphs as before, each keeps its style. - let (start, old_end, new_end) = changed_range(&old, &plain); - t.splice_paras(start, old_end, plain.get(start..new_end).unwrap_or_default()); + // Paragraphs added or joined: the styles follow the paragraphs' text. With as many + // paragraphs as before, each keeps its style. + moved = Some(moved_para_styles(&t.paragraph_styles(), &old, &plain)); } } t.runs = new; + if let Some(styles) = moved { + t.set_paragraph_styles(styles); + } } match paragraphs { Some(v) => { @@ -311,13 +317,96 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va Ok(()) } -/// The bytes that differ between `old` and `new` once their common start and end are taken away, -/// on character boundaries: `old[start..old_end]` became `new[start..new_end]`. -fn changed_range(old: &str, new: &str) -> (usize, usize, usize) { - let start = old.char_indices().zip(new.chars()).find(|((_, a), b)| a != b).map_or(old.len().min(new.len()), |((i, _), _)| i); - let (old_rest, new_rest) = (old.get(start..).unwrap_or_default(), new.get(start..).unwrap_or_default()); - let same: usize = old_rest.chars().rev().zip(new_rest.chars().rev()).take_while(|(a, b)| a == b).map(|(c, _)| c.len_utf8()).sum(); - (start, old.len() - same, new.len() - same) +/// The paragraph styles of text `new` that replaced `old`, whose paragraphs had `styles` (one per +/// paragraph). The paragraphs, split at `\n`, are matched as a longest common subsequence of their +/// texts after the paragraphs both start and end with are set aside; when the paragraphs left in +/// the old text times those left in the new pass [`MAX_MATCHED_PAIRS`], they are paired in order +/// instead. A +/// matched paragraph keeps its style. Between two matched paragraphs, the changed ones take the +/// styles of the old paragraphs there in order, and the last of those past their count; paragraphs +/// added where there were none take the style of the paragraph before them, or of the next one at +/// the start. A style copied to a paragraph that was not there loses its list number +/// ([`vectorcraft_doc::text::ParaList::start`]). +fn moved_para_styles(styles: &[ParaStyle], old: &str, new: &str) -> Vec { + let a: Vec<&str> = old.split('\n').collect(); + let b: Vec<&str> = new.split('\n').collect(); + let pre = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); + let (a_rest, b_rest) = (a.get(pre..).unwrap_or_default(), b.get(pre..).unwrap_or_default()); + let suf = a_rest.iter().rev().zip(b_rest.iter().rev()).take_while(|(x, y)| x == y).count(); + // `matched[j]`: the old paragraph that new paragraph `j` is, if any. + let mut matched: Vec> = vec![None; b.len()]; + for (j, m) in matched.iter_mut().enumerate().take(pre) { + *m = Some(j); + } + for k in 0..suf { + if let Some(m) = matched.get_mut(b.len() - 1 - k) { + *m = Some(a.len() - 1 - k); + } + } + let (am, bm) = (a_rest.get(..a_rest.len() - suf).unwrap_or_default(), b_rest.get(..b_rest.len() - suf).unwrap_or_default()); + if !am.is_empty() && !bm.is_empty() && am.len().saturating_mul(bm.len()) <= MAX_MATCHED_PAIRS { + let mut ids = std::collections::HashMap::new(); + let mut id = |s: &str| { + let next = ids.len(); + *ids.entry(s.to_string()).or_insert(next) + }; + let ai: Vec = am.iter().map(|s| id(s)).collect(); + let bi: Vec = bm.iter().map(|s| id(s)).collect(); + // `len[i * w + j]`: the length of the longest common subsequence of `ai[i..]` and `bi[j..]`. + let w = bi.len() + 1; + let mut len = vec![0u32; (ai.len() + 1) * w]; + for i in (0..ai.len()).rev() { + for j in (0..bi.len()).rev() { + let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0); + let v = if ai.get(i) == bi.get(j) { at(i + 1, j + 1) + 1 } else { at(i + 1, j).max(at(i, j + 1)) }; + if let Some(c) = len.get_mut(i * w + j) { + *c = v; + } + } + } + let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0); + let (mut i, mut j) = (0, 0); + while i < ai.len() && j < bi.len() { + if ai.get(i) == bi.get(j) { + if let Some(m) = matched.get_mut(pre + j) { + *m = Some(pre + i); + } + (i, j) = (i + 1, j + 1); + } else if at(i + 1, j) >= at(i, j + 1) { + i += 1; + } else { + j += 1; + } + } + } + let style = |i: usize, numbered: bool| { + let mut s = styles.get(i).or(styles.last()).cloned().unwrap_or_default(); + if !numbered && let Some(l) = s.list.as_mut() { + l.start = None; + } + s + }; + let mut out = Vec::with_capacity(b.len()); + let (mut next_old, mut j) = (0, 0); + while j < b.len() { + if let Some(&Some(i)) = matched.get(j) { + out.push(style(i, true)); + (next_old, j) = (i + 1, j + 1); + continue; + } + // New paragraphs `j..end` stand where old paragraphs `next_old..old_end` were. + let end = (j..b.len()).find(|&k| matched.get(k).is_some_and(Option::is_some)).unwrap_or(b.len()); + let old_end = matched.get(end).copied().flatten().unwrap_or(a.len()); + for g in 0..end - j { + out.push(if next_old < old_end { + style((next_old + g).min(old_end - 1), next_old + g < old_end) + } else { + style(next_old.checked_sub(1).unwrap_or(old_end), false) + }); + } + j = end; + } + out } /// An attribute of the style at `at` out of its range, naming the attribute. diff --git a/docs/plugins.md b/docs/plugins.md index 0b870d9e62..f857f1498f 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -772,8 +772,11 @@ exactly as given, or with the fields it changes; a field it leaves out keeps its its attributes: indents and space before and after within ±1296 pt, the Hyphenation and Justification options in their ranges, at most 256 tab stops at 0 to 100,000 pt, and a custom Kinsoku set only by the name of one of the document's sets, whose characters the paragraph takes. With `text.runs` alone, each paragraph keeps its style when - the number of paragraphs stays the same; runs that add or join paragraphs move the styles with the text, as typing - the same change does. + the number of paragraphs stays the same. When runs add or join paragraphs, the host matches the old and new + paragraphs by their text: a paragraph whose text is unchanged keeps its style, changed paragraphs take the styles of + the paragraphs they replace in order, and a paragraph added between others takes the style of the one before it (of + the next one at the start), without a list number. Apart from the paragraphs both texts start and end with, when + the old paragraphs times the new ones pass 262,144, the host pairs them in order instead. - `opacity` is a number from 0 to 1. - `symbolId` names a symbol in the document. An instance that shows another symbol loses its overrides, as Replace Symbol does. From 68df6224ea52c9622c38cf3dd4dfd1fc875ab7ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:00:55 -0800 Subject: [PATCH 027/107] Accessibility: Save PDF and Print name every number and length field Screen readers found six image resolution fields in Save PDF with no name, and the four bleed fields were not connected to their labels. In Print, the artboard Range field had no name, Width and Height were both named Width:, Placement X and Y both Placement:, and Scale W and H both Scale:. - save_pdf::number_named and length_named take a name for a field that shares its row or has none; number and length keep naming a field by its row. - The resolution fields are named by their group and the word before them (Color images to, Color images above), the bleed fields by their side, Width and Height by their own labels, and Placement and Scale by the row and the axis. - No visible text changes. Tests: dialogs::save_pdf::tests and dialogs::tests_print every_number_and_length_field_is_named_by_its_label. --- crates/ui-egui/src/dialogs/print.rs | 40 ++++++++++------- crates/ui-egui/src/dialogs/save_pdf.rs | 28 +++++++++--- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 38 ++++++++++++++++ crates/ui-egui/src/dialogs/tests_print.rs | 47 ++++++++++++++++++++ docs/target-app-parity.md | 1 + 5 files changed, 130 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index de04998800..532b9031e7 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -26,7 +26,9 @@ use vectorcraft_pdf::{ PrintSettings, }; -use super::save_pdf::{TOP_LABEL_WIDTH, choice, current_section, flag, get, heading, length, note, number, pick, row, row_with, set, text}; +use super::save_pdf::{ + TOP_LABEL_WIDTH, choice, current_section, flag, get, heading, length, length_named, note, number, pick, row, row_with, set, text, +}; use super::{DialogSpec, form}; use crate::state::Dialog; use crate::theme::{self, Tokens}; @@ -606,10 +608,11 @@ fn whole(ui: &mut egui::Ui, d: &mut Dialog, path: &str, range: std::ops::RangeIn }); } -/// A Scale percentage at `path`, 1–1000 %: the value typed, once one was. -fn percent(ui: &mut egui::Ui, d: &mut Dialog, path: &str, enabled: bool) -> Option { +/// A Scale percentage at `path`, 1–1000 %, that screen readers name `name`: the value typed, once +/// one was. +fn percent(ui: &mut egui::Ui, d: &mut Dialog, path: &str, name: &str, enabled: bool) -> Option { let v = get(d, path).as_f64().unwrap_or(100.0); - let typed = ui.add_enabled_ui(enabled, |ui| widgets::range_field(ui, path, v, 1.0..=1000.0, "%", 3, 64.0)).inner; + let typed = ui.add_enabled_ui(enabled, |ui| widgets::range_field_named(ui, path, Some(name), v, 1.0..=1000.0, "%", 3, 64.0)).inner; if let Some(x) = typed { set(d, path, json!(x)); } @@ -694,7 +697,7 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } let mut range = get(d, "range").as_str().unwrap_or_default().to_string(); let edit = egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(140.0).hint_text("1-3, 5"); - if ui.add_enabled(artboards == PrintArtboards::Range, edit).changed() { + if ui.add_enabled(artboards == PrintArtboards::Range, edit).accessible_name(tl!("Range:")).changed() { set(d, "range", json!(range)); } }); @@ -706,18 +709,19 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { row(ui, tl!("Size:"), |ui| { pick::(ui, d, "media", 160.0, |_| true); }); - // A paper size shows its size; Custom takes one. + // A paper size shows its size; Custom takes one. Each field is named by its own label. let media = choice::(d, "media").unwrap_or_default(); - row(ui, tl!("Width:"), |ui| match media.size() { + let (width, height) = (tl!("Width:"), tl!("Height:")); + row(ui, width, |ui| match media.size() { Some((w, h)) => { - ui.add_enabled_ui(false, |ui| widgets::num_field(ui, "print-media-w", Some(w), unit, 80.0)); - ui.label(tl!("Height:")); - ui.add_enabled_ui(false, |ui| widgets::num_field(ui, "print-media-h", Some(h), unit, 80.0)); + ui.add_enabled_ui(false, |ui| widgets::num_field_named(ui, "print-media-w", Some(width), Some(w), unit, 80.0)); + ui.label(height); + ui.add_enabled_ui(false, |ui| widgets::num_field_named(ui, "print-media-h", Some(height), Some(h), unit, 80.0)); } None => { - length(ui, d, "width", unit, true); - ui.label(tl!("Height:")); - length(ui, d, "height", unit, true); + length_named(ui, d, "width", Some(width), unit, true); + ui.label(height); + length_named(ui, d, "height", Some(height), unit, true); } }); heading(ui, tl!("Orientation")); @@ -741,10 +745,11 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { if let Some(o) = widgets::reference_point_named(ui, current, tl!("Placement:")).and_then(|i| Origin::ALL.get(i)) { set(d, "placement.origin", json!(o.id())); } + // Each offset is named by the row and its axis. ui.label("X:"); - length(ui, d, "placement.x", unit, true); + length_named(ui, d, "placement.x", Some(&format!("{} X:", tl!("Placement:"))), unit, true); ui.label("Y:"); - length(ui, d, "placement.y", unit, true); + length_named(ui, d, "placement.y", Some(&format!("{} Y:", tl!("Placement:"))), unit, true); }); }); if placed { @@ -761,13 +766,14 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { row(ui, tl!("Scale:"), |ui| { let on = scaling == PrintScaling::Custom || tiles; let linked = get(d, SCALE_LINKED).as_bool() == Some(true); + // Each percentage is named by the row and its own label. ui.label(tl!("W:")); - let w = percent(ui, d, "scale.width", on); + let w = percent(ui, d, "scale.width", &format!("{} {}", tl!("Scale:"), tl!("W:")), on); if let Some(w) = w.filter(|_| linked) { set(d, "scale.height", json!(w)); } ui.label(tl!("H:")); - let h = percent(ui, d, "scale.height", on); + let h = percent(ui, d, "scale.height", &format!("{} {}", tl!("Scale:"), tl!("H:")), on); if let Some(h) = h.filter(|_| linked) { set(d, "scale.width", json!(h)); } diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index a8db555bfb..e096ece979 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -399,9 +399,15 @@ pub(super) fn choice_label<'a>(lang: crate::i18n::Lang, path: &str, label: &'a s } pub(super) fn number(ui: &mut egui::Ui, d: &mut Dialog, path: &str, suffix: &str, enabled: bool) { + number_named(ui, d, path, None, suffix, enabled); +} + +/// [`number`] that screen readers name `name` (already translated) instead of by its row's label: +/// for a field that shares its row with another, or that has no row. +pub(super) fn number_named(ui: &mut egui::Ui, d: &mut Dialog, path: &str, name: Option<&str>, suffix: &str, enabled: bool) { let v = get(d, path).as_f64().unwrap_or(0.0); ui.add_enabled_ui(enabled, |ui| { - if let Some(x) = widgets::plain_field(ui, path, v, suffix, 3, 64.0) { + if let Some(x) = widgets::plain_field_named(ui, path, name, v, suffix, 3, 64.0) { set(d, path, json!(x)); } }); @@ -409,9 +415,14 @@ pub(super) fn number(ui: &mut egui::Ui, d: &mut Dialog, path: &str, suffix: &str /// A length in points, shown in the document's units. pub(super) fn length(ui: &mut egui::Ui, d: &mut Dialog, path: &str, unit: Unit, enabled: bool) { + length_named(ui, d, path, None, unit, enabled); +} + +/// [`length`] that screen readers name `name` (already translated), as [`number_named`] is. +pub(super) fn length_named(ui: &mut egui::Ui, d: &mut Dialog, path: &str, name: Option<&str>, unit: Unit, enabled: bool) { let v = get(d, path).as_f64(); ui.add_enabled_ui(enabled, |ui| { - if let Some(x) = widgets::num_field(ui, path, v, unit, 80.0) { + if let Some(x) = widgets::num_field_named(ui, path, name, v, unit, 80.0) { set(d, path, json!(x)); } }); @@ -637,6 +648,7 @@ fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) { let mut range = d.str("range"); if ui .add_enabled(!all, egui::TextEdit::singleline(&mut range).align(egui::Align2::LEFT_CENTER).desired_width(140.0).hint_text("1-3, 5")) + .accessible_name(tl!("Range:")) .changed() { d.fields.insert("range".into(), json!(range)); @@ -650,11 +662,12 @@ fn image_rows(ui: &mut egui::Ui, d: &mut Dialog, key: &str, title: &str) { let on = get(d, &format!("{base}.downsample")) != Downsample::None.id(); ui.horizontal(|ui| { pick::(ui, d, &format!("{base}.downsample"), 150.0, |_| true); + // Each resolution is named by its group and the word before it. ui.label(tl!("to")); let ppi = super::ppi_suffix(); - number(ui, d, &format!("{base}.ppi"), &ppi, on); + number_named(ui, d, &format!("{base}.ppi"), Some(&format!("{title} {}", tl!("to"))), &ppi, on); ui.label(tl!("above")); - number(ui, d, &format!("{base}.abovePpi"), &ppi, on); + number_named(ui, d, &format!("{base}.abovePpi"), Some(&format!("{title} {}", tl!("above"))), &ppi, on); }); ui.horizontal(|ui| { ui.label(tl!("Compression:")); @@ -728,16 +741,17 @@ pub(super) fn marks_and_bleeds(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut ] { for (i, p, label) in pair { ui.label(label); + // Each side's field is named by its label. match document { Some(b) => { - ui.add_enabled_ui(false, |ui| widgets::num_field(ui, p, b.get(i).copied(), unit, 80.0)); + ui.add_enabled_ui(false, |ui| widgets::num_field_named(ui, p, Some(label), b.get(i).copied(), unit, 80.0)); } None if pdf => { - if let Some(x) = widgets::num_field(ui, p, get(d, p).as_f64(), unit, 80.0) { + if let Some(x) = widgets::num_field_named(ui, p, Some(label), get(d, p).as_f64(), unit, 80.0) { edit_bleed(d, i, x); } } - None => length(ui, d, p, unit, true), + None => length_named(ui, d, p, Some(label), unit, true), } } ui.end_row(); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 501aed4ed0..929342832a 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1570,3 +1570,41 @@ fn save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones() { assert!(app.ui.dialog.is_none(), "{bad}"); } } + +/// Every number and length field is named by its visible label: the image resolutions by their +/// group and the word before the field, the bleed sides by theirs. +#[test] +fn every_number_and_length_field_is_named_by_its_label() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/names.pdf"})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + theme::install_fonts(&ctx); + let names = |app: &mut VectorcraftApp, section: &str| { + set_field(app, "__section", json!(section)); + let mut out = egui::FullOutput::default(); + for _ in 0..2 { + out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + } + let names = super::super::tests_print::field_names(&out); + assert!(names.iter().all(|n| !n.trim().is_empty()), "{section}: {names:?}"); + names + }; + let has = |names: &[String], expected: &[&str]| { + for name in expected { + assert_eq!(names.iter().filter(|n| n == name).count(), 1, "{name} in {names:?}"); + } + }; + has(&names(&mut app, "General"), &["Range:"]); + let compression = + ["Color images to", "Color images above", "Grayscale images to", "Grayscale images above", "Monochrome images to", "Monochrome images above"]; + has(&names(&mut app, "Compression"), &compression); + // Without the document's bleed the sides take values; with it they show it dimmed. + let bleed = ["Offset:", "Top:", "Bottom:", "Left:", "Right:"]; + set_field(&mut app, "bleed.useDocument", json!(false)); + has(&names(&mut app, "Marks and Bleeds"), &bleed); + set_field(&mut app, "bleed.useDocument", json!(true)); + has(&names(&mut app, "Marks and Bleeds"), &bleed); + has(&names(&mut app, "Advanced"), &["Subset fonts below:"]); +} diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 00b45e0db7..f60131e1a8 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -532,3 +532,50 @@ fn a_spot_inks_icon_converts_it_to_process_and_back() { screen.run(&mut app, vec![click(keep)]); assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": false}])); } + +/// The names screen readers give the text fields in `out`'s accessibility tree: a field's own +/// name, else the text of a label it is labeled by, else "". +pub(super) fn field_names(out: &egui::FullOutput) -> Vec { + use egui::accesskit::Role; + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A label node carries its text as its value. + let text_of = |id| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + nodes + .iter() + .filter(|(_, n)| matches!(n.role(), Role::TextInput | Role::SpinButton)) + .map(|(_, n)| n.label().map(str::to_string).or_else(|| n.labelled_by().iter().find_map(|l| text_of(*l))).unwrap_or_default()) + .collect() +} + +/// Every number and length field of every section is named by its visible label, and the fields +/// of a row with several are told apart by theirs. +#[test] +fn every_number_and_length_field_is_named_by_its_label() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + let mut screen = Screen::new(); + let mut names = |app: &mut VectorcraftApp, section: &str| { + set(app, "__section", json!(section)); + screen.run(app, vec![]); + let names = field_names(&screen.run(app, vec![])); + assert!(names.iter().all(|n| !n.trim().is_empty()), "{section}: {names:?}"); + names + }; + let has = |names: &[String], expected: &[&str]| { + for name in expected { + assert_eq!(names.iter().filter(|n| n == name).count(), 1, "{name} in {names:?}"); + } + }; + // A paper size shows its size in dimmed fields; Custom takes one. + let general = ["Copies:", "Range:", "Width:", "Height:", "Placement: X:", "Placement: Y:", "Scale: W:", "Scale: H:", "Overlap:", "Gutter:"]; + has(&names(&mut app, "General"), &general); + set(&mut app, "media", json!("custom")); + has(&names(&mut app, "General"), &general); + // The document's bleed shows in dimmed fields; without it the fields take the values. + let bleed = ["Offset:", "Top:", "Bottom:", "Left:", "Right:"]; + has(&names(&mut app, "Marks and Bleed"), &bleed); + super::save_pdf::set(dialog(&mut app), "bleed.useDocument", json!(false)); + has(&names(&mut app, "Marks and Bleed"), &bleed); + has(&names(&mut app, "Graphics"), &["Flatness:"]); + has(&names(&mut app, "Advanced"), &["Unprintable margin:"]); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..4ea84bb12e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -803,6 +803,7 @@ since 2026-10-01. - **EPS Save with Use Artboards:** Save As › EPS Options show Use Artboards with All or Range, for a separate file per artboard ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)), unchecked by default (the scripting reference's EPS save options list `saveMultipleArtboards` with a default of false, [scripting reference](https://web.archive.org/web/20160803105056/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf)). Unchecked, Save writes one file whose bounding box fits all the visible art, as Export does, without the artboards' background colors; when no art shows, the page is the first artboard in its color. An opened EPS saved back this way loses its page margins. Checked with two or more chosen artboards, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it. Checked with one chosen artboard, VectorCraft writes that artboard as the page of the file at the path alone (the behavior Save had since #4293). Evidence: `cmd::fileio::tests_artboard_fill::eps_save_draws_the_color_on_an_artboard_page`, `tests::save::eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard`, `tests::save::opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page`, `tests::save::eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard`, `dialogs::save_options::tests::eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard`. - **EPS Options custom flattener settings:** the help page describes flattening an EPS's transparency with a preset or with custom options, adjusted through Custom ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)). EPS Options now has Custom… beside the flattener Preset. It opens Custom Transparency Flattener Options on the settings the export would use: the raster/vector balance, both resolutions, the text and stroke outline switches, Clip Complex Regions and Anti-alias Rasters. OK goes back to EPS Options with the preset shown as [Custom], the export flattens with those settings, and the next EPS Options start from them; choosing a preset drops them, and Cancel goes back to EPS Options unchanged. Preserve Alpha Transparency stays off, and overprints are kept only with Overprints set to Preserve. The [Custom] label, the remembering, the Cancel behavior, Anti-alias Rasters and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::tests_eps::custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged`, `custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen`, `bad_custom_flattener_options_keep_the_dialog_open`. - **Save PDF custom flattener settings:** the help page describes the Advanced section's flattener preset for PDF 1.3 saves of transparent art, with a Custom button for adjusting the flattener settings, and says neither is available at PDF 1.4 and later ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). Save PDF › Advanced now has Custom… beside Flattener preset, enabled for PDF 1.3, PDF/X-1a and PDF/X-3. It opens Custom Transparency Flattener Options on the settings the save would use: the raster/vector balance, both resolutions, the text and stroke outline switches and Anti-alias Rasters; Clip Complex Regions shows on, as the PDF 1.3 writer always clips, overprints are kept only with Overprint set to Preserve, and Preserve Alpha Transparency shows off, as PDF 1.3 rasters keep no alpha. OK goes back to Save PDF with the preset shown as [Custom] and the save flattens with those settings; settings equal to the preset's leave its name, choosing a preset drops them, and Cancel goes back unchanged. PDF presets keep the flattener preset but not these settings, and Save Preset… says so while they are set. `ui.savePdfDialog` keeps a `flattener` it is given. The [Custom] label, the Cancel behavior, Anti-alias Rasters, the editor's absence from the PDF preset editor and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::save_pdf::tests::custom_is_enabled_where_the_save_flattens`, `custom_starts_from_the_preset_and_cancel_goes_back_unchanged`, `custom_options_are_written_until_a_preset_is_chosen`, `custom_options_equal_to_the_preset_leave_its_name`, `custom_shows_alpha_as_the_pdf_1_3_writer_drops_it`, `save_preset_says_it_leaves_the_custom_flattener_options_out`, `save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones`. +- **Save PDF and Print field names for screen readers:** every number, length and range field in Save PDF and Print has a name in the accessibility tree. Screen readers name the image resolution fields by their group and the word before them ("Color images to", "Color images above"), the bleed fields by their side ("Top:"), Print's Width and Height fields by their own labels, the Placement and Scale fields by the row and their axis ("Placement: X:", "Scale: W:"), and the artboard range fields "Range:". Scores and estimates are unchanged. Evidence: `dialogs::save_pdf::tests::every_number_and_length_field_is_named_by_its_label`, `dialogs::tests_print::every_number_and_length_field_is_named_by_its_label`. - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. From 494635f9326e19212a81ed92fb8a931cc84985a7 Mon Sep 17 00:00:00 2001 From: centy Date: Sun, 22 Nov 2026 10:25:45 -0500 Subject: [PATCH 028/107] 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 438f2a9ba8f0f5d943925d16bdc70032d3daa983 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:29:09 -0800 Subject: [PATCH 029/107] Scripts: Promise review fixes for rooting, slices, finally and the combinators - A promise resolved with itself roots its TypeError before the queue reserves room, so a collection there no longer frees the reason. - A sliced run whose last job ends a slice reports Done in that slice instead of Paused, and a pause asked for in a run's last step no longer pauses the next run. - The job queue is replaced at run end, which frees its buffer. - A reaction job runs a finally callback as its own call, so a slice can pause inside it; the callback no longer runs to its end within the unbroken-fuel allowance. - all, allSettled and race read an array to its current length at each step, and a string input is flattened through the charged path and shared instead of copied. - The test262 runner checks the expected exception of an async test with a runtime negative. --- crates/js/src/builtins/promise.rs | 98 ++++++++++++++++++++++--- crates/js/src/promise_tests.rs | 117 +++++++++++++++++++++++++++++- crates/js/tests/test262.rs | 2 +- 3 files changed, 206 insertions(+), 11 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index d960fac60b..52c0e229ae 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -32,6 +32,7 @@ use crate::LimitKind; use crate::bytecode::Code; use crate::heap::{BOUND_ARG_BYTES, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::string_builtins::flat_charged; use crate::value::Value; /// Where a promise was rejected: the code and the instruction. @@ -142,6 +143,9 @@ enum Then { Settle(ObjId), /// 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 + /// Catch Finally function: `derived` is settled as that function's result settles it. + Finally { derived: ObjId, value: Value, throws: bool }, } /// The built-in functions a promise operation's functions call, with their record. @@ -211,6 +215,10 @@ impl Promises { roots.values.extend(self.completion.iter()); match &self.running { Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Finally { derived, value, .. }) => { + roots.objects.push(*derived); + roots.values.push(value); + } None => {} } for job in &self.queue { @@ -233,6 +241,12 @@ impl Promises { JOB_BYTES.saturating_mul(self.queue.len()) } + /// How many jobs are queued, and how many the queue's buffer has room for. + #[cfg(test)] + pub(crate) fn queue_size(&self) -> (usize, usize) { + (self.queue.len(), self.queue.capacity()) + } + /// Drops the noted rejections whose promise has a handler now. pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) { self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled)); @@ -455,7 +469,7 @@ fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult if o == p { let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); let site = here(interp); - return settle(interp, p, false, e, site); + return reject_promise(interp, p, e, site); } let then = match interp.get_from(o, &key("then"), &resolution) { Ok(t) => t, @@ -584,10 +598,12 @@ impl Interp { if self.frames.is_empty() { let Some(job) = self.promises.queue.pop_front() else { self.promises.draining = false; + // A pause asked for in the run's last step ends with the run. + self.pause.set(false); return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined))); }; self.start_job(job)?; - if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + if self.can_pause_between_jobs(pause_at) { return Ok(None); } continue; @@ -597,6 +613,7 @@ impl Interp { Ok(Some(v)) if self.promises.running.is_none() => { // The script's own code ended. if self.promises.queue.is_empty() { + self.pause.set(false); return Ok(Some(v)); } self.promises.completion = Some(v); @@ -606,12 +623,19 @@ impl Interp { Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?, Err(e) => return Err(e), } - if self.frames.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) { + if self.can_pause_between_jobs(pause_at) { return Ok(None); } } } + /// No code is running and jobs are still queued, and the slice has used its fuel or the host + /// asked for a pause. With the queue empty the run is done instead, and the next turn of the + /// loop ends it. + fn can_pause_between_jobs(&self, pause_at: u64) -> bool { + self.frames.is_empty() && !self.promises.queue.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) + } + fn job_returned(&mut self, r: JsResult) -> JsResult<()> { match r { Ok(v) => self.finish_job(Ok(v)), @@ -632,7 +656,14 @@ impl Interp { return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; } root(interp, &Value::Object(derived)); - (handler, Value::Undefined, vec![argument], Then::Settle(derived)) + match finally_callback(interp, &handler) { + // The callback runs as the job's own call, so a slice can pause inside it. + Some((on_finally, throws)) => { + 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)), + } } Job::Thenable { promise, thenable, then } => { interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]); @@ -665,6 +696,18 @@ impl Interp { root(interp, &Value::Object(rec)); reject_through(interp, rec, e, site) }), + (Then::Finally { derived, value, throws }, Ok(result)) => scoped(self, |interp| { + interp.temp_roots.extend([Value::Object(derived), value.clone(), result.clone()]); + match after_finally(interp, result, value, throws) { + Ok(v) => resolve_promise(interp, derived, v), + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + reject_promise(interp, derived, e, site) + } + Err(e) => Err(e), + } + }), + (Then::Finally { derived, .. }, Err(e)) => reject_promise(self, derived, e, site), } } @@ -673,7 +716,8 @@ impl Interp { pub(crate) fn end_jobs(&mut self, keep_rejections: bool) { let queued = self.promises.queue_bytes(); self.heap.bytes = self.heap.bytes.saturating_sub(queued); - self.promises.queue.clear(); + // A new queue frees the old one's buffer, which the heap estimate does not count. + self.promises.queue = VecDeque::new(); self.promises.running = None; self.promises.completion = None; self.promises.draining = false; @@ -799,8 +843,15 @@ fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult JsResult { scoped(interp, |interp| { root(interp, &value); + root(interp, &result); let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object); let promise = promise_resolve(interp, &ctor, result)?; root(interp, &promise); @@ -812,6 +863,29 @@ fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult Option<(Value, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let natives = &interp.promises.natives; + let throws = if natives.get(Kind::ThenFinally as usize) == Some(target) { + false + } else if natives.get(Kind::CatchFinally as usize) == Some(target) { + true + } else { + return None; + }; + match args.first().and_then(Value::as_object).and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::PromiseRecord(rec)) => match &**rec { + Record::Finally { on_finally } => Some((on_finally.clone(), throws)), + _ => None, + }, + _ => None, + } +} + fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { finally_step(interp, args, false) } @@ -934,10 +1008,12 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe }) } -/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. +/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to +/// its length at each step, as an array iterator reads it, and another object up to the `length` +/// it had at the start. enum Inputs { Indexed { object: ObjId, length: f64 }, - CodePoints(Vec), + CodePoints(Rc<[u16]>), } impl Inputs { @@ -949,7 +1025,7 @@ impl Inputs { } _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), }, - Value::String(s) => Ok(Inputs::CodePoints(s.flat().to_vec())), + Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)), _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), } } @@ -958,7 +1034,11 @@ impl Inputs { fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { match self { Inputs::Indexed { object, length } => { - if *index >= *length { + let end = match interp.heap.object(*object).map(|o| &o.class) { + Some(Class::Array { length, .. }) => f64::from(*length), + _ => *length, + }; + if *index >= end { return Ok(None); } let v = super::get_at(interp, *object, *index)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 96e93764ff..8e03f2a136 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -76,6 +76,26 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() { assert_eq!(log(src), "true"); } +#[test] +fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { + let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\ + for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }"; + let mut finished = 0; + for spare in (40_000..240_000).step_by(641) { + let mut r = realm(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match r.run(src) { + Ok(_) => finished += 1, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue, + Err(e) => panic!("{spare}: {e:?}"), + } + r.set_limits(Limits::default()); + assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + } + assert!(finished > 0); +} + #[test] fn catch_finally_and_the_combinators_settle_as_the_specification_says() { let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\ @@ -104,6 +124,36 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { } } +#[test] +fn the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() { + // `Promise.resolve` runs once for each input and appends to the input while it is read. + let src = "var resolve = Promise.resolve; var input;\n\ + Promise.resolve = function (x) {\n\ + if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\ + return resolve.call(this, x);\n\ + };\n\ + input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\ + input = { length: 1, 0: 1 }; Promise.all(input).then(function (v) { log.push('object ' + v.join(',')); });"; + let out = log(src); + assert!(out.contains("array 1,2,3"), "{out}"); + assert!(out.contains("object 1"), "{out}"); + assert!(!out.contains("object 1,"), "{out}"); +} + +#[test] +fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() { + // A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap + // has room for. The combinator would stop at its first input. + let mut r = realm(); + r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() }); + let e = r.run("Promise.race(s)").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}"); + r.set_limits(Limits::default()); + assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0)); +} + #[test] fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { let mut r = realm(); @@ -206,18 +256,83 @@ fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() { assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0)); } +#[test] +fn a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() { + let mut r = realm(); + r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap(); + let v = loop { + match r.advance(1).unwrap() { + Progress::Paused => { + let interp = r.interp(); + assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run"); + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); +} + +#[test] +fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() { + let mut r = realm(); + let flag = r.pause_flag(); + r.define_function("pauseNow", move |_| { + flag.set(true); + Ok(JsValue::Undefined) + }); + r.start("Promise.resolve().then(pauseNow); 'first'").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into()))); + r.start("var a = 1; var b = 2; a + b").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0))); +} + +#[test] +fn a_sliced_run_pauses_inside_a_finally_callback() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.set_unbroken_fuel(5_000); + r.start( + "var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\ + Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\ + Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\ + 'done'", + ) + .unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 10, "{paused_in_jobs}"); + assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into())); +} + #[test] fn an_ended_sliced_run_drops_its_jobs() { let mut r = realm(); - r.start("var ran = 0; Promise.resolve().then(function () { for (;;) ran++; });").unwrap(); + r.start( + "var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });", + ) + .unwrap(); let mut slices = 0; while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining { slices += 1; assert!(slices < 1000); } assert!(r.is_running()); + assert_eq!(r.interp().promises.queue_size().0, 1); r.end(); assert!(!r.is_running()); assert_eq!(r.interp().promises.queue_bytes(), 0); + assert_eq!(r.interp().promises.queue_size(), (0, 0)); assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into())); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 9f5223ea36..0c23a80e9b 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -734,7 +734,7 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool Ok(JsValue::Undefined) }); let result = realm.run(script); - if asynchronous && result.is_ok() { + if asynchronous && result.is_ok() && negative_type.is_none() { let printed = printed.borrow(); return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { Ok(()) From d5de4b2f6bb4854c0c45cb56ca999df89c1a825a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:00:17 -0800 Subject: [PATCH 030/107] Plug-ins: errors for filters that write objects are translated in every complete catalog The messages a filter's `writes` manifest key and its changed type, images and symbol instances can give have an `@msg` row in each of the 25 complete-message catalogs. The other new errors use messages the catalogs already translate: "`{key}` must be a string", "`{key}` must be an object", and "read-only field 'text' changed" for text changes to an object that is not type. --- crates/plugins/src/objects/tests.rs | 7 +++- crates/plugins/src/objects/writes.rs | 59 +++++++++++++++------------- crates/ui-egui/src/i18n/ca.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/da.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/de.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/el.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/es.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/fi.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/fr.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/hi.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/hu.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/id.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/it.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/ja.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/ka.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/ko.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/nl.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/pl.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/pt-br.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/ru.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/sv.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/uk.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/vi.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/zh-hans.tsv | 28 +++++++++++++ crates/ui-egui/src/i18n/zh-hant.tsv | 28 +++++++++++++ 27 files changed, 738 insertions(+), 28 deletions(-) diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 5322425ea8..147b9a1f4a 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1269,7 +1269,7 @@ fn bad_writes_are_refused_naming_the_object_and_the_field() { text, json!({"text": {"runs": styled(&|s| s["fontSzie"] = json!(9))}}), &InputKind::ALL, - "text.runs[0].style: unknown attribute 'fontSzie'".into(), + "text.runs[0].style: unknown key 'fontSzie'".into(), ), ( text, @@ -1285,6 +1285,11 @@ fn bad_writes_are_refused_naming_the_object_and_the_field() { "font_family: must be 1-256 printable characters".into(), ), (text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()), + (text, json!({"text": 5}), &InputKind::ALL, format!("objects[{ti}] (id {t}): `text` must be an object")), + (text, json!({"text": {"runs": [{"text": 5, "style": style}]}}), &InputKind::ALL, "text.runs[0]: `text` must be a string".into()), + (text, json!({"text": {"runs": [{"text": "Hi", "style": 5}]}}), &InputKind::ALL, "text.runs[0]: `style` must be an object".into()), + (text, json!({"text": {"paragraphs": [5, {}]}}), &InputKind::ALL, "text: `paragraphs[0]` must be an object".into()), + (text, json!({"text": {"paragraphs": [{"spaceBefor": 1}, {}]}}), &InputKind::ALL, "text.paragraphs[0]: unknown key 'spaceBefor'".into()), ( text, json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}), diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs index 54b44b74c8..03667373bb 100644 --- a/crates/plugins/src/objects/writes.rs +++ b/crates/plugins/src/objects/writes.rs @@ -51,7 +51,7 @@ pub(super) fn changes(o: &Map, given: &Value, kind: InputKind, at continue; } match (k.as_str(), was) { - ("text", Some(was)) => text_changes(v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?, + ("text", Some(was)) => text_changes(k, v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?, ("name", None) if v.is_null() => {} (_, Some(was)) if first_difference(v, was, "").is_none() => {} _ => { @@ -62,16 +62,17 @@ pub(super) fn changes(o: &Map, given: &Value, kind: InputKind, at Ok((!out.is_empty()).then_some(out)) } -/// The `runs` and `paragraphs` of type text `v` that differ from `was` (the text the input gave), -/// into `out`; its other fields must be as given, and type given as `truncated` keeps its text. A -/// changed list is held to [`MAX_INPUT_RUNS`] entries, and changed runs to [`MAX_INPUT_TEXT`] bytes -/// of text, which count toward `total`, held to [`MAX_INPUT_TEXT_TOTAL`]. -fn text_changes(v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map) -> Result<()> { - let t = v.as_object().ok_or_else(|| out_err(at, "`text` must be an object"))?; +/// The `runs` and `paragraphs` of type text `v`, the output's field `key`, that differ from `was` +/// (the text the input gave), into `out`; its other fields must be as given, and type given as +/// `truncated` keeps its text. A changed list is held to [`MAX_INPUT_RUNS`] entries, and changed +/// runs to [`MAX_INPUT_TEXT`] bytes of text, which count toward `total`, held to +/// [`MAX_INPUT_TEXT_TOTAL`]. +fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map) -> Result<()> { + let t = v.as_object().ok_or_else(|| out_err(at, format!("`{key}` must be an object")))?; let mut keys: Vec<&String> = t.keys().collect(); keys.sort(); for k in keys { - let field = format!("text.{k}"); + let field = format!("{key}.{k}"); let given = was.get(k); let differs = given.is_none_or(|g| first_difference(&t[k], g, "").is_some()); if !matches!(k.as_str(), "runs" | "paragraphs") { @@ -134,16 +135,18 @@ fn attr_names() -> &'static [&'static str] { fields } -/// `v` as a `T` whose attributes are all ones `T` reads: an unknown key, as an ill-typed value, is -/// an error at `at`. -fn strict(v: &Value, at: &str, what: &str) -> Result { - let o = v.as_object().ok_or_else(|| out_err(at, format!("{what} must be an object")))?; +/// `v`, the field `key` of the entry at `parent`, as a `T` whose attributes are all ones `T` reads: +/// a value that isn't an object is an error at `parent`, and an unknown key, as an ill-typed value, +/// an error at `parent.key`. +fn strict(v: &Value, parent: &str, key: &str) -> Result { + let o = v.as_object().ok_or_else(|| out_err(parent, format!("`{key}` must be an object")))?; + let at = format!("{parent}.{key}"); let names = attr_names::(); if let Some(k) = o.keys().find(|k| !names.contains(&k.as_str())) { let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); - return Err(out_err(at, format!("unknown attribute '{k}'"))); + return Err(out_err(&at, format!("unknown key '{k}'"))); } - serde_json::from_value(v.clone()).map_err(|e| out_err(at, e)) + serde_json::from_value(v.clone()).map_err(|e| out_err(&at, e)) } /// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't @@ -212,7 +215,7 @@ pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map, } if changes.contains_key("runs") || changes.contains_key("paragraphs") { let story = doc.story_of(n.id).len(); - let NodeKind::Text(t) = &mut n.kind else { return Err(out_err(at, "only type has text")) }; + let NodeKind::Text(t) = &mut n.kind else { return Err(read_only_changed(at, "text")) }; set_text(doc, t, story > 1, changes.get("runs"), changes.get("paragraphs"), at)?; } if let Some(v) = changes.get("name") { @@ -243,9 +246,10 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); return Err(out_err(&at, format!("unknown key '{k}'"))); } - let text = o.get("text").and_then(Value::as_str).ok_or_else(|| out_err(&at, "`text` must be a string"))?; + let key = "text"; + let text = o.get(key).and_then(Value::as_str).ok_or_else(|| out_err(&at, format!("`{key}` must be a string")))?; let style_v = o.get("style").unwrap_or(&Value::Null); - let mut style: CharStyle = strict(style_v, &format!("{at}.style"), "`style`")?; + let mut style: CharStyle = strict(style_v, &at, "style")?; let inline = match o.get("inline") { None | Some(Value::Null) => None, Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?), @@ -299,13 +303,13 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va } match paragraphs { Some(v) => { - let at = format!("{at}.text.paragraphs"); + let text = format!("{at}.text"); let list = v.as_array().map(Vec::as_slice).unwrap_or_default(); let count = t.paragraph_count(); if list.len() != count { - return Err(out_err(&at, format!("expected {count} paragraph styles, one per paragraph"))); + return Err(out_err(&format!("{text}.paragraphs"), format!("expected {count} paragraph styles, one per paragraph"))); } - let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &format!("{at}[{i}]"))).collect::>()?; + let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &text, &format!("paragraphs[{i}]"))).collect::>()?; t.set_paragraph_styles(styles); } None => t.normalize_paras(), @@ -414,17 +418,18 @@ fn range_err(at: &str, e: &AttrRangeError) -> Error { out_err(&format!("{at}.{}", e.key), &e.message) } -/// Paragraph style `v` from a filter's output, at `at`: each attribute one a paragraph reads, each -/// number in the range the paragraph style commands keep it to ([`ParaStyle::check_ranges`], the -/// Justification options as given), and a custom Kinsoku set one of `doc`'s, by name, whose -/// characters it takes. -fn para_style(doc: &Document, v: &Value, at: &str) -> Result { - let mut st: ParaStyle = strict(v, at, "a paragraph style")?; +/// Paragraph style `v` from a filter's output, the entry `key` of the text at `parent`: each +/// attribute one a paragraph reads, each number in the range the paragraph style commands keep it +/// to ([`ParaStyle::check_ranges`], the Justification options as given), and a custom Kinsoku set +/// one of `doc`'s, by name, whose characters it takes. +fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result { + let mut st: ParaStyle = strict(v, parent, key)?; + let at = format!("{parent}.{key}"); let justification = match v.get("justification") { None | Some(Value::Null) => None, Some(j) => Some(serde_json::from_value::(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?), }; - st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(at, &e))?; + st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(&at, &e))?; if let Some(set) = &st.kinsoku_set { let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| { let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..f44a98aa2b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7875,6 +7875,34 @@ variable-list-end {0}, {1} {0} i {1} @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` +@msg only a filter declares `writes` només un filtre declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` inclou `{shown}` dues vegades +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` inclou `{shown}`, que `inputs` no inclou +@msg `writes` needs `api` {WRITES_API} or later `writes` requereix `api` {WRITES_API} o posterior +@msg `writes` needs the permission `doc.write` `writes` requereix el permís `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} no és text, ni una imatge ni una instància de símbol +@msg the text of type given as `truncated` can't be changed no es pot canviar el text d’un text donat com a `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries ha de ser una llista d’un màxim de {MAX_INPUT_RUNS} entrades +@msg type needs at least one run el text necessita almenys un tram +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de text (límit {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output més de {MAX_INPUT_TEXT_TOTAL} bytes de text en tota la sortida +@msg unknown key '{k}' clau desconeguda '{k}' +@msg must be a list of 6 numbers ha de ser una llista de 6 nombres +@msg a number is out of range (limit ±{MAX_COORD}) un nombre és fora de l’interval (límit ±{MAX_COORD}) +@msg flattens the object to a line or a point redueix l’objecte a una línia o un punt +@msg an object flattened to a line or a point can't be placed again un objecte reduït a una línia o un punt no es pot tornar a col·locar +@msg must be a number from 0 to 1 ha de ser un nombre de 0 a 1 +@msg must be the name of a symbol ha de ser el nom d’un símbol +@msg '{shown}' is not a symbol in this document '{shown}' no és un símbol d’aquest document +@msg a run must be {{"text", "style", "inline"?}} un tram ha de ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` conté el caràcter d’un gràfic en línia +@msg inline graphics can't be added, removed, reordered or changed els gràfics en línia no es poden afegir, eliminar, reordenar ni canviar +@msg the characters of threaded type can't be changed els caràcters del text enllaçat no es poden canviar +@msg the characters of type with ruby can't be changed els caràcters del text amb rubí no es poden canviar +@msg expected {count} paragraph styles, one per paragraph s’esperaven {count} estils de paràgraf, un per paràgraf +@msg the document has no Kinsoku set named '{shown}' el document no té cap conjunt Kinsoku anomenat '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters ha de tenir 1-{MAX_FAMILY} caràcters imprimibles @msg memory budget (object {_1} needs {size} bytes of input, {left} left) pressupost de memòria (l’objecte {_1} necessita {size} bytes d’entrada, en queden {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) pressupost d’objectes (més de {MAX_OBJECTS} objectes de només lectura) @msg instruction budget pressupost d’instruccions diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..bd9a668d87 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7485,6 +7485,34 @@ axis Y Axis osa Y @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` +@msg only a filter declares `writes` `writes` deklaruje pouze filtr +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance +@msg `writes` lists `{shown}` twice `writes` uvádí `{shown}` dvakrát +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` uvádí `{shown}`, který `inputs` neuvádí +@msg `writes` needs `api` {WRITES_API} or later `writes` vyžaduje `api` {WRITES_API} nebo vyšší +@msg `writes` needs the permission `doc.write` `writes` vyžaduje oprávnění `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} není text, obraz ani instance symbolu +@msg the text of type given as `truncated` can't be changed text objektu předaného jako `truncated` nelze změnit +@msg must be a list of at most {MAX_INPUT_RUNS} entries musí být seznam nejvýše {MAX_INPUT_RUNS} položek +@msg type needs at least one run text potřebuje alespoň jeden úsek +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtů textu (limit {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output více než {MAX_INPUT_TEXT_TOTAL} bajtů textu v celém výstupu +@msg unknown key '{k}' neznámý klíč '{k}' +@msg must be a list of 6 numbers musí být seznam 6 čísel +@msg a number is out of range (limit ±{MAX_COORD}) číslo je mimo rozsah (limit ±{MAX_COORD}) +@msg flattens the object to a line or a point zplošťuje objekt na čáru nebo bod +@msg an object flattened to a line or a point can't be placed again objekt zploštělý na čáru nebo bod nelze znovu umístit +@msg must be a number from 0 to 1 musí být číslo od 0 do 1 +@msg must be the name of a symbol musí být název symbolu +@msg '{shown}' is not a symbol in this document '{shown}' není symbol v tomto dokumentu +@msg a run must be {{"text", "style", "inline"?}} úsek musí být {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` obsahuje znak vložené grafiky +@msg inline graphics can't be added, removed, reordered or changed vloženou grafiku nelze přidávat, odebírat, přeřazovat ani měnit +@msg the characters of threaded type can't be changed znaky zřetězeného textu nelze změnit +@msg the characters of type with ruby can't be changed znaky textu s ruby nelze změnit +@msg expected {count} paragraph styles, one per paragraph očekáváno {count} stylů odstavců, jeden na každý odstavec +@msg the document has no Kinsoku set named '{shown}' dokument nemá sadu Kinsoku s názvem '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters musí mít 1-{MAX_FAMILY} tisknutelných znaků @msg memory budget (object {_1} needs {size} bytes of input, {left} left) rozpočet paměti (objekt {_1} potřebuje {size} bajtů vstupu, zbývá {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) rozpočet objektů (více než {MAX_OBJECTS} objektů jen pro čtení) @msg instruction budget rozpočet instrukcí diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..1fd4a9d2d8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -697,6 +697,34 @@ liquify-list-end {0}, {1} {0} og {1} @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` +@msg only a filter declares `writes` kun et filter angiver `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance +@msg `writes` lists `{shown}` twice `writes` angiver `{shown}` to gange +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` angiver `{shown}`, som `inputs` ikke angiver +@msg `writes` needs `api` {WRITES_API} or later `writes` kræver `api` {WRITES_API} eller nyere +@msg `writes` needs the permission `doc.write` `writes` kræver tilladelsen `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} er hverken tekst, et billede eller en symbolforekomst +@msg the text of type given as `truncated` can't be changed teksten i et tekstobjekt givet som `truncated` kan ikke ændres +@msg must be a list of at most {MAX_INPUT_RUNS} entries skal være en liste med højst {MAX_INPUT_RUNS} elementer +@msg type needs at least one run tekst skal have mindst ét tekststykke +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte tekst (grænse {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mere end {MAX_INPUT_TEXT_TOTAL} byte tekst i hele outputtet +@msg unknown key '{k}' ukendt nøgle '{k}' +@msg must be a list of 6 numbers skal være en liste med 6 tal +@msg a number is out of range (limit ±{MAX_COORD}) et tal er uden for området (grænse ±{MAX_COORD}) +@msg flattens the object to a line or a point gør objektet fladt til en linje eller et punkt +@msg an object flattened to a line or a point can't be placed again et objekt, der er gjort fladt til en linje eller et punkt, kan ikke placeres igen +@msg must be a number from 0 to 1 skal være et tal fra 0 til 1 +@msg must be the name of a symbol skal være navnet på et symbol +@msg '{shown}' is not a symbol in this document '{shown}' er ikke et symbol i dette dokument +@msg a run must be {{"text", "style", "inline"?}} et tekststykke skal være {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` indeholder tegnet for en indlejret grafik +@msg inline graphics can't be added, removed, reordered or changed indlejrede grafikker kan ikke tilføjes, fjernes, omarrangeres eller ændres +@msg the characters of threaded type can't be changed tegnene i sammenkædet tekst kan ikke ændres +@msg the characters of type with ruby can't be changed tegnene i tekst med ruby kan ikke ændres +@msg expected {count} paragraph styles, one per paragraph forventede {count} afsnitsstile, én pr. afsnit +@msg the document has no Kinsoku set named '{shown}' dokumentet har intet Kinsoku-sæt med navnet '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters skal være 1-{MAX_FAMILY} tegn, der kan udskrives @msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (mere end {MAX_OBJECTS} skrivebeskyttede objekter) @msg instruction budget instruktionsbudget diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..aa2452f6a7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7068,6 +7068,34 @@ axis Y Axis Y-Achse @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` +@msg only a filter declares `writes` nur ein Filter deklariert `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance +@msg `writes` lists `{shown}` twice `writes` führt `{shown}` doppelt auf +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` führt `{shown}` auf, das `inputs` nicht aufführt +@msg `writes` needs `api` {WRITES_API} or later `writes` erfordert `api` {WRITES_API} oder höher +@msg `writes` needs the permission `doc.write` `writes` erfordert die Berechtigung `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} ist weder Text noch ein Bild noch eine Symbolinstanz +@msg the text of type given as `truncated` can't be changed der Text eines als `truncated` übergebenen Textobjekts kann nicht geändert werden +@msg must be a list of at most {MAX_INPUT_RUNS} entries muss eine Liste mit höchstens {MAX_INPUT_RUNS} Einträgen sein +@msg type needs at least one run Text braucht mindestens einen Abschnitt +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} Byte Text (Grenze {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mehr als {MAX_INPUT_TEXT_TOTAL} Byte Text in der gesamten Ausgabe +@msg unknown key '{k}' unbekannter Schlüssel '{k}' +@msg must be a list of 6 numbers muss eine Liste von 6 Zahlen sein +@msg a number is out of range (limit ±{MAX_COORD}) eine Zahl liegt außerhalb des Bereichs (Grenze ±{MAX_COORD}) +@msg flattens the object to a line or a point macht das Objekt zu einer Linie oder einem Punkt +@msg an object flattened to a line or a point can't be placed again ein zu einer Linie oder einem Punkt zusammengefallenes Objekt kann nicht neu platziert werden +@msg must be a number from 0 to 1 muss eine Zahl von 0 bis 1 sein +@msg must be the name of a symbol muss der Name eines Symbols sein +@msg '{shown}' is not a symbol in this document '{shown}' ist kein Symbol in diesem Dokument +@msg a run must be {{"text", "style", "inline"?}} ein Abschnitt muss {{"text", "style", "inline"?}} sein +@msg `text` holds the character of an inline graphic `text` enthält das Zeichen einer eingebundenen Grafik +@msg inline graphics can't be added, removed, reordered or changed eingebundene Grafiken können nicht hinzugefügt, entfernt, umgeordnet oder geändert werden +@msg the characters of threaded type can't be changed die Zeichen von verkettetem Text können nicht geändert werden +@msg the characters of type with ruby can't be changed die Zeichen von Text mit Ruby können nicht geändert werden +@msg expected {count} paragraph styles, one per paragraph {count} Absatzformate erwartet, eines pro Absatz +@msg the document has no Kinsoku set named '{shown}' das Dokument hat keinen Kinsoku-Satz namens '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters muss 1-{MAX_FAMILY} druckbare Zeichen haben @msg memory budget (object {_1} needs {size} bytes of input, {left} left) Speicherbudget (Objekt {_1} benötigt {size} Byte Eingabe, {left} verbleiben) @msg object budget (more than {MAX_OBJECTS} read-only objects) Objektbudget (mehr als {MAX_OBJECTS} schreibgeschützte Objekte) @msg instruction budget Anweisungsbudget diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..2932e0f10f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7475,6 +7475,34 @@ axis Y Axis Άξονας Y @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` +@msg only a filter declares `writes` μόνο ένα φίλτρο δηλώνει `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance το `writes` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance +@msg `writes` lists `{shown}` twice το `writes` αναφέρει το `{shown}` δύο φορές +@msg `writes` lists `{shown}`, which `inputs` doesn't list το `writes` αναφέρει το `{shown}`, το οποίο δεν αναφέρει το `inputs` +@msg `writes` needs `api` {WRITES_API} or later το `writes` απαιτεί `api` {WRITES_API} ή νεότερο +@msg `writes` needs the permission `doc.write` το `writes` απαιτεί το δικαίωμα `doc.write` +@msg {_1} is not type, an image or a symbol instance το {_1} δεν είναι κείμενο, εικόνα ή στιγμιότυπο συμβόλου +@msg the text of type given as `truncated` can't be changed το κείμενο ενός αντικειμένου κειμένου που δόθηκε ως `truncated` δεν μπορεί να αλλάξει +@msg must be a list of at most {MAX_INPUT_RUNS} entries πρέπει να είναι λίστα με έως {MAX_INPUT_RUNS} στοιχεία +@msg type needs at least one run το κείμενο χρειάζεται τουλάχιστον ένα τμήμα +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte κειμένου (όριο {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output περισσότερα από {MAX_INPUT_TEXT_TOTAL} byte κειμένου σε όλη την έξοδο +@msg unknown key '{k}' άγνωστο κλειδί '{k}' +@msg must be a list of 6 numbers πρέπει να είναι λίστα 6 αριθμών +@msg a number is out of range (limit ±{MAX_COORD}) ένας αριθμός είναι εκτός εύρους (όριο ±{MAX_COORD}) +@msg flattens the object to a line or a point συμπιέζει το αντικείμενο σε γραμμή ή σημείο +@msg an object flattened to a line or a point can't be placed again ένα αντικείμενο που συμπιέστηκε σε γραμμή ή σημείο δεν μπορεί να τοποθετηθεί ξανά +@msg must be a number from 0 to 1 πρέπει να είναι αριθμός από 0 έως 1 +@msg must be the name of a symbol πρέπει να είναι το όνομα ενός συμβόλου +@msg '{shown}' is not a symbol in this document το '{shown}' δεν είναι σύμβολο σε αυτό το έγγραφο +@msg a run must be {{"text", "style", "inline"?}} ένα τμήμα πρέπει να είναι {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic το `text` περιέχει τον χαρακτήρα ενός ενσωματωμένου γραφικού +@msg inline graphics can't be added, removed, reordered or changed τα ενσωματωμένα γραφικά δεν μπορούν να προστεθούν, να αφαιρεθούν, να αναδιαταχθούν ή να αλλάξουν +@msg the characters of threaded type can't be changed οι χαρακτήρες συνδεδεμένου κειμένου δεν μπορούν να αλλάξουν +@msg the characters of type with ruby can't be changed οι χαρακτήρες κειμένου με ruby δεν μπορούν να αλλάξουν +@msg expected {count} paragraph styles, one per paragraph αναμένονταν {count} στυλ παραγράφων, ένα ανά παράγραφο +@msg the document has no Kinsoku set named '{shown}' το έγγραφο δεν έχει σύνολο Kinsoku με όνομα '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters πρέπει να έχει 1-{MAX_FAMILY} εκτυπώσιμους χαρακτήρες @msg memory budget (object {_1} needs {size} bytes of input, {left} left) προϋπολογισμός μνήμης (το αντικείμενο {_1} χρειάζεται {size} byte εισόδου, απομένουν {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) προϋπολογισμός αντικειμένων (περισσότερα από {MAX_OBJECTS} αντικείμενα μόνο για ανάγνωση) @msg instruction budget προϋπολογισμός εντολών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..34276431cb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7461,6 +7461,34 @@ axis Y Axis Eje Y @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` +@msg only a filter declares `writes` solo un filtro declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` incluye `{shown}` dos veces +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` incluye `{shown}`, que `inputs` no incluye +@msg `writes` needs `api` {WRITES_API} or later `writes` requiere `api` {WRITES_API} o posterior +@msg `writes` needs the permission `doc.write` `writes` requiere el permiso `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} no es texto, ni una imagen ni una instancia de símbolo +@msg the text of type given as `truncated` can't be changed no se puede cambiar el texto de un objeto de texto dado como `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries debe ser una lista de {MAX_INPUT_RUNS} entradas como máximo +@msg type needs at least one run el texto necesita al menos un tramo +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (límite {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output más de {MAX_INPUT_TEXT_TOTAL} bytes de texto en toda la salida +@msg unknown key '{k}' clave desconocida '{k}' +@msg must be a list of 6 numbers debe ser una lista de 6 números +@msg a number is out of range (limit ±{MAX_COORD}) un número está fuera de rango (límite ±{MAX_COORD}) +@msg flattens the object to a line or a point reduce el objeto a una línea o un punto +@msg an object flattened to a line or a point can't be placed again un objeto reducido a una línea o un punto no se puede volver a colocar +@msg must be a number from 0 to 1 debe ser un número de 0 a 1 +@msg must be the name of a symbol debe ser el nombre de un símbolo +@msg '{shown}' is not a symbol in this document '{shown}' no es un símbolo de este documento +@msg a run must be {{"text", "style", "inline"?}} un tramo debe ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contiene el carácter de un gráfico en línea +@msg inline graphics can't be added, removed, reordered or changed los gráficos en línea no se pueden añadir, quitar, reordenar ni cambiar +@msg the characters of threaded type can't be changed los caracteres del texto enlazado no se pueden cambiar +@msg the characters of type with ruby can't be changed los caracteres del texto con ruby no se pueden cambiar +@msg expected {count} paragraph styles, one per paragraph se esperaban {count} estilos de párrafo, uno por párrafo +@msg the document has no Kinsoku set named '{shown}' el documento no tiene ningún conjunto de kinsoku llamado '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters debe tener 1-{MAX_FAMILY} caracteres imprimibles @msg memory budget (object {_1} needs {size} bytes of input, {left} left) presupuesto de memoria (el objeto {_1} necesita {size} bytes de entrada, quedan {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) presupuesto de objetos (más de {MAX_OBJECTS} objetos de solo lectura) @msg instruction budget presupuesto de instrucciones diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..f32241570a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7552,6 +7552,34 @@ axis Y Axis Y-akseli @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` +@msg only a filter declares `writes` vain suodatin voi määrittää `writes`-avaimen +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance +@msg `writes` lists `{shown}` twice `writes` luettelee kohteen `{shown}` kahdesti +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` luettelee kohteen `{shown}`, jota `inputs` ei luettele +@msg `writes` needs `api` {WRITES_API} or later `writes` edellyttää `api`-tasoa {WRITES_API} tai uudempaa +@msg `writes` needs the permission `doc.write` `writes` edellyttää käyttöoikeutta `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} ei ole teksti, kuva eikä symbolin ilmentymä +@msg the text of type given as `truncated` can't be changed `truncated`-merkinnällä annetun tekstiobjektin tekstiä ei voi muuttaa +@msg must be a list of at most {MAX_INPUT_RUNS} entries on oltava luettelo, jossa on enintään {MAX_INPUT_RUNS} kohdetta +@msg type needs at least one run tekstissä on oltava vähintään yksi tekstijakso +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} tavua tekstiä (raja {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output yli {MAX_INPUT_TEXT_TOTAL} tavua tekstiä koko tulosteessa +@msg unknown key '{k}' tuntematon avain '{k}' +@msg must be a list of 6 numbers on oltava 6 luvun luettelo +@msg a number is out of range (limit ±{MAX_COORD}) luku on alueen ulkopuolella (raja ±{MAX_COORD}) +@msg flattens the object to a line or a point litistää objektin viivaksi tai pisteeksi +@msg an object flattened to a line or a point can't be placed again viivaksi tai pisteeksi litistynyttä objektia ei voi sijoittaa uudelleen +@msg must be a number from 0 to 1 on oltava luku väliltä 0-1 +@msg must be the name of a symbol on oltava symbolin nimi +@msg '{shown}' is not a symbol in this document '{shown}' ei ole symboli tässä dokumentissa +@msg a run must be {{"text", "style", "inline"?}} tekstijakson on oltava {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` sisältää upotetun grafiikan merkin +@msg inline graphics can't be added, removed, reordered or changed upotettuja grafiikoita ei voi lisätä, poistaa, järjestää uudelleen eikä muuttaa +@msg the characters of threaded type can't be changed ketjutetun tekstin merkkejä ei voi muuttaa +@msg the characters of type with ruby can't be changed ruby-merkintöjä sisältävän tekstin merkkejä ei voi muuttaa +@msg expected {count} paragraph styles, one per paragraph odotettiin {count} kappaletyyliä, yksi kutakin kappaletta kohden +@msg the document has no Kinsoku set named '{shown}' dokumentissa ei ole Kinsoku-joukkoa nimeltä '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters siinä on oltava 1-{MAX_FAMILY} tulostettavaa merkkiä @msg memory budget (object {_1} needs {size} bytes of input, {left} left) muistibudjetti (objekti {_1} tarvitsee {size} tavua syötettä, jäljellä {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektibudjetti (yli {MAX_OBJECTS} vain luku -objektia) @msg instruction budget käskybudjetti diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..47613b7f0b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7482,6 +7482,34 @@ axis Y Axis Axe Y @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` +@msg only a filter declares `writes` seul un filtre déclare `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance +@msg `writes` lists `{shown}` twice `writes` mentionne `{shown}` deux fois +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` mentionne `{shown}`, que `inputs` ne mentionne pas +@msg `writes` needs `api` {WRITES_API} or later `writes` nécessite `api` {WRITES_API} ou plus +@msg `writes` needs the permission `doc.write` `writes` nécessite l’autorisation `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} n’est ni du texte, ni une image, ni une instance de symbole +@msg the text of type given as `truncated` can't be changed le texte d’un objet texte fourni comme `truncated` ne peut pas être modifié +@msg must be a list of at most {MAX_INPUT_RUNS} entries doit être une liste d’au plus {MAX_INPUT_RUNS} entrées +@msg type needs at least one run le texte doit compter au moins un segment +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} octets de texte (limite {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output plus de {MAX_INPUT_TEXT_TOTAL} octets de texte sur l’ensemble de la sortie +@msg unknown key '{k}' clé inconnue '{k}' +@msg must be a list of 6 numbers doit être une liste de 6 nombres +@msg a number is out of range (limit ±{MAX_COORD}) un nombre est hors limites (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point réduit l’objet à une ligne ou à un point +@msg an object flattened to a line or a point can't be placed again un objet réduit à une ligne ou à un point ne peut pas être replacé +@msg must be a number from 0 to 1 doit être un nombre de 0 à 1 +@msg must be the name of a symbol doit être le nom d’un symbole +@msg '{shown}' is not a symbol in this document '{shown}' n’est pas un symbole de ce document +@msg a run must be {{"text", "style", "inline"?}} un segment doit être {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contient le caractère d’un graphique incorporé +@msg inline graphics can't be added, removed, reordered or changed les graphiques incorporés ne peuvent pas être ajoutés, supprimés, réordonnés ni modifiés +@msg the characters of threaded type can't be changed les caractères d’un texte lié ne peuvent pas être modifiés +@msg the characters of type with ruby can't be changed les caractères d’un texte avec ruby ne peuvent pas être modifiés +@msg expected {count} paragraph styles, one per paragraph {count} styles de paragraphe attendus, un par paragraphe +@msg the document has no Kinsoku set named '{shown}' le document n’a aucun jeu de kinsoku nommé '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters doit compter 1-{MAX_FAMILY} caractères imprimables @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget mémoire (l’objet {_1} nécessite {size} octets d’entrée, il en reste {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budget d’objets (plus de {MAX_OBJECTS} objets en lecture seule) @msg instruction budget budget d’instructions diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..c2a539baaa 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6669,6 +6669,34 @@ arrowhead Feather पंख @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है +@msg only a filter declares `writes` केवल फ़िल्टर `writes` घोषित करता है +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें +@msg `writes` lists `{shown}` twice `writes` में `{shown}` दो बार सूचीबद्ध है +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` में `{shown}` सूचीबद्ध है, जो `inputs` में सूचीबद्ध नहीं है +@msg `writes` needs `api` {WRITES_API} or later `writes` के लिए `api` {WRITES_API} या बाद का स्तर आवश्यक है +@msg `writes` needs the permission `doc.write` `writes` के लिए अनुमति `doc.write` आवश्यक है +@msg {_1} is not type, an image or a symbol instance {_1} न टेक्स्ट है, न इमेज, न सिंबल इंस्टेंस +@msg the text of type given as `truncated` can't be changed `truncated` के रूप में दिए गए टेक्स्ट ऑब्जेक्ट का टेक्स्ट बदला नहीं जा सकता +@msg must be a list of at most {MAX_INPUT_RUNS} entries अधिकतम {MAX_INPUT_RUNS} प्रविष्टियों की सूची होनी चाहिए +@msg type needs at least one run टेक्स्ट में कम से कम एक रन होना चाहिए +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) टेक्स्ट के {bytes} बाइट (सीमा {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output पूरे आउटपुट में {MAX_INPUT_TEXT_TOTAL} बाइट से अधिक टेक्स्ट +@msg unknown key '{k}' अज्ञात कुंजी '{k}' +@msg must be a list of 6 numbers 6 संख्याओं की सूची होनी चाहिए +@msg a number is out of range (limit ±{MAX_COORD}) एक संख्या सीमा से बाहर है (सीमा ±{MAX_COORD}) +@msg flattens the object to a line or a point ऑब्जेक्ट को एक रेखा या बिंदु में चपटा कर देता है +@msg an object flattened to a line or a point can't be placed again रेखा या बिंदु में चपटे हुए ऑब्जेक्ट को फिर से रखा नहीं जा सकता +@msg must be a number from 0 to 1 0 से 1 तक की संख्या होनी चाहिए +@msg must be the name of a symbol किसी सिंबल का नाम होना चाहिए +@msg '{shown}' is not a symbol in this document '{shown}' इस दस्तावेज़ में कोई सिंबल नहीं है +@msg a run must be {{"text", "style", "inline"?}} रन {{"text", "style", "inline"?}} होना चाहिए +@msg `text` holds the character of an inline graphic `text` में इनलाइन ग्राफ़िक का वर्ण है +@msg inline graphics can't be added, removed, reordered or changed इनलाइन ग्राफ़िक जोड़े, हटाए, पुनः क्रमित या बदले नहीं जा सकते +@msg the characters of threaded type can't be changed थ्रेडेड टेक्स्ट के वर्ण बदले नहीं जा सकते +@msg the characters of type with ruby can't be changed रूबी वाले टेक्स्ट के वर्ण बदले नहीं जा सकते +@msg expected {count} paragraph styles, one per paragraph {count} पैराग्राफ़ स्टाइल अपेक्षित थे, हर पैराग्राफ़ के लिए एक +@msg the document has no Kinsoku set named '{shown}' दस्तावेज़ में '{shown}' नाम का कोई किनसोकू सेट नहीं है +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} प्रिंट करने योग्य वर्ण होने चाहिए @msg memory budget (object {_1} needs {size} bytes of input, {left} left) मेमोरी बजट (ऑब्जेक्ट {_1} को इनपुट के {size} बाइट चाहिए, {left} शेष हैं) @msg object budget (more than {MAX_OBJECTS} read-only objects) ऑब्जेक्ट बजट ({MAX_OBJECTS} से अधिक केवल-पठन ऑब्जेक्ट) @msg the plug-in's grant can't be removed from the plug-in store प्लग-इन की अनुमति प्लग-इन स्टोर से हटाई नहीं जा सकती diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..33c9c60ee3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7470,6 +7470,34 @@ axis Y Axis Y tengely @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges +@msg only a filter declares `writes` `writes` kulcsot csak szűrő adhat meg +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance a `writes` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket +@msg `writes` lists `{shown}` twice a `writes` kétszer sorolja fel ezt: `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list a `writes` felsorolja ezt: `{shown}`, de az `inputs` nem sorolja fel +@msg `writes` needs `api` {WRITES_API} or later a `writes` használatához `api` {WRITES_API} vagy újabb szükséges +@msg `writes` needs the permission `doc.write` a `writes` használatához a(z) `doc.write` engedély szükséges +@msg {_1} is not type, an image or a symbol instance {_1} nem szöveg, nem kép és nem szimbólumpéldány +@msg the text of type given as `truncated` can't be changed a `truncated` jelöléssel átadott szövegobjektum szövege nem módosítható +@msg must be a list of at most {MAX_INPUT_RUNS} entries legfeljebb {MAX_INPUT_RUNS} elemű lista legyen +@msg type needs at least one run a szövegnek legalább egy szakaszra van szüksége +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bájt szöveg (korlát: {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output több mint {MAX_INPUT_TEXT_TOTAL} bájt szöveg a teljes kimenetben +@msg unknown key '{k}' ismeretlen kulcs: '{k}' +@msg must be a list of 6 numbers 6 számból álló lista legyen +@msg a number is out of range (limit ±{MAX_COORD}) egy szám a tartományon kívül esik (korlát: ±{MAX_COORD}) +@msg flattens the object to a line or a point vonallá vagy ponttá lapítja az objektumot +@msg an object flattened to a line or a point can't be placed again a vonallá vagy ponttá lapított objektum nem helyezhető el újra +@msg must be a number from 0 to 1 0 és 1 közötti szám legyen +@msg must be the name of a symbol egy szimbólum neve legyen +@msg '{shown}' is not a symbol in this document '{shown}' nem szimbólum ebben a dokumentumban +@msg a run must be {{"text", "style", "inline"?}} egy szakasz formája {{"text", "style", "inline"?}} legyen +@msg `text` holds the character of an inline graphic a `text` egy szövegközi grafika karakterét tartalmazza +@msg inline graphics can't be added, removed, reordered or changed szövegközi grafikák nem adhatók hozzá, nem távolíthatók el, nem rendezhetők át és nem módosíthatók +@msg the characters of threaded type can't be changed a láncolt szöveg karakterei nem módosíthatók +@msg the characters of type with ruby can't be changed a rubyt tartalmazó szöveg karakterei nem módosíthatók +@msg expected {count} paragraph styles, one per paragraph {count} bekezdésstílus volt várható, bekezdésenként egy +@msg the document has no Kinsoku set named '{shown}' a dokumentumban nincs '{shown}' nevű Kinsoku-készlet +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} nyomtatható karakter legyen @msg memory budget (object {_1} needs {size} bytes of input, {left} left) memóriakeret (a(z) {_1} objektumnak {size} bájt bemenet kell, {left} maradt) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektumkeret (több mint {MAX_OBJECTS} csak olvasható objektum) @msg instruction budget utasításkeret diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..caf5f93cfe 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -579,6 +579,34 @@ @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` +@msg only a filter declares `writes` hanya filter yang mendeklarasikan `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance +@msg `writes` lists `{shown}` twice `writes` mencantumkan `{shown}` dua kali +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` mencantumkan `{shown}`, yang tidak dicantumkan `inputs` +@msg `writes` needs `api` {WRITES_API} or later `writes` memerlukan `api` {WRITES_API} atau lebih baru +@msg `writes` needs the permission `doc.write` `writes` memerlukan izin `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} bukan teks, gambar, atau instans simbol +@msg the text of type given as `truncated` can't be changed teks dari objek teks yang diberikan sebagai `truncated` tidak dapat diubah +@msg must be a list of at most {MAX_INPUT_RUNS} entries harus berupa daftar berisi paling banyak {MAX_INPUT_RUNS} entri +@msg type needs at least one run teks memerlukan setidaknya satu potongan +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte teks (batas {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output lebih dari {MAX_INPUT_TEXT_TOTAL} byte teks di seluruh keluaran +@msg unknown key '{k}' kunci tidak dikenal '{k}' +@msg must be a list of 6 numbers harus berupa daftar 6 angka +@msg a number is out of range (limit ±{MAX_COORD}) sebuah angka di luar rentang (batas ±{MAX_COORD}) +@msg flattens the object to a line or a point memipihkan objek menjadi garis atau titik +@msg an object flattened to a line or a point can't be placed again objek yang dipipihkan menjadi garis atau titik tidak dapat ditempatkan lagi +@msg must be a number from 0 to 1 harus berupa angka dari 0 sampai 1 +@msg must be the name of a symbol harus berupa nama simbol +@msg '{shown}' is not a symbol in this document '{shown}' bukan simbol di dokumen ini +@msg a run must be {{"text", "style", "inline"?}} potongan harus berupa {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` berisi karakter grafik sebaris +@msg inline graphics can't be added, removed, reordered or changed grafik sebaris tidak dapat ditambahkan, dihapus, diurutkan ulang, atau diubah +@msg the characters of threaded type can't be changed karakter teks beruntun tidak dapat diubah +@msg the characters of type with ruby can't be changed karakter teks dengan ruby tidak dapat diubah +@msg expected {count} paragraph styles, one per paragraph diharapkan {count} gaya paragraf, satu per paragraf +@msg the document has no Kinsoku set named '{shown}' dokumen tidak memiliki set Kinsoku bernama '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters harus berupa 1-{MAX_FAMILY} karakter yang dapat dicetak @msg memory budget (object {_1} needs {size} bytes of input, {left} left) anggaran memori (objek {_1} memerlukan {size} byte masukan, tersisa {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) anggaran objek (lebih dari {MAX_OBJECTS} objek baca-saja) @msg instruction budget anggaran instruksi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..0659a3fcb0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7107,6 +7107,34 @@ axis Y Axis Asse Y @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` +@msg only a filter declares `writes` solo un filtro dichiara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` elenca `{shown}` due volte +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` elenca `{shown}`, che `inputs` non elenca +@msg `writes` needs `api` {WRITES_API} or later `writes` richiede `api` {WRITES_API} o successivo +@msg `writes` needs the permission `doc.write` `writes` richiede l’autorizzazione `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} non è testo, né un’immagine né un’istanza di simbolo +@msg the text of type given as `truncated` can't be changed il testo di un oggetto di testo fornito come `truncated` non può essere modificato +@msg must be a list of at most {MAX_INPUT_RUNS} entries deve essere un elenco di al massimo {MAX_INPUT_RUNS} voci +@msg type needs at least one run il testo richiede almeno un segmento +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte di testo (limite {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output più di {MAX_INPUT_TEXT_TOTAL} byte di testo nell’intero output +@msg unknown key '{k}' chiave sconosciuta '{k}' +@msg must be a list of 6 numbers deve essere un elenco di 6 numeri +@msg a number is out of range (limit ±{MAX_COORD}) un numero è fuori intervallo (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point riduce l’oggetto a una linea o a un punto +@msg an object flattened to a line or a point can't be placed again un oggetto ridotto a una linea o a un punto non può essere ricollocato +@msg must be a number from 0 to 1 deve essere un numero da 0 a 1 +@msg must be the name of a symbol deve essere il nome di un simbolo +@msg '{shown}' is not a symbol in this document '{shown}' non è un simbolo di questo documento +@msg a run must be {{"text", "style", "inline"?}} un segmento deve essere {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contiene il carattere di una grafica in linea +@msg inline graphics can't be added, removed, reordered or changed le grafiche in linea non possono essere aggiunte, rimosse, riordinate o modificate +@msg the characters of threaded type can't be changed i caratteri del testo concatenato non possono essere modificati +@msg the characters of type with ruby can't be changed i caratteri del testo con ruby non possono essere modificati +@msg expected {count} paragraph styles, one per paragraph attesi {count} stili paragrafo, uno per paragrafo +@msg the document has no Kinsoku set named '{shown}' il documento non ha alcun set kinsoku denominato '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters deve avere 1-{MAX_FAMILY} caratteri stampabili @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget di memoria (l’oggetto {_1} richiede {size} byte di input, ne restano {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budget di oggetti (più di {MAX_OBJECTS} oggetti di sola lettura) @msg instruction budget budget di istruzioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..40564d2335 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7182,6 +7182,34 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です +@msg only a filter declares `writes` `writes` を宣言できるのはフィルターだけです +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください +@msg `writes` lists `{shown}` twice `writes` に `{shown}` が 2 回指定されています +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` に指定された `{shown}` は `inputs` に指定されていません +@msg `writes` needs `api` {WRITES_API} or later `writes` には `api` {WRITES_API} 以上が必要です +@msg `writes` needs the permission `doc.write` `writes` には権限 `doc.write` が必要です +@msg {_1} is not type, an image or a symbol instance {_1} はテキスト、画像、シンボルインスタンスのいずれでもありません +@msg the text of type given as `truncated` can't be changed `truncated` として渡されたテキストの文字列は変更できません +@msg must be a list of at most {MAX_INPUT_RUNS} entries {MAX_INPUT_RUNS} 項目以下のリストにしてください +@msg type needs at least one run テキストには 1 つ以上のランが必要です +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) テキストが {bytes} バイトあります (上限 {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 出力全体のテキストが {MAX_INPUT_TEXT_TOTAL} バイトを超えています +@msg unknown key '{k}' 不明なキー '{k}' +@msg must be a list of 6 numbers 6 つの数値のリストにしてください +@msg a number is out of range (limit ±{MAX_COORD}) 数値が範囲外です (上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point オブジェクトが線または点につぶれます +@msg an object flattened to a line or a point can't be placed again 線または点につぶれたオブジェクトは配置し直せません +@msg must be a number from 0 to 1 0 から 1 までの数値にしてください +@msg must be the name of a symbol シンボルの名前にしてください +@msg '{shown}' is not a symbol in this document '{shown}' はこのドキュメントのシンボルではありません +@msg a run must be {{"text", "style", "inline"?}} ランは {{"text", "style", "inline"?}} にしてください +@msg `text` holds the character of an inline graphic `text` にインライングラフィックの文字が含まれています +@msg inline graphics can't be added, removed, reordered or changed インライングラフィックは追加、削除、並べ替え、変更できません +@msg the characters of threaded type can't be changed スレッドテキストの文字は変更できません +@msg the characters of type with ruby can't be changed ルビのあるテキストの文字は変更できません +@msg expected {count} paragraph styles, one per paragraph 段落スタイルは段落ごとに 1 つ、計 {count} 個必要です +@msg the document has no Kinsoku set named '{shown}' ドキュメントに '{shown}' という名前の禁則処理セットはありません +@msg must be 1-{MAX_FAMILY} printable characters 印刷可能な 1-{MAX_FAMILY} 文字にしてください @msg memory budget (object {_1} needs {size} bytes of input, {left} left) メモリ予算 (オブジェクト {_1} には {size} バイトの入力が必要ですが、残りは {left} です) @msg object budget (more than {MAX_OBJECTS} read-only objects) オブジェクト予算 ({MAX_OBJECTS} 個を超える読み取り専用オブジェクト) @msg instruction budget 命令予算 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..d03cd5d871 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9588,6 +9588,34 @@ axis Y Axis Y ღერძი @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` +@msg only a filter declares `writes` `writes`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance +@msg `writes` lists `{shown}` twice `writes`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes`-ში ჩამოთვლილია `{shown}`, რომელიც `inputs`-ში არ არის ჩამოთვლილი +@msg `writes` needs `api` {WRITES_API} or later `writes`-ს სჭირდება `api` {WRITES_API} ან უფრო ახალი +@msg `writes` needs the permission `doc.write` `writes`-ს სჭირდება ნებართვა `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} არც ტექსტია, არც გამოსახულება და არც სიმბოლოს ეგზემპლარი +@msg the text of type given as `truncated` can't be changed `truncated`-ად გადაცემული ტექსტური ობიექტის ტექსტის შეცვლა შეუძლებელია +@msg must be a list of at most {MAX_INPUT_RUNS} entries უნდა იყოს სია მაქსიმუმ {MAX_INPUT_RUNS} ჩანაწერით +@msg type needs at least one run ტექსტს სჭირდება მინიმუმ ერთი მონაკვეთი +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) ტექსტის {bytes} ბაიტი (ლიმიტი {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output მთელ გამონატანში {MAX_INPUT_TEXT_TOTAL} ბაიტზე მეტი ტექსტია +@msg unknown key '{k}' უცნობი გასაღები '{k}' +@msg must be a list of 6 numbers უნდა იყოს 6 რიცხვის სია +@msg a number is out of range (limit ±{MAX_COORD}) რიცხვი დიაპაზონს გარეთაა (ლიმიტი ±{MAX_COORD}) +@msg flattens the object to a line or a point ობიექტს ხაზად ან წერტილად აბრტყელებს +@msg an object flattened to a line or a point can't be placed again ხაზად ან წერტილად გაბრტყელებული ობიექტის ხელახლა განთავსება შეუძლებელია +@msg must be a number from 0 to 1 უნდა იყოს რიცხვი 0-დან 1-მდე +@msg must be the name of a symbol უნდა იყოს სიმბოლოს სახელი +@msg '{shown}' is not a symbol in this document '{shown}' ამ დოკუმენტში სიმბოლო არ არის +@msg a run must be {{"text", "style", "inline"?}} მონაკვეთი უნდა იყოს {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` შეიცავს ტექსტში ჩასმული გრაფიკის სიმბოლოს +@msg inline graphics can't be added, removed, reordered or changed ტექსტში ჩასმული გრაფიკის დამატება, წაშლა, გადალაგება ან შეცვლა შეუძლებელია +@msg the characters of threaded type can't be changed დაკავშირებული ტექსტის სიმბოლოების შეცვლა შეუძლებელია +@msg the characters of type with ruby can't be changed რუბის მქონე ტექსტის სიმბოლოების შეცვლა შეუძლებელია +@msg expected {count} paragraph styles, one per paragraph მოსალოდნელი იყო აბზაცის {count} სტილი, თითო აბზაცზე ერთი +@msg the document has no Kinsoku set named '{shown}' დოკუმენტს არ აქვს Kinsoku-ის ნაკრები სახელით '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters უნდა შედგებოდეს 1-{MAX_FAMILY} დასაბეჭდი სიმბოლოსგან @msg memory budget (object {_1} needs {size} bytes of input, {left} left) მეხსიერების ბიუჯეტი (ობიექტს {_1} სჭირდება შეყვანის {size} ბაიტი, დარჩენილია {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) ობიექტების ბიუჯეტი ({MAX_OBJECTS}-ზე მეტი მხოლოდ წასაკითხი ობიექტი) @msg instruction budget ინსტრუქციების ბიუჯეტი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..5d9fc80d8e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7079,6 +7079,34 @@ axis Y Axis Y축 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 +@msg only a filter declares `writes` 필터만 `writes`를 선언할 수 있습니다 +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 +@msg `writes` lists `{shown}` twice `writes`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes`에 나열된 `{shown}`이(가) `inputs`에는 없습니다 +@msg `writes` needs `api` {WRITES_API} or later `writes`에는 `api` {WRITES_API} 이상이 필요합니다 +@msg `writes` needs the permission `doc.write` `writes`에는 `doc.write` 권한이 필요합니다 +@msg {_1} is not type, an image or a symbol instance {_1}은(는) 문자, 이미지, 심볼 인스턴스가 아닙니다 +@msg the text of type given as `truncated` can't be changed `truncated`로 전달된 문자 개체의 텍스트는 변경할 수 없습니다 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 항목이 최대 {MAX_INPUT_RUNS}개인 목록이어야 합니다 +@msg type needs at least one run 문자에는 런이 하나 이상 있어야 합니다 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 텍스트 {bytes}바이트(한도 {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 출력 전체의 텍스트가 {MAX_INPUT_TEXT_TOTAL}바이트를 넘습니다 +@msg unknown key '{k}' 알 수 없는 키 '{k}' +@msg must be a list of 6 numbers 숫자 6개의 목록이어야 합니다 +@msg a number is out of range (limit ±{MAX_COORD}) 숫자가 범위를 벗어났습니다(한도 ±{MAX_COORD}) +@msg flattens the object to a line or a point 개체를 선이나 점으로 납작하게 만듭니다 +@msg an object flattened to a line or a point can't be placed again 선이나 점으로 납작해진 개체는 다시 배치할 수 없습니다 +@msg must be a number from 0 to 1 0에서 1 사이의 숫자여야 합니다 +@msg must be the name of a symbol 심볼 이름이어야 합니다 +@msg '{shown}' is not a symbol in this document '{shown}'은(는) 이 문서의 심볼이 아닙니다 +@msg a run must be {{"text", "style", "inline"?}} 런은 {{"text", "style", "inline"?}} 형식이어야 합니다 +@msg `text` holds the character of an inline graphic `text`에 인라인 그래픽 문자가 들어 있습니다 +@msg inline graphics can't be added, removed, reordered or changed 인라인 그래픽은 추가, 제거, 순서 변경, 수정할 수 없습니다 +@msg the characters of threaded type can't be changed 연결된 문자의 글자는 변경할 수 없습니다 +@msg the characters of type with ruby can't be changed 루비가 있는 문자의 글자는 변경할 수 없습니다 +@msg expected {count} paragraph styles, one per paragraph 단락마다 하나씩 단락 스타일 {count}개가 필요합니다 +@msg the document has no Kinsoku set named '{shown}' 문서에 '{shown}'(이)라는 긴소쿠 세트가 없습니다 +@msg must be 1-{MAX_FAMILY} printable characters 인쇄 가능한 문자 1-{MAX_FAMILY}자여야 합니다 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 메모리 예산(개체 {_1}에 입력 {size}바이트가 필요하지만 {left}바이트 남음) @msg object budget (more than {MAX_OBJECTS} read-only objects) 개체 예산(읽기 전용 개체 {MAX_OBJECTS}개 초과) @msg instruction budget 명령어 예산 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..98b9ef88fa 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -543,6 +543,34 @@ liquify-list-end {0}, {1} {0} en {1} @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` +@msg only a filter declares `writes` alleen een filter declareert `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` noemt een onbekende objectsoort `{shown}`: gebruik type, image of symbolInstance +@msg `writes` lists `{shown}` twice `writes` noemt `{shown}` twee keer +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` noemt `{shown}`, dat `inputs` niet noemt +@msg `writes` needs `api` {WRITES_API} or later `writes` vereist `api` {WRITES_API} of hoger +@msg `writes` needs the permission `doc.write` `writes` vereist de machtiging `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} is geen tekst, afbeelding of symboolinstantie +@msg the text of type given as `truncated` can't be changed de tekst van een tekstobject dat als `truncated` is doorgegeven, kan niet worden gewijzigd +@msg must be a list of at most {MAX_INPUT_RUNS} entries moet een lijst van ten hoogste {MAX_INPUT_RUNS} items zijn +@msg type needs at least one run tekst heeft ten minste één tekstreeks nodig +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes tekst (limiet {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output meer dan {MAX_INPUT_TEXT_TOTAL} bytes tekst in de hele uitvoer +@msg unknown key '{k}' onbekende sleutel '{k}' +@msg must be a list of 6 numbers moet een lijst van 6 getallen zijn +@msg a number is out of range (limit ±{MAX_COORD}) een getal valt buiten het bereik (limiet ±{MAX_COORD}) +@msg flattens the object to a line or a point drukt het object plat tot een lijn of een punt +@msg an object flattened to a line or a point can't be placed again een object dat tot een lijn of een punt is platgedrukt, kan niet opnieuw worden geplaatst +@msg must be a number from 0 to 1 moet een getal van 0 tot 1 zijn +@msg must be the name of a symbol moet de naam van een symbool zijn +@msg '{shown}' is not a symbol in this document '{shown}' is geen symbool in dit document +@msg a run must be {{"text", "style", "inline"?}} een tekstreeks moet {{"text", "style", "inline"?}} zijn +@msg `text` holds the character of an inline graphic `text` bevat het teken van een inline afbeelding +@msg inline graphics can't be added, removed, reordered or changed inline afbeeldingen kunnen niet worden toegevoegd, verwijderd, anders geordend of gewijzigd +@msg the characters of threaded type can't be changed de tekens van gekoppelde tekst kunnen niet worden gewijzigd +@msg the characters of type with ruby can't be changed de tekens van tekst met ruby kunnen niet worden gewijzigd +@msg expected {count} paragraph styles, one per paragraph {count} alineastijlen verwacht, één per alinea +@msg the document has no Kinsoku set named '{shown}' het document heeft geen Kinsoku-set met de naam '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters moet uit 1-{MAX_FAMILY} afdrukbare tekens bestaan @msg memory budget (object {_1} needs {size} bytes of input, {left} left) geheugenbudget (object {_1} heeft {size} bytes invoer nodig, {left} over) @msg object budget (more than {MAX_OBJECTS} read-only objects) objectbudget (meer dan {MAX_OBJECTS} alleen-lezen objecten) @msg instruction budget instructiebudget diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..0ae06b14fe 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7340,6 +7340,34 @@ axis Y Axis Oś Y @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` +@msg only a filter declares `writes` tylko filtr deklaruje `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance +@msg `writes` lists `{shown}` twice `writes` wymienia `{shown}` dwa razy +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` wymienia `{shown}`, którego nie wymienia `inputs` +@msg `writes` needs `api` {WRITES_API} or later `writes` wymaga `api` {WRITES_API} lub nowszego +@msg `writes` needs the permission `doc.write` `writes` wymaga uprawnienia `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} nie jest tekstem, obrazem ani wystąpieniem symbolu +@msg the text of type given as `truncated` can't be changed nie można zmienić tekstu obiektu tekstowego przekazanego jako `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries musi być listą co najwyżej {MAX_INPUT_RUNS} pozycji +@msg type needs at least one run tekst potrzebuje co najmniej jednego fragmentu +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtów tekstu (limit {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output ponad {MAX_INPUT_TEXT_TOTAL} bajtów tekstu w całym wyniku +@msg unknown key '{k}' nieznany klucz '{k}' +@msg must be a list of 6 numbers musi być listą 6 liczb +@msg a number is out of range (limit ±{MAX_COORD}) liczba spoza zakresu (limit ±{MAX_COORD}) +@msg flattens the object to a line or a point spłaszcza obiekt do linii lub punktu +@msg an object flattened to a line or a point can't be placed again obiektu spłaszczonego do linii lub punktu nie można ponownie umieścić +@msg must be a number from 0 to 1 musi być liczbą od 0 do 1 +@msg must be the name of a symbol musi być nazwą symbolu +@msg '{shown}' is not a symbol in this document '{shown}' nie jest symbolem w tym dokumencie +@msg a run must be {{"text", "style", "inline"?}} fragment musi mieć postać {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` zawiera znak grafiki w wierszu +@msg inline graphics can't be added, removed, reordered or changed grafik w wierszu nie można dodawać, usuwać, zmieniać ich kolejności ani modyfikować +@msg the characters of threaded type can't be changed nie można zmienić znaków tekstu wątkowego +@msg the characters of type with ruby can't be changed nie można zmienić znaków tekstu z ruby +@msg expected {count} paragraph styles, one per paragraph oczekiwano {count} stylów akapitowych, po jednym na akapit +@msg the document has no Kinsoku set named '{shown}' dokument nie ma zestawu kinsoku o nazwie '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters musi mieć 1-{MAX_FAMILY} drukowalnych znaków @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budżet pamięci (obiekt {_1} wymaga {size} bajtów danych wejściowych, pozostało {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) budżet obiektów (ponad {MAX_OBJECTS} obiektów tylko do odczytu) @msg instruction budget budżet instrukcji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..9ea5a38f63 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7384,6 +7384,34 @@ axis Y Axis Eixo Y @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` +@msg only a filter declares `writes` somente um filtro declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance +@msg `writes` lists `{shown}` twice `writes` lista `{shown}` duas vezes +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` lista `{shown}`, que `inputs` não lista +@msg `writes` needs `api` {WRITES_API} or later `writes` exige `api` {WRITES_API} ou posterior +@msg `writes` needs the permission `doc.write` `writes` exige a permissão `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} não é texto, nem uma imagem, nem uma instância de símbolo +@msg the text of type given as `truncated` can't be changed o texto de um objeto de texto fornecido como `truncated` não pode ser alterado +@msg must be a list of at most {MAX_INPUT_RUNS} entries deve ser uma lista de no máximo {MAX_INPUT_RUNS} entradas +@msg type needs at least one run o texto precisa de pelo menos um trecho +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (limite {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mais de {MAX_INPUT_TEXT_TOTAL} bytes de texto em toda a saída +@msg unknown key '{k}' chave desconhecida '{k}' +@msg must be a list of 6 numbers deve ser uma lista de 6 números +@msg a number is out of range (limit ±{MAX_COORD}) um número está fora do intervalo (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point achata o objeto em uma linha ou um ponto +@msg an object flattened to a line or a point can't be placed again um objeto achatado em uma linha ou um ponto não pode ser posicionado de novo +@msg must be a number from 0 to 1 deve ser um número de 0 a 1 +@msg must be the name of a symbol deve ser o nome de um símbolo +@msg '{shown}' is not a symbol in this document '{shown}' não é um símbolo deste documento +@msg a run must be {{"text", "style", "inline"?}} um trecho deve ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contém o caractere de um gráfico em linha +@msg inline graphics can't be added, removed, reordered or changed gráficos em linha não podem ser adicionados, removidos, reordenados nem alterados +@msg the characters of threaded type can't be changed os caracteres de texto encadeado não podem ser alterados +@msg the characters of type with ruby can't be changed os caracteres de texto com ruby não podem ser alterados +@msg expected {count} paragraph styles, one per paragraph eram esperados {count} estilos de parágrafo, um por parágrafo +@msg the document has no Kinsoku set named '{shown}' o documento não tem um conjunto Kinsoku chamado '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters deve ter 1-{MAX_FAMILY} caracteres imprimíveis @msg memory budget (object {_1} needs {size} bytes of input, {left} left) orçamento de memória (o objeto {_1} precisa de {size} bytes de entrada, restam {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) orçamento de objetos (mais de {MAX_OBJECTS} objetos somente leitura) @msg instruction budget orçamento de instruções diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..2eece19466 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7107,6 +7107,34 @@ axis Y Axis Ось Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` +@msg only a filter declares `writes` `writes` может объявлять только фильтр +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance в `writes` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance +@msg `writes` lists `{shown}` twice в `writes` `{shown}` указано дважды +@msg `writes` lists `{shown}`, which `inputs` doesn't list в `writes` указано `{shown}`, которого нет в `inputs` +@msg `writes` needs `api` {WRITES_API} or later для `writes` нужен `api` {WRITES_API} или выше +@msg `writes` needs the permission `doc.write` для `writes` нужно разрешение `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} не является ни текстом, ни изображением, ни экземпляром символа +@msg the text of type given as `truncated` can't be changed текст текстового объекта, переданного как `truncated`, изменить нельзя +@msg must be a list of at most {MAX_INPUT_RUNS} entries должно быть списком не более чем из {MAX_INPUT_RUNS} элементов +@msg type needs at least one run у текста должен быть хотя бы один фрагмент +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байт текста (предел {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output более {MAX_INPUT_TEXT_TOTAL} байт текста во всём выводе +@msg unknown key '{k}' неизвестный ключ '{k}' +@msg must be a list of 6 numbers должно быть списком из 6 чисел +@msg a number is out of range (limit ±{MAX_COORD}) число вне диапазона (предел ±{MAX_COORD}) +@msg flattens the object to a line or a point сплющивает объект в линию или точку +@msg an object flattened to a line or a point can't be placed again объект, сплющенный в линию или точку, нельзя разместить заново +@msg must be a number from 0 to 1 должно быть числом от 0 до 1 +@msg must be the name of a symbol должно быть именем символа +@msg '{shown}' is not a symbol in this document '{shown}' не является символом этого документа +@msg a run must be {{"text", "style", "inline"?}} фрагмент должен иметь вид {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` содержит символ встроенной в строку графики +@msg inline graphics can't be added, removed, reordered or changed встроенную в строку графику нельзя добавлять, удалять, переупорядочивать или изменять +@msg the characters of threaded type can't be changed знаки связанного текста изменить нельзя +@msg the characters of type with ruby can't be changed знаки текста с руби изменить нельзя +@msg expected {count} paragraph styles, one per paragraph ожидалось стилей абзацев: {count}, по одному на абзац +@msg the document has no Kinsoku set named '{shown}' в документе нет набора kinsoku с именем '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters должно содержать 1-{MAX_FAMILY} печатаемых символов @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет памяти (объекту {_1} нужно {size} байт входных данных, осталось {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет объектов (более {MAX_OBJECTS} объектов только для чтения) @msg instruction budget бюджет инструкций diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..bdf7d14ed1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7497,6 +7497,34 @@ axis Y Axis Y-axel @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` +@msg only a filter declares `writes` bara ett filter anger `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance +@msg `writes` lists `{shown}` twice `writes` anger `{shown}` två gånger +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` anger `{shown}`, som `inputs` inte anger +@msg `writes` needs `api` {WRITES_API} or later `writes` kräver `api` {WRITES_API} eller senare +@msg `writes` needs the permission `doc.write` `writes` kräver behörigheten `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} är varken text, en bild eller en symbolinstans +@msg the text of type given as `truncated` can't be changed texten i ett textobjekt som getts som `truncated` kan inte ändras +@msg must be a list of at most {MAX_INPUT_RUNS} entries måste vara en lista med högst {MAX_INPUT_RUNS} poster +@msg type needs at least one run text behöver minst ett textavsnitt +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte text (gräns {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mer än {MAX_INPUT_TEXT_TOTAL} byte text i hela utdatan +@msg unknown key '{k}' okänd nyckel '{k}' +@msg must be a list of 6 numbers måste vara en lista med 6 tal +@msg a number is out of range (limit ±{MAX_COORD}) ett tal ligger utanför intervallet (gräns ±{MAX_COORD}) +@msg flattens the object to a line or a point plattar till objektet till en linje eller en punkt +@msg an object flattened to a line or a point can't be placed again ett objekt som plattats till en linje eller en punkt kan inte placeras igen +@msg must be a number from 0 to 1 måste vara ett tal från 0 till 1 +@msg must be the name of a symbol måste vara namnet på en symbol +@msg '{shown}' is not a symbol in this document '{shown}' är ingen symbol i det här dokumentet +@msg a run must be {{"text", "style", "inline"?}} ett textavsnitt måste vara {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` innehåller tecknet för en grafik i texten +@msg inline graphics can't be added, removed, reordered or changed grafik i texten kan inte läggas till, tas bort, ordnas om eller ändras +@msg the characters of threaded type can't be changed tecknen i länkad text kan inte ändras +@msg the characters of type with ruby can't be changed tecknen i text med ruby kan inte ändras +@msg expected {count} paragraph styles, one per paragraph {count} styckestilar förväntades, en per stycke +@msg the document has no Kinsoku set named '{shown}' dokumentet har ingen Kinsoku-uppsättning med namnet '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters måste vara 1-{MAX_FAMILY} utskrivbara tecken @msg memory budget (object {_1} needs {size} bytes of input, {left} left) minnesbudget (objekt {_1} behöver {size} byte indata, {left} återstår) @msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (fler än {MAX_OBJECTS} skrivskyddade objekt) @msg the plug-in's grant can't be removed from the plug-in store pluginets behörighet kan inte tas bort ur pluginlagret diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..1314fa61b0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7557,6 +7557,34 @@ axis Y Axis Y ekseni @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir +@msg only a filter declares `writes` `writes` yalnızca bir filtrede bildirilebilir +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın +@msg `writes` lists `{shown}` twice `writes` `{shown}` değerini iki kez listeliyor +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` `{shown}` değerini listeliyor, ancak `inputs` listelemiyor +@msg `writes` needs `api` {WRITES_API} or later `writes` için `api` {WRITES_API} veya üstü gerekir +@msg `writes` needs the permission `doc.write` `writes` için `doc.write` izni gerekir +@msg {_1} is not type, an image or a symbol instance {_1} metin, görüntü veya sembol örneği değil +@msg the text of type given as `truncated` can't be changed `truncated` olarak verilen metin nesnesinin metni değiştirilemez +@msg must be a list of at most {MAX_INPUT_RUNS} entries en fazla {MAX_INPUT_RUNS} girişli bir liste olmalıdır +@msg type needs at least one run metnin en az bir parçası olmalıdır +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bayt metin (sınır {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output çıktının tamamında {MAX_INPUT_TEXT_TOTAL} bayttan fazla metin +@msg unknown key '{k}' bilinmeyen anahtar '{k}' +@msg must be a list of 6 numbers 6 sayılık bir liste olmalıdır +@msg a number is out of range (limit ±{MAX_COORD}) bir sayı aralık dışında (sınır ±{MAX_COORD}) +@msg flattens the object to a line or a point nesneyi bir çizgiye veya noktaya yassılaştırıyor +@msg an object flattened to a line or a point can't be placed again bir çizgiye veya noktaya yassılaşmış nesne yeniden yerleştirilemez +@msg must be a number from 0 to 1 0 ile 1 arasında bir sayı olmalıdır +@msg must be the name of a symbol bir sembolün adı olmalıdır +@msg '{shown}' is not a symbol in this document '{shown}' bu belgede bir sembol değil +@msg a run must be {{"text", "style", "inline"?}} bir parça {{"text", "style", "inline"?}} biçiminde olmalıdır +@msg `text` holds the character of an inline graphic `text` satır içi bir grafiğin karakterini içeriyor +@msg inline graphics can't be added, removed, reordered or changed satır içi grafikler eklenemez, kaldırılamaz, yeniden sıralanamaz veya değiştirilemez +@msg the characters of threaded type can't be changed zincirli metnin karakterleri değiştirilemez +@msg the characters of type with ruby can't be changed ruby içeren metnin karakterleri değiştirilemez +@msg expected {count} paragraph styles, one per paragraph her paragraf için bir tane olmak üzere {count} paragraf stili bekleniyordu +@msg the document has no Kinsoku set named '{shown}' belgede '{shown}' adlı Kinsoku seti yok +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} yazdırılabilir karakter olmalıdır @msg memory budget (object {_1} needs {size} bytes of input, {left} left) bellek bütçesi (nesne {_1} için {size} bayt girdi gerekiyor, {left} kaldı) @msg object budget (more than {MAX_OBJECTS} read-only objects) nesne bütçesi ({MAX_OBJECTS} adetten fazla salt okunur nesne) @msg instruction budget talimat bütçesi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..b4db911a41 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7089,6 +7089,34 @@ axis Y Axis Вісь Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` +@msg only a filter declares `writes` `writes` може оголошувати лише фільтр +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance в `writes` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance +@msg `writes` lists `{shown}` twice в `writes` `{shown}` указано двічі +@msg `writes` lists `{shown}`, which `inputs` doesn't list в `writes` указано `{shown}`, якого немає в `inputs` +@msg `writes` needs `api` {WRITES_API} or later для `writes` потрібен `api` {WRITES_API} або новіший +@msg `writes` needs the permission `doc.write` для `writes` потрібен дозвіл `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} не є ні текстом, ні зображенням, ні екземпляром символу +@msg the text of type given as `truncated` can't be changed текст текстового об’єкта, переданого як `truncated`, змінити не можна +@msg must be a list of at most {MAX_INPUT_RUNS} entries має бути списком щонайбільше з {MAX_INPUT_RUNS} елементів +@msg type needs at least one run текст повинен мати щонайменше один фрагмент +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байтів тексту (межа {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output понад {MAX_INPUT_TEXT_TOTAL} байтів тексту в усьому виводі +@msg unknown key '{k}' невідомий ключ '{k}' +@msg must be a list of 6 numbers має бути списком із 6 чисел +@msg a number is out of range (limit ±{MAX_COORD}) число поза діапазоном (межа ±{MAX_COORD}) +@msg flattens the object to a line or a point сплющує об’єкт у лінію чи точку +@msg an object flattened to a line or a point can't be placed again об’єкт, сплющений у лінію чи точку, не можна розмістити знову +@msg must be a number from 0 to 1 має бути числом від 0 до 1 +@msg must be the name of a symbol має бути назвою символу +@msg '{shown}' is not a symbol in this document '{shown}' не є символом цього документа +@msg a run must be {{"text", "style", "inline"?}} фрагмент має мати вигляд {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` містить знак вбудованої в рядок графіки +@msg inline graphics can't be added, removed, reordered or changed вбудовану в рядок графіку не можна додавати, вилучати, переставляти чи змінювати +@msg the characters of threaded type can't be changed знаки пов’язаного тексту змінити не можна +@msg the characters of type with ruby can't be changed знаки тексту з рубі змінити не можна +@msg expected {count} paragraph styles, one per paragraph очікувалося стилів абзаців: {count}, по одному на абзац +@msg the document has no Kinsoku set named '{shown}' у документі немає набору kinsoku з назвою '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters має містити 1-{MAX_FAMILY} друкованих символів @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет пам’яті (об’єкту {_1} потрібно {size} байтів вхідних даних, залишилося {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) бюджет об’єктів (понад {MAX_OBJECTS} об’єктів лише для читання) @msg instruction budget бюджет інструкцій diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..440b373486 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7136,6 +7136,34 @@ axis Y Axis Trục Y @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` +@msg only a filter declares `writes` chỉ bộ lọc mới khai báo `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance +@msg `writes` lists `{shown}` twice `writes` liệt kê `{shown}` hai lần +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` liệt kê `{shown}`, nhưng `inputs` không liệt kê +@msg `writes` needs `api` {WRITES_API} or later `writes` cần `api` {WRITES_API} trở lên +@msg `writes` needs the permission `doc.write` `writes` cần quyền `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} không phải là văn bản, hình ảnh hay thực thể ký hiệu +@msg the text of type given as `truncated` can't be changed không thể thay đổi văn bản của đối tượng văn bản được đưa vào dưới dạng `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries phải là danh sách có tối đa {MAX_INPUT_RUNS} mục +@msg type needs at least one run văn bản cần ít nhất một đoạn chạy +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte văn bản (giới hạn {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output hơn {MAX_INPUT_TEXT_TOTAL} byte văn bản trên toàn bộ đầu ra +@msg unknown key '{k}' khóa không xác định '{k}' +@msg must be a list of 6 numbers phải là danh sách gồm 6 số +@msg a number is out of range (limit ±{MAX_COORD}) một số nằm ngoài phạm vi (giới hạn ±{MAX_COORD}) +@msg flattens the object to a line or a point làm dẹt đối tượng thành một đường hoặc một điểm +@msg an object flattened to a line or a point can't be placed again không thể đặt lại một đối tượng đã bị dẹt thành đường hoặc điểm +@msg must be a number from 0 to 1 phải là một số từ 0 đến 1 +@msg must be the name of a symbol phải là tên của một ký hiệu +@msg '{shown}' is not a symbol in this document '{shown}' không phải là ký hiệu trong tài liệu này +@msg a run must be {{"text", "style", "inline"?}} một đoạn chạy phải có dạng {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` chứa ký tự của một đồ họa nội dòng +@msg inline graphics can't be added, removed, reordered or changed không thể thêm, xóa, sắp xếp lại hoặc thay đổi đồ họa nội dòng +@msg the characters of threaded type can't be changed không thể thay đổi ký tự của văn bản chuỗi +@msg the characters of type with ruby can't be changed không thể thay đổi ký tự của văn bản có ruby +@msg expected {count} paragraph styles, one per paragraph cần {count} kiểu đoạn văn, mỗi đoạn một kiểu +@msg the document has no Kinsoku set named '{shown}' tài liệu không có bộ Kinsoku nào tên '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters phải có 1-{MAX_FAMILY} ký tự in được @msg memory budget (object {_1} needs {size} bytes of input, {left} left) ngân sách bộ nhớ (đối tượng {_1} cần {size} byte đầu vào, còn lại {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) ngân sách đối tượng (hơn {MAX_OBJECTS} đối tượng chỉ đọc) @msg instruction budget ngân sách lệnh diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..ba4c8c3cfa 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7317,6 +7317,34 @@ axis Y Axis Y 轴 @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` +@msg only a filter declares `writes` 只有滤镜才能声明 `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance +@msg `writes` lists `{shown}` twice `writes` 列出了两次 `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` 列出了 `{shown}`,但 `inputs` 未列出它 +@msg `writes` needs `api` {WRITES_API} or later `writes` 需要 `api` {WRITES_API} 或更高 +@msg `writes` needs the permission `doc.write` `writes` 需要权限 `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} 不是文字、图像或符号实例 +@msg the text of type given as `truncated` can't be changed 作为 `truncated` 给出的文字对象的文本不能更改 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 必须是最多 {MAX_INPUT_RUNS} 个条目的列表 +@msg type needs at least one run 文字至少需要一个文本段 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文本 {bytes} 字节(上限 {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整个输出中的文本超过 {MAX_INPUT_TEXT_TOTAL} 字节 +@msg unknown key '{k}' 未知键 '{k}' +@msg must be a list of 6 numbers 必须是 6 个数字的列表 +@msg a number is out of range (limit ±{MAX_COORD}) 有数字超出范围(上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point 会把对象压扁成一条线或一个点 +@msg an object flattened to a line or a point can't be placed again 已压扁成线或点的对象无法重新放置 +@msg must be a number from 0 to 1 必须是 0 到 1 之间的数字 +@msg must be the name of a symbol 必须是符号的名称 +@msg '{shown}' is not a symbol in this document '{shown}' 不是此文档中的符号 +@msg a run must be {{"text", "style", "inline"?}} 文本段必须是 {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` 含有随文图形的字符 +@msg inline graphics can't be added, removed, reordered or changed 随文图形不能添加、删除、重新排序或更改 +@msg the characters of threaded type can't be changed 串接文本的字符不能更改 +@msg the characters of type with ruby can't be changed 带注音的文字的字符不能更改 +@msg expected {count} paragraph styles, one per paragraph 应有 {count} 个段落样式,每个段落一个 +@msg the document has no Kinsoku set named '{shown}' 文档中没有名为 '{shown}' 的 Kinsoku 集 +@msg must be 1-{MAX_FAMILY} printable characters 必须是 1-{MAX_FAMILY} 个可打印字符 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 内存预算(对象 {_1} 需要 {size} 字节的输入,剩余 {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) 对象预算(超过 {MAX_OBJECTS} 个只读对象) @msg instruction budget 指令预算 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..e9654bb319 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7138,6 +7138,34 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` +@msg only a filter declares `writes` 只有濾鏡才能宣告 `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance +@msg `writes` lists `{shown}` twice `writes` 列出了兩次 `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` 列出了 `{shown}`,但 `inputs` 未列出它 +@msg `writes` needs `api` {WRITES_API} or later `writes` 需要 `api` {WRITES_API} 或更高 +@msg `writes` needs the permission `doc.write` `writes` 需要權限 `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} 不是文字、影像或符號範例 +@msg the text of type given as `truncated` can't be changed 以 `truncated` 提供的文字物件,其文字無法變更 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 必須是最多 {MAX_INPUT_RUNS} 個項目的清單 +@msg type needs at least one run 文字至少需要一個文字段 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文字 {bytes} 位元組(上限 {MAX_INPUT_TEXT}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整個輸出中的文字超過 {MAX_INPUT_TEXT_TOTAL} 位元組 +@msg unknown key '{k}' 未知的鍵 '{k}' +@msg must be a list of 6 numbers 必須是 6 個數字的清單 +@msg a number is out of range (limit ±{MAX_COORD}) 有數字超出範圍(上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point 會把物件壓扁成一條線或一個點 +@msg an object flattened to a line or a point can't be placed again 已壓扁成線或點的物件無法重新放置 +@msg must be a number from 0 to 1 必須是 0 到 1 之間的數字 +@msg must be the name of a symbol 必須是符號的名稱 +@msg '{shown}' is not a symbol in this document '{shown}' 不是此文件中的符號 +@msg a run must be {{"text", "style", "inline"?}} 文字段必須是 {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` 含有行內圖形的字元 +@msg inline graphics can't be added, removed, reordered or changed 行內圖形無法新增、移除、重新排序或變更 +@msg the characters of threaded type can't be changed 串連文字的字元無法變更 +@msg the characters of type with ruby can't be changed 含注音的文字,其字元無法變更 +@msg expected {count} paragraph styles, one per paragraph 應有 {count} 個段落樣式,每個段落一個 +@msg the document has no Kinsoku set named '{shown}' 文件中沒有名為 '{shown}' 的 Kinsoku 集 +@msg must be 1-{MAX_FAMILY} printable characters 必須是 1-{MAX_FAMILY} 個可列印字元 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 記憶體預算(物件 {_1} 需要 {size} 位元組的輸入,剩餘 {left}) @msg object budget (more than {MAX_OBJECTS} read-only objects) 物件預算(超過 {MAX_OBJECTS} 個唯讀物件) @msg instruction budget 指令預算 From 989aa08f16937a4ca0b3345dd0628db7d0185179 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:58:30 -0800 Subject: [PATCH 031/107] Plug-ins: a failed removal keeps settings, and the key store reconnects - plugin.remove deletes the stored module of a plug-in that isn't installed while its settings and cache are still moved aside, so a module that can't be deleted leaves them in place for the next try. - plugin.remove of an invalid id no longer raises the grants generation. - The size check before a signed grants write uses the generation the file is written at, so a file that fits the 1 MiB limit is kept. - The system key store connection is dropped when the key store can't be reached through it or fails, and the next call connects again; a missing entry keeps the connection. --- crates/engine/src/cmd/plugin.rs | 34 ++++++++++---- crates/engine/src/store.rs | 9 ++-- crates/engine/src/store/grant_keys.rs | 67 ++++++++++++++++++++++----- crates/engine/src/tests/plugins.rs | 47 +++++++++++++++++-- 4 files changed, 129 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index c2395534a3..8b994aceda 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1218,19 +1218,36 @@ fn remove(s: &mut Session, p: &Value) -> Result { let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); + // A module stored for an id that isn't installed (one no grant covers is skipped at startup) + // counts as removed once its file is gone. + let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id); + let module_left = std::cell::Cell::new(false); + let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default()); // Installed again, it asks again. A grant that can't be removed may still approve the module, and // so may a grants file that can't be opened or read, or a signed copy of the file put back when // the generation couldn't be raised (the key store can't be reached). Without a plug-in folder - // nothing keeps a grant. - let forget = || s.store_grant_in(&turn, id, None) || s.plugin_dir.is_none(); - // Its settings and cache are moved aside and its grant removed before anything is deleted: when - // either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove` - // tries again. + // nothing keeps a grant. The stored module of an id that isn't installed is deleted next, while + // its settings and cache can still be moved back. + let forget = || { + if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() { + return false; + } + let deleted = !module || s.unstore_plugin(&turn, id); + module_left.set(!deleted); + deleted + }; + // Its settings and cache are moved aside, its grant removed and its stored module deleted before + // anything else is deleted: when one of them can't be done, the settings and cache are moved back, + // the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id + // names no grant and no module. let failed = if installed || stored { s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string()) - } else { + } else if vectorcraft_plugins::manifest::valid_id(id) { (!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string()) + } else { + None }; + let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e }); if let Some(e) = failed { if installed { s.attach_plugin_storage(&turn, id); @@ -1238,11 +1255,8 @@ fn remove(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other(e)); } registry::revoke(id); - // A module stored for an id that isn't installed (one no grant covers is skipped at startup) - // counts as removed once its file is gone. - let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id); if !s.unstore_plugin(&turn, id) && module { - return Err(EngineError::Other(format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default()))); + return Err(EngineError::Other(cant_delete())); } if !stored && !module && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 57e693ef43..aba70c4fb3 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -1652,10 +1652,13 @@ fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool return false; } }; - // A file too large to keep is found before the raise, at the longest generation and a MAC of its - // length, so the file in place keeps its grants when nothing can be written. + // A file too large to keep is found before the raise, at the generation it would be written at + // (three past the kept one, [`raise_generation`]) and a MAC of its length, so the file in place + // keeps its grants when nothing can be written. When the kept generation can't be read, the raise + // fails too. + let expected = grant_keys::current_generation(&folder).ok().and_then(|kept| kept.checked_add(3)).unwrap_or(u64::MAX); let mut file = - SignedGrants { version: GRANTS_VERSION, generation: Some(u64::MAX), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) }; + SignedGrants { version: GRANTS_VERSION, generation: Some(expected), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) }; if grants_bytes(serde_json::to_value(&file).ok()).is_none() { log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); return false; diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs index 034d44d582..151cd4055d 100644 --- a/crates/engine/src/store/grant_keys.rs +++ b/crates/engine/src/store/grant_keys.rs @@ -269,7 +269,9 @@ struct OsGrantKeys { /// same time keep one. making: Mutex<()>, /// The connection to the system's key store, once one is made. A failed connection is not - /// kept: the next call tries again, so a key store that starts after VectorCraft is used. + /// kept, and a kept one is dropped when the key store can't be reached through it or fails + /// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after + /// VectorCraft, or restarts, is used. store: Mutex>>, /// How a connection is made ([`connect`]). connect: fn() -> Result, keyring_core::Error>, @@ -296,8 +298,18 @@ impl OsGrantKeys { Ok(store.insert((self.connect)().map_err(store_error)?).clone()) } + /// What the key store error `e` says ([`store_error`]). When the key store can't be reached or + /// fails, the connection is dropped first, so the next call makes a new one: the Secret Service + /// loses the session of a connection when it restarts. An entry that isn't there keeps it. + fn failed(&self, e: keyring_core::Error) -> KeyStoreError { + if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) { + *self.store.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + store_error(e) + } + fn entry(&self, account: &str) -> Result { - self.store()?.build(Self::SERVICE, account, None).map_err(store_error) + self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e)) } fn key_entry(&self) -> Result { @@ -305,7 +317,7 @@ impl OsGrantKeys { } /// The key the system's key store keeps, read from it. - fn stored(entry: &keyring_core::Entry) -> Result, KeyStoreError> { + fn stored(&self, entry: &keyring_core::Entry) -> Result, KeyStoreError> { match entry.get_secret() { // A secret that is not 64 hexadecimal digits is not a key this version made: there is none. Ok(secret) => Ok(std::str::from_utf8(&secret) @@ -314,7 +326,7 @@ impl OsGrantKeys { .and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok()) .map(GrantKey)), Err(keyring_core::Error::NoEntry) => Ok(None), - Err(e) => Err(store_error(e)), + Err(e) => Err(self.failed(e)), } } @@ -361,12 +373,12 @@ fn to_hex(bytes: &[u8]) -> String { impl GrantKeyStore for OsGrantKeys { /// Read from the key store each time, so that a key removed or replaced there is not used. fn key(&self) -> Result, KeyStoreError> { - Self::stored(&self.key_entry()?) + self.stored(&self.key_entry()?) } fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); - self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(store_error) + self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e)) } /// Reads the key store again and makes the key only while holding [`creation_lock`], so that @@ -374,15 +386,15 @@ impl GrantKeyStore for OsGrantKeys { fn create_key(&self) -> Result { let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); let entry = self.key_entry()?; - if let Some(key) = Self::stored(&entry)? { + if let Some(key) = self.stored(&entry)? { return Ok(key); } let _turn = creation_lock()?; - match Self::stored(&entry)? { + match self.stored(&entry)? { Some(key) => Ok(key), None => { - entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(store_error)?; - Self::stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?; + self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) } } } @@ -399,12 +411,12 @@ impl GrantKeyStore for OsGrantKeys { .map(|bytes| Some(u64::from_be_bytes(bytes))) .ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())), Err(keyring_core::Error::NoEntry) => Ok(None), - Err(e) => Err(store_error(e)), + Err(e) => Err(self.failed(e)), } } fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { - self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(store_error) + self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e)) } } @@ -465,6 +477,37 @@ mod tests { Ok(store) } + /// Connections asked for from [`restarting`]. + static RESTARTS: AtomicUsize = AtomicUsize::new(0); + /// The store [`restarting`] connects to first. + static BEFORE: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + /// The store [`restarting`] connects to on every later try. + static AFTER: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that restarts after the first connection: later connections reach another store. + fn restarting() -> Result, keyring_core::Error> { + let store: Arc = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() }; + Ok(store) + } + + /// A connection that the key store can't be reached through is dropped, and the next call + /// connects again; an entry that isn't there keeps the connection. + #[test] + fn the_system_key_store_reconnects_after_it_restarts() { + let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() }; + assert_eq!(keys.key().unwrap(), None, "no key is kept yet"); + keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap(); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection"); + + AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap(); + let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap(); + let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap(); + cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into())); + assert!(keys.key().is_err(), "the connection fails"); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection"); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 2); + } + /// The secret `MOCK` keeps for `account`, as it is kept. fn kept(account: &str) -> Vec { MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap() diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index e0ebeab953..00a5360dd0 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4514,7 +4514,8 @@ fn a_removal_the_key_store_cannot_make_last_fails() { /// A stored plug-in that didn't load, because the grants file of an older version doesn't count, and /// that keeps no settings or cache, is removed with its module and its entry, and the removal -/// reports it removed. A removal whose stored module can't be deleted fails. +/// reports it removed. A removal whose stored module can't be deleted fails and keeps its settings. +/// Removing an invalid id leaves the kept generation as it is. #[test] fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() { use vectorcraft_plugins::permissions::sha256_hex; @@ -4536,13 +4537,29 @@ fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() { assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "a second removal finds nothing"); // A stored module that can't be deleted (here a folder in its place), of a plug-in that keeps - // settings, fails the removal. + // settings, fails the removal, and the settings stay for the next try. std::fs::create_dir_all(module.join("held")).unwrap(); - std::fs::create_dir_all(crate::store::plugin_data_dir(&folder.0, id)).unwrap(); + let data_dir = crate::store::plugin_data_dir(&folder.0, id); + std::fs::create_dir_all(&data_dir).unwrap(); + let setting = data_dir.join("settings.json"); + std::fs::write(&setting, b"{}").unwrap(); let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); assert!(refused.contains("can't delete"), "{refused}"); assert!(module.exists()); + assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back"); std::fs::remove_dir_all(&module).unwrap(); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal deletes them"); + assert!(!data_dir.exists()); + + // An invalid id names no grant: its removal doesn't raise the generation. + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([3; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + for invalid in ["", "not an id"] { + assert!(s.execute("plugin.remove", &json!({"id": invalid})).is_err(), "{invalid:?} isn't found"); + assert_eq!(kept_generation(&keys, &folder.0), None, "{invalid:?}: the generation is left as it is"); + } + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err()); + assert_eq!(kept_generation(&keys, &folder.0), Some(2), "a valid id's removal still retires signed copies"); } /// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same @@ -4935,6 +4952,30 @@ fn a_revoke_after_a_write_whose_generation_wasnt_kept_keeps_that_write_granting_ } } +/// A grant whose signed file fits the 1 MiB limit at the generation it is written at is kept, also +/// when the file would not fit with a longer generation number. +#[test] +fn a_grants_file_that_fits_at_its_generation_is_written() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-grants-fit"); + let id = "test.engine.permissions.grantsfit"; + let grant = doc_read_grant(id, &sha256_hex(b"module")); + let grants = folder.0.join("grants.json"); + // The file as it is written: compact, since pretty-printed it is larger than the limit. + let size = |pad: &str| serde_json::to_vec(&json!({"version": 1, "generation": 3, "grants": [grant, pad], "mac": "0".repeat(64)})).unwrap().len(); + let pad = "a".repeat((1 << 20) - size("")); + assert_eq!(size(&pad), 1 << 20); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([pad]).to_string())).unwrap(); + assert!(s.store_grant(id, Some(grant)), "the grant is kept"); + let written = std::fs::read(&grants).unwrap(); + assert_eq!((written.len(), generation_of(&written)), (1 << 20, Some(3))); + assert_eq!(kept_generation(&keys, &folder.0), Some(3)); +} + /// A grants file edited to carry the largest generations doesn't stop a revoke and doesn't move the /// generation the key store keeps near the limit, so later grants are still kept: the generation /// comes from the key store alone. From e4768c6eed0ca0b0a20590e1c412d7fba43a8234 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:54:43 -0800 Subject: [PATCH 032/107] Clipboard: a failed copy stays replaced, and the menu's Paste into a field takes nothing Without a change count, a Copy or Cut whose formats could not be written was kept for as long as the clipboard held the same text as at the failure. When another app copied other text and later put the older text back, Paste took the copied art again. The record of the failed write is now dropped once a different change count, or different readable text, is seen on the clipboard. The Edit menu's Paste into a focused text field, after a failed Copy whose formats have no text, found no text and fell through to the canvas Paste, which pasted the copied art. The field now gets an empty paste and takes nothing. --- crates/ui-egui/src/menus/invoke.rs | 2 +- crates/ui-egui/src/sysclip.rs | 31 +++++++++++++-- crates/ui-egui/src/tests/sysclip.rs | 58 +++++++++++++++++++++++++++++ docs/mcp.md | 4 +- 4 files changed, 88 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7186f0707d..8bb9fcbe4e 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -112,7 +112,7 @@ pub(super) fn field_event(app: &mut VectorcraftApp, id: &str) -> Option egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }, "edit.copy" => egui::Event::Copy, "edit.cut" => egui::Event::Cut, - "edit.paste" | "edit.pasteWithoutFormatting" => egui::Event::Paste(app.written_clipboard_text()?), + "edit.paste" | "edit.pasteWithoutFormatting" => egui::Event::Paste(app.field_paste_text()?), _ => return None, }) } diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 6b8a019223..f841721c99 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -138,9 +138,20 @@ impl Publishing { } /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing - /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? - fn holds_unwritten(&self, cb: &mut (dyn SystemClipboard + 'static)) -> bool { - self.unwritten.as_ref().is_some_and(|(held, _)| Held::now(cb) == *held) + /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? A different change count, or + /// different text read from `cb`, shows a later copy: the record of the failed write is then + /// dropped, so the clipboard holding the older text again later does not bring it back. Text + /// that could not be read keeps the record. + fn holds_unwritten(&mut self, cb: &mut (dyn SystemClipboard + 'static)) -> bool { + let Some((held, _)) = &self.unwritten else { return false }; + let now = Held::now(cb); + if now == *held { + return true; + } + if now != Held::Text(None) { + self.unwritten = None; + } + false } } @@ -482,7 +493,7 @@ impl VectorcraftApp { (_, Some(cb)) => { // After a Copy or Cut whose formats could not be written, with nothing copied // since, what the clipboard still holds is older than the internal clipboard. - let publishing = &self.clipboard_publishing; + let publishing = &mut self.clipboard_publishing; if publishing.pending || publishing.holds_unwritten(cb.as_mut()) || cb.holds_ours() { return Ok(None); } @@ -559,6 +570,18 @@ impl VectorcraftApp { self.unwritten_copy().unwrap_or_else(|| self.system_clipboard_text()) } + /// The text a paste from the Edit menu gives a focused text field ([`Self::written_clipboard_text`]): + /// empty when the formats of a Copy or Cut could not be written and have no text, so the field + /// takes nothing and the art is not pasted onto the canvas. `None` when the system clipboard + /// holds no text. + pub(crate) fn field_paste_text(&mut self) -> Option { + background::wait_until(self, |app| !app.clipboard_publishing.pending); + match self.unwritten_copy() { + Some(text) => Some(text.unwrap_or_default()), + None => self.system_clipboard_text(), + } + } + /// The text on the system clipboard, if any. pub(crate) fn system_clipboard_text(&mut self) -> Option { match self.services.system_clipboard.as_mut() { diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index d857f5be93..412f8264ac 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -720,6 +720,64 @@ fn the_menus_paste_into_a_field_waits_for_the_formats() { background::wait_all(&mut app); } +/// The Edit menu's Paste into a text field after a Copy whose formats have no text (On Copy: +/// Include SVG Code off) and could not be written: the field takes nothing, not the text another +/// app left on the clipboard, and the copied art is not pasted onto the canvas. +#[test] +fn the_menus_paste_into_a_field_after_a_refused_textless_copy_takes_nothing() { + for uncounted in [false, true] { + let (mut app, board) = app(); + if uncounted { + without_change_count(&board); + } + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": false})); + let rect = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [rect]})); + copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]); + refuse_writes(&board, true); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + refuse_writes(&board, false); + let objects = count(&app); + let (ctx, id, mut field) = (egui::Context::default(), egui::Id::unique("field"), String::new()); + for paste in [false, true] { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + if paste { + menus::invoke_from_system_menu(&mut app, ui.ctx(), "edit.paste", json!({})); + } + ui.add(egui::TextEdit::singleline(&mut field).id(id)).request_focus(); + }); + out.textures_delta.clear(); + } + assert_eq!(field, "", "uncounted {uncounted}: the field takes nothing"); + assert_eq!(count(&app), objects, "uncounted {uncounted}: nothing is pasted onto the canvas"); + } +} + +/// Without a change count, a Copy whose formats could not be written stops being what Paste takes +/// once different text is seen on the clipboard: when another app later puts the older text back, +/// Paste takes that text, not the copied art. +#[test] +fn a_refused_copy_stays_replaced_when_the_older_text_comes_back() { + let (mut app, board) = app(); + without_change_count(&board); + let rect = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [rect]})); + copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]); + refuse_writes(&board, true); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + refuse_writes(&board, false); + + copy_elsewhere(&board, vec![(TEXT, b"New".to_vec())]); + assert_eq!(app.written_clipboard_text().as_deref(), Some("New")); + copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]); + assert_eq!(app.written_clipboard_text().as_deref(), Some("Old"), "a paste into text"); + run(&mut app, "edit.paste", json!({})); + let NodeKind::Text(t) = &pasted(&app)[0].kind else { panic!("the copied art, not the clipboard's text") }; + assert_eq!(t.plain_text(), "Old"); +} + /// A paste chord into type being edited, before the formats are written: the formats are written /// first, and the paste pastes their text whether the host read another app's text for it or found /// no text, also when the chord's key comes up a frame after they were written; with no text in diff --git a/docs/mcp.md b/docs/mcp.md index 0825fc6fd2..763241086f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9863,8 +9863,8 @@ or refused the write), every Paste takes the internal clipboard until another ap into a text field or type takes the copy's text, or nothing when the formats have no text. Windows and macOS notice that copy by the clipboard's change count. Linux and the BSDs notice it only when it changes the clipboard's text, so there Paste reads the system clipboard when it held only a picture, or nothing that could be read, at the failed -write. While a text field or the Type tool has the keyboard, the app waits for -them. Windows carries every format both ways and pastes a bitmap from PNG, else +write. Once a paste there has read the changed text, the older text coming back does not restore the copy. While a +text field or the Type tool has the keyboard, the app waits for them. Windows carries every format both ways and pastes a bitmap from PNG, else from the device-independent bitmap screenshots copy (`CF_DIBV5`, then `CF_DIB`; alpha kept, opaque when it is zero throughout, at most 32768 px a side); macOS and Linux carry one format (the text, else the PNG) and paste text and bitmaps (macOS the pasteboard's PNG, else TIFF, as screenshots copy them). A Paste from the menus or the keys decodes From 03c1c6c70f602c4ed6cac58c65eabe8e26c52bc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:09:03 -0800 Subject: [PATCH 033/107] Plug-ins: written type keeps one paragraph style per paragraph, and API level 2 filters may leave out an image's opacity - A read-only image entry may leave out `opacity`, which hosts before API level 3 don't give, so a level 2 filter that rebuilds an image entry from the fields it knows still matches. - A `text.paragraphs` list returned as it was given next to changed `text.runs` is checked against the new paragraphs: a count that no longer matches is refused instead of being dropped. - Written runs hold at most 4,096 paragraphs, the limit for runs and for the paragraphs a filter is given. - A fill or stroke in a written run's style with a key its `type` doesn't read (`tintt`) is refused with the `unknown key` error. - The font family limit counts the name as given, not the trimmed name. - The run styles of a type object are indexed once per object, not compared with every run's style. - Character styles loaded from another document are skipped when their tracking, kerning, rotation, miter limit, dashes, Small Caps or variable font axes are out of range, as `charStyle.new` checks them. - The plug-in command test's Size command adds a square, since an output that changes nothing records no undo step. Docs: docs/plugins.md, docs/mcp.md, plugin.run params text. --- crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/src/cmd/textstyles.rs | 10 ++++- crates/engine/src/cmd/textstyles/tests.rs | 12 ++++-- crates/engine/src/tests/plugins.rs | 6 ++- crates/plugins/src/objects.rs | 22 +++++++--- crates/plugins/src/objects/tests.rs | 36 +++++++++++++++- crates/plugins/src/objects/writes.rs | 52 ++++++++++++++++++++--- 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/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/tests/plugins.rs | 5 ++- docs/mcp.md | 8 ++-- docs/plugins.md | 25 +++++++---- 35 files changed, 168 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 7818ece63b..4d30ec597b 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1317,7 +1317,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. An output that changes nothing records no undo step. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given (an image may leave out opacity), or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs, 4,096 paragraphs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, fills and strokes with only the keys their type reads, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, also when given as they were next to changed runs, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. An output that changes nothing records no undo step. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", has_doc, run ), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 0bc0a34367..1d3c8f7d7b 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -1096,12 +1096,16 @@ fn unused(s: &mut Session, kind: Kind) -> Result { /// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in /// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { - const RANGED: [&str; 24] = [ + const RANGED: [&str; 32] = [ "size", "h_scale", "v_scale", "leading", + "tracking", + "kerning", + "kerningBefore", "baseline_shift", + "rotation", "akiLeft", "akiRight", "tsume", @@ -1113,6 +1117,10 @@ fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { "warichuGap", "warichuScale", "stroke_width", + "stroke_miter_limit", + "stroke_dash", + "small_caps", + "fontAxes", "left_indent", "right_indent", "first_line_indent", diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 3b0c872b09..c0a92a20e3 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -837,8 +837,8 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } -/// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is -/// out of the range `charStyle.new` takes is skipped. +/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or +/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped. #[test] fn loaded_styles_out_of_range_are_skipped() { let (mut s, _) = session_with_text("Title"); @@ -848,11 +848,17 @@ fn loaded_styles_out_of_range_are_skipped() { ("Shifted", json!({"baseline_shift": 5000.0})), ("Thick", json!({"stroke_width": -2.0})), ("Gapped", json!({"warichuGap": 500.0})), + ("Spun", json!({"rotation": 720.0})), + ("Tracked", json!({"tracking": 50000.0})), + ("Kerned", json!({"kerning": -5000.0})), + ("Before", json!({"kerningBefore": 50000.0})), + ("Mitered", json!({"stroke_miter_limit": 0.5})), ("Fine", json!({"size": 12.0, "h_scale": 50.0})), ]; let data = styles_file(&file, &[]); let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap(); - assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick", "Gapped"]})); + let skipped = ["Huge", "Flat", "Shifted", "Thick", "Gapped", "Spun", "Tracked", "Kerned", "Before", "Mitered"]; + assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": skipped})); assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]); } diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index dbb864b3b9..a63bfac584 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3945,12 +3945,14 @@ fn a_filter_that_writes_type_images_and_instances_is_one_undo_step() { let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); run(&mut s, "plugin.run", p(echo)); assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "an echo records no undo step"); - // Refused writes leave the document and the history as they were. + // Refused writes leave the document and the history as they were, also when a valid change + // comes before the refused one. let bad = "test.engine.writes.bad"; + let retyped = json!({"id": t.0, "text": {"runs": [{"text": "Hello again", "style": style}]}}); for (writes, output, says) in [ ( all, - json!({"objects": [{"id": r.0}, {"id": t.0}, {"id": image.0}, {"id": inst.0, "symbolId": "Nowhere"}]}), + json!({"objects": [{"id": r.0}, retyped, {"id": image.0}, {"id": inst.0, "symbolId": "Nowhere"}]}), format!("objects[3] (id {}).symbolId: 'Nowhere' is not a symbol in this document", inst.0), ), ( diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 3f58ef4573..6b5a2b80cc 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -913,20 +913,28 @@ fn output_id(o: &Value) -> Option { /// numbers compared by value. Otherwise the error names the first field that differs /// (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as /// [`crate::permissions::display_text`] shows a manifest string, since the entry's keys are the -/// plug-in's. +/// plug-in's. An image's `opacity`, which filters are given from plug-in API level 3, may be left +/// out, so an entry that a filter built for level 2 writes as it was given there still matches. fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> { let changed = match (o, given) { (Value::Object(x), Value::Object(y)) => { let mut keys: Vec<&String> = x.keys().collect(); keys.sort(); - keys.into_iter().find_map(|k| match y.get(k) { - Some(q) => first_difference(&x[k], q, k), - None => Some(k.clone()), - }) + keys.into_iter() + .find_map(|k| match y.get(k) { + Some(q) => first_difference(&x[k], q, k), + None => Some(k.clone()), + }) + .or_else(|| { + let image = y.get("type").and_then(Value::as_str) == Some(InputKind::Image.name()); + let mut missing: Vec<&String> = y.keys().filter(|k| !x.contains_key(*k) && !(image && *k == "opacity")).collect(); + missing.sort(); + missing.first().map(|k| (*k).clone()) + }) } - _ => None, + _ => first_difference(o, given, ""), }; - match changed.or_else(|| first_difference(o, given, "")) { + match changed { None => Ok(()), Some(field) => Err(read_only_changed(at, &field)), } diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 147b9a1f4a..99baa8dfd7 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1066,7 +1066,8 @@ fn a_changed_field_is_named_escaped_and_short() { } /// A filter given read-only objects returns each one as `{"id": …}` or exactly as given (numbers by -/// value), and they stay as they are, new objects listed after one going just above it. Any change, +/// value; an image may leave out its `opacity`), and they stay as they are, new objects listed +/// after one going just above it. Any change, /// an object left out or listed twice, and a new object of such a kind are refused before anything /// changes. #[test] @@ -1087,6 +1088,14 @@ fn read_only_kind_field_and_omission_refuse() { let mut echo = input.clone(); echo["objects"][3]["transform"] = json!([1, 0, 0, 1, 5, 50]); assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_ok()); + // An image without `opacity`, as plug-in API level 2 gave it, is the image as given. + let mut echo = input.clone(); + for i in [4, 5] { + assert_eq!(echo["objects"][i]["type"], json!("image")); + echo["objects"][i].as_object_mut().unwrap().remove("opacity"); + } + let out = decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).unwrap(); + assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5); // So is an id written as a float; a fractional one names no object. let id = input["objects"][3]["id"].as_u64().unwrap(); let mut echo = input.clone(); @@ -1284,6 +1293,30 @@ fn bad_writes_are_refused_naming_the_object_and_the_field() { &InputKind::ALL, "font_family: must be 1-256 printable characters".into(), ), + ( + text, + json!({"text": {"runs": styled(&|s| s["font_family"] = json!(format!(" {}", "a".repeat(256))))}}), + &InputKind::ALL, + "font_family: must be 1-256 printable characters".into(), + ), + ( + text, + json!({"text": {"runs": styled(&|s| s["fill"] = json!({"type": "solid", "color": s["fill"]["color"], "tintt": 0.5}))}}), + &InputKind::ALL, + "text.runs[0].style.fill: unknown key 'tintt'".into(), + ), + ( + text, + json!({"text": {"runs": styled(&|s| s["stroke"] = json!({"type": "none", "pattern": "Dots"}))}}), + &InputKind::ALL, + "text.runs[0].style.stroke: unknown key 'pattern'".into(), + ), + ( + text, + json!({"text": {"runs": [{"text": "A\nB\nC", "style": style}], "paragraphs": input["objects"][at(text)]["text"]["paragraphs"]}}), + &InputKind::ALL, + "text.paragraphs: expected 3 paragraph styles, one per paragraph".into(), + ), (text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()), (text, json!({"text": 5}), &InputKind::ALL, format!("objects[{ti}] (id {t}): `text` must be an object")), (text, json!({"text": {"runs": [{"text": 5, "style": style}]}}), &InputKind::ALL, "text.runs[0]: `text` must be a string".into()), @@ -1358,6 +1391,7 @@ fn written_text_is_held_to_the_input_limits_and_truncated_type_keeps_its_text() for (id, text_v, says) in [ (text, json!({"runs": [run("x".repeat(MAX_INPUT_TEXT + 1))]}), format!("bytes of text (limit {MAX_INPUT_TEXT})")), (text, json!({"runs": vec![run("x".into()); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")), + (text, json!({"runs": [run("\n".repeat(MAX_INPUT_RUNS))]}), format!("{} paragraphs (limit {MAX_INPUT_RUNS})", MAX_INPUT_RUNS + 1)), (text, json!({"paragraphs": vec![json!({}); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")), (long, json!({"runs": [run("short".into())]}), "the text of type given as `truncated` can't be changed".to_string()), ] { diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs index 03667373bb..48588e40e2 100644 --- a/crates/plugins/src/objects/writes.rs +++ b/crates/plugins/src/objects/writes.rs @@ -3,6 +3,8 @@ //! attributes, and its paragraph styles; an image's opacity; and the symbol an instance shows. //! Every other field stays read-only, and every value is checked before anything changes. +use std::collections::HashSet; + use serde::de::DeserializeOwned; use serde_json::{Map, Value}; use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR}; @@ -66,7 +68,8 @@ pub(super) fn changes(o: &Map, given: &Value, kind: InputKind, at /// (the text the input gave), into `out`; its other fields must be as given, and type given as /// `truncated` keeps its text. A changed list is held to [`MAX_INPUT_RUNS`] entries, and changed /// runs to [`MAX_INPUT_TEXT`] bytes of text, which count toward `total`, held to -/// [`MAX_INPUT_TEXT_TOTAL`]. +/// [`MAX_INPUT_TEXT_TOTAL`], and to [`MAX_INPUT_RUNS`] paragraphs. With changed runs, `paragraphs` +/// given as they were go into `out` too, to be checked against the new paragraphs. fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map) -> Result<()> { let t = v.as_object().ok_or_else(|| out_err(at, format!("`{key}` must be an object")))?; let mut keys: Vec<&String> = t.keys().collect(); @@ -98,6 +101,12 @@ fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, to if bytes > MAX_INPUT_TEXT { return Err(out_err(&format!("{at}.{field}"), format!("{bytes} bytes of text (limit {MAX_INPUT_TEXT})"))); } + // Each paragraph gets a paragraph style; the text holds at most as many paragraphs as runs. + let breaks = |r: &Value| r.get("text").and_then(Value::as_str).map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count()); + let paragraphs = list.iter().fold(1usize, |n, r| n.saturating_add(breaks(r))); + if paragraphs > MAX_INPUT_RUNS { + return Err(out_err(&format!("{at}.{field}"), format!("{paragraphs} paragraphs (limit {MAX_INPUT_RUNS})"))); + } *total = total.saturating_add(bytes); if *total > MAX_INPUT_TEXT_TOTAL { return Err(out_err(&format!("{at}.{field}"), format!("more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output"))); @@ -105,6 +114,13 @@ fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, to } out.insert(k.clone(), t[k].clone()); } + // Paragraph styles given as they were still need one per paragraph of the new runs. + if out.contains_key("runs") + && !out.contains_key("paragraphs") + && let Some(p) = t.get("paragraphs") + { + out.insert("paragraphs".into(), p.clone()); + } Ok(()) } @@ -237,7 +253,8 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va if let Some(runs) = runs { let at = format!("{at}.text.runs"); let list = runs.as_array().map(Vec::as_slice).unwrap_or_default(); - let own: Vec = t.runs.iter().map(|r| serde_json::to_value(&r.style).unwrap_or(Value::Null)).collect(); + // The type's own styles, as JSON text, to look each run's style up once. + let own: HashSet = t.runs.iter().filter_map(|r| serde_json::to_string(&r.style).ok()).collect(); let mut new = Vec::with_capacity(list.len()); for (i, v) in list.iter().enumerate() { let at = format!("{at}[{i}]"); @@ -260,7 +277,12 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va } // Every number goes to the layout, so it is checked even in a style the type has. style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?; - if !own.contains(style_v) { + for key in ["fill", "stroke"] { + if let Some(p) = style_v.get(key) { + check_paint_keys(p, &format!("{at}.style.{key}"))?; + } + } + if !serde_json::to_string(&style).is_ok_and(|s| own.contains(&s)) { check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?; } } @@ -441,11 +463,12 @@ fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result, at: &str) -> Result<()> { let family = s.font_family.trim(); - if family.is_empty() || family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) { + if family.is_empty() || s.font_family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) { return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters"))); } let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| { @@ -457,3 +480,20 @@ fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: & s.stroke = paint(&s.stroke, was.map(|w| &w.stroke), "stroke")?; Ok(()) } + +/// Checks that paint `v` of a style, at `at`, has no key besides `type` and those its `type` +/// reads; a key of another paint, or an unknown one, is an error naming it. +fn check_paint_keys(v: &Value, at: &str) -> Result<()> { + let Some(o) = v.as_object() else { return Ok(()) }; + let known: &[&str] = match o.get("type").and_then(Value::as_str) { + Some("solid") => &["color", "swatch", "tint"], + Some("gradient") => attr_names::(), + Some("pattern") => &["pattern", "xf"], + _ => &[], + }; + if let Some(k) = o.keys().find(|k| *k != "type" && !known.contains(&k.as_str())) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(at, format!("unknown key '{k}'"))); + } + Ok(()) +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f44a98aa2b..f04f04fc31 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7886,6 +7886,7 @@ variable-list-end {0}, {1} {0} i {1} @msg must be a list of at most {MAX_INPUT_RUNS} entries ha de ser una llista d’un màxim de {MAX_INPUT_RUNS} entrades @msg type needs at least one run el text necessita almenys un tram @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de text (límit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paràgrafs (límit {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output més de {MAX_INPUT_TEXT_TOTAL} bytes de text en tota la sortida @msg unknown key '{k}' clau desconeguda '{k}' @msg must be a list of 6 numbers ha de ser una llista de 6 nombres diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bd9a668d87..747698eafa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7496,6 +7496,7 @@ axis Y Axis osa Y @msg must be a list of at most {MAX_INPUT_RUNS} entries musí být seznam nejvýše {MAX_INPUT_RUNS} položek @msg type needs at least one run text potřebuje alespoň jeden úsek @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtů textu (limit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} odstavců (limit {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output více než {MAX_INPUT_TEXT_TOTAL} bajtů textu v celém výstupu @msg unknown key '{k}' neznámý klíč '{k}' @msg must be a list of 6 numbers musí být seznam 6 čísel diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1fd4a9d2d8..1d47d41030 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -708,6 +708,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg must be a list of at most {MAX_INPUT_RUNS} entries skal være en liste med højst {MAX_INPUT_RUNS} elementer @msg type needs at least one run tekst skal have mindst ét tekststykke @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte tekst (grænse {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} afsnit (grænse {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mere end {MAX_INPUT_TEXT_TOTAL} byte tekst i hele outputtet @msg unknown key '{k}' ukendt nøgle '{k}' @msg must be a list of 6 numbers skal være en liste med 6 tal diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index aa2452f6a7..e791d84bbb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7079,6 +7079,7 @@ axis Y Axis Y-Achse @msg must be a list of at most {MAX_INPUT_RUNS} entries muss eine Liste mit höchstens {MAX_INPUT_RUNS} Einträgen sein @msg type needs at least one run Text braucht mindestens einen Abschnitt @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} Byte Text (Grenze {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} Absätze (Grenze {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mehr als {MAX_INPUT_TEXT_TOTAL} Byte Text in der gesamten Ausgabe @msg unknown key '{k}' unbekannter Schlüssel '{k}' @msg must be a list of 6 numbers muss eine Liste von 6 Zahlen sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2932e0f10f..338d012156 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7486,6 +7486,7 @@ axis Y Axis Άξονας Y @msg must be a list of at most {MAX_INPUT_RUNS} entries πρέπει να είναι λίστα με έως {MAX_INPUT_RUNS} στοιχεία @msg type needs at least one run το κείμενο χρειάζεται τουλάχιστον ένα τμήμα @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte κειμένου (όριο {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} παράγραφοι (όριο {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output περισσότερα από {MAX_INPUT_TEXT_TOTAL} byte κειμένου σε όλη την έξοδο @msg unknown key '{k}' άγνωστο κλειδί '{k}' @msg must be a list of 6 numbers πρέπει να είναι λίστα 6 αριθμών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 34276431cb..6e4f34deff 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7472,6 +7472,7 @@ axis Y Axis Eje Y @msg must be a list of at most {MAX_INPUT_RUNS} entries debe ser una lista de {MAX_INPUT_RUNS} entradas como máximo @msg type needs at least one run el texto necesita al menos un tramo @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (límite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} párrafos (límite {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output más de {MAX_INPUT_TEXT_TOTAL} bytes de texto en toda la salida @msg unknown key '{k}' clave desconocida '{k}' @msg must be a list of 6 numbers debe ser una lista de 6 números diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f32241570a..d1135176ff 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7563,6 +7563,7 @@ axis Y Axis Y-akseli @msg must be a list of at most {MAX_INPUT_RUNS} entries on oltava luettelo, jossa on enintään {MAX_INPUT_RUNS} kohdetta @msg type needs at least one run tekstissä on oltava vähintään yksi tekstijakso @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} tavua tekstiä (raja {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} kappaletta (raja {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output yli {MAX_INPUT_TEXT_TOTAL} tavua tekstiä koko tulosteessa @msg unknown key '{k}' tuntematon avain '{k}' @msg must be a list of 6 numbers on oltava 6 luvun luettelo diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 47613b7f0b..299f44bfbf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7493,6 +7493,7 @@ axis Y Axis Axe Y @msg must be a list of at most {MAX_INPUT_RUNS} entries doit être une liste d’au plus {MAX_INPUT_RUNS} entrées @msg type needs at least one run le texte doit compter au moins un segment @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} octets de texte (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraphes (limite {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output plus de {MAX_INPUT_TEXT_TOTAL} octets de texte sur l’ensemble de la sortie @msg unknown key '{k}' clé inconnue '{k}' @msg must be a list of 6 numbers doit être une liste de 6 nombres diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index c2a539baaa..f67e02ec23 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6680,6 +6680,7 @@ arrowhead Feather पंख @msg must be a list of at most {MAX_INPUT_RUNS} entries अधिकतम {MAX_INPUT_RUNS} प्रविष्टियों की सूची होनी चाहिए @msg type needs at least one run टेक्स्ट में कम से कम एक रन होना चाहिए @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) टेक्स्ट के {bytes} बाइट (सीमा {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} अनुच्छेद (सीमा {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output पूरे आउटपुट में {MAX_INPUT_TEXT_TOTAL} बाइट से अधिक टेक्स्ट @msg unknown key '{k}' अज्ञात कुंजी '{k}' @msg must be a list of 6 numbers 6 संख्याओं की सूची होनी चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 33c9c60ee3..0fb8ed6aa7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7481,6 +7481,7 @@ axis Y Axis Y tengely @msg must be a list of at most {MAX_INPUT_RUNS} entries legfeljebb {MAX_INPUT_RUNS} elemű lista legyen @msg type needs at least one run a szövegnek legalább egy szakaszra van szüksége @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bájt szöveg (korlát: {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} bekezdés (korlát: {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output több mint {MAX_INPUT_TEXT_TOTAL} bájt szöveg a teljes kimenetben @msg unknown key '{k}' ismeretlen kulcs: '{k}' @msg must be a list of 6 numbers 6 számból álló lista legyen diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index caf5f93cfe..b14f822bb4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -590,6 +590,7 @@ @msg must be a list of at most {MAX_INPUT_RUNS} entries harus berupa daftar berisi paling banyak {MAX_INPUT_RUNS} entri @msg type needs at least one run teks memerlukan setidaknya satu potongan @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte teks (batas {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraf (batas {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output lebih dari {MAX_INPUT_TEXT_TOTAL} byte teks di seluruh keluaran @msg unknown key '{k}' kunci tidak dikenal '{k}' @msg must be a list of 6 numbers harus berupa daftar 6 angka diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0659a3fcb0..cd25008e7a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7118,6 +7118,7 @@ axis Y Axis Asse Y @msg must be a list of at most {MAX_INPUT_RUNS} entries deve essere un elenco di al massimo {MAX_INPUT_RUNS} voci @msg type needs at least one run il testo richiede almeno un segmento @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte di testo (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragrafi (limite {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output più di {MAX_INPUT_TEXT_TOTAL} byte di testo nell’intero output @msg unknown key '{k}' chiave sconosciuta '{k}' @msg must be a list of 6 numbers deve essere un elenco di 6 numeri diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 40564d2335..623bf42990 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7193,6 +7193,7 @@ axis Y Axis Y 軸 @msg must be a list of at most {MAX_INPUT_RUNS} entries {MAX_INPUT_RUNS} 項目以下のリストにしてください @msg type needs at least one run テキストには 1 つ以上のランが必要です @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) テキストが {bytes} バイトあります (上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落が {paragraphs} 個あります (上限 {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 出力全体のテキストが {MAX_INPUT_TEXT_TOTAL} バイトを超えています @msg unknown key '{k}' 不明なキー '{k}' @msg must be a list of 6 numbers 6 つの数値のリストにしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d03cd5d871..6064542ca7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9599,6 +9599,7 @@ axis Y Axis Y ღერძი @msg must be a list of at most {MAX_INPUT_RUNS} entries უნდა იყოს სია მაქსიმუმ {MAX_INPUT_RUNS} ჩანაწერით @msg type needs at least one run ტექსტს სჭირდება მინიმუმ ერთი მონაკვეთი @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) ტექსტის {bytes} ბაიტი (ლიმიტი {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} აბზაცი (ლიმიტი {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output მთელ გამონატანში {MAX_INPUT_TEXT_TOTAL} ბაიტზე მეტი ტექსტია @msg unknown key '{k}' უცნობი გასაღები '{k}' @msg must be a list of 6 numbers უნდა იყოს 6 რიცხვის სია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5d9fc80d8e..ea4f59f9bd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7090,6 +7090,7 @@ axis Y Axis Y축 @msg must be a list of at most {MAX_INPUT_RUNS} entries 항목이 최대 {MAX_INPUT_RUNS}개인 목록이어야 합니다 @msg type needs at least one run 문자에는 런이 하나 이상 있어야 합니다 @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 텍스트 {bytes}바이트(한도 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 단락 {paragraphs}개(한도 {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 출력 전체의 텍스트가 {MAX_INPUT_TEXT_TOTAL}바이트를 넘습니다 @msg unknown key '{k}' 알 수 없는 키 '{k}' @msg must be a list of 6 numbers 숫자 6개의 목록이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 98b9ef88fa..43e6d1f4c3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -554,6 +554,7 @@ liquify-list-end {0}, {1} {0} en {1} @msg must be a list of at most {MAX_INPUT_RUNS} entries moet een lijst van ten hoogste {MAX_INPUT_RUNS} items zijn @msg type needs at least one run tekst heeft ten minste één tekstreeks nodig @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes tekst (limiet {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} alinea's (limiet {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output meer dan {MAX_INPUT_TEXT_TOTAL} bytes tekst in de hele uitvoer @msg unknown key '{k}' onbekende sleutel '{k}' @msg must be a list of 6 numbers moet een lijst van 6 getallen zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0ae06b14fe..ee5699b7da 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7351,6 +7351,7 @@ axis Y Axis Oś Y @msg must be a list of at most {MAX_INPUT_RUNS} entries musi być listą co najwyżej {MAX_INPUT_RUNS} pozycji @msg type needs at least one run tekst potrzebuje co najmniej jednego fragmentu @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtów tekstu (limit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} akapitów (limit {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output ponad {MAX_INPUT_TEXT_TOTAL} bajtów tekstu w całym wyniku @msg unknown key '{k}' nieznany klucz '{k}' @msg must be a list of 6 numbers musi być listą 6 liczb diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9ea5a38f63..6a2651871b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7395,6 +7395,7 @@ axis Y Axis Eixo Y @msg must be a list of at most {MAX_INPUT_RUNS} entries deve ser uma lista de no máximo {MAX_INPUT_RUNS} entradas @msg type needs at least one run o texto precisa de pelo menos um trecho @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} parágrafos (limite {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mais de {MAX_INPUT_TEXT_TOTAL} bytes de texto em toda a saída @msg unknown key '{k}' chave desconhecida '{k}' @msg must be a list of 6 numbers deve ser uma lista de 6 números diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2eece19466..a5fc05d141 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7118,6 +7118,7 @@ axis Y Axis Ось Y @msg must be a list of at most {MAX_INPUT_RUNS} entries должно быть списком не более чем из {MAX_INPUT_RUNS} элементов @msg type needs at least one run у текста должен быть хотя бы один фрагмент @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байт текста (предел {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} абзацев (предел {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output более {MAX_INPUT_TEXT_TOTAL} байт текста во всём выводе @msg unknown key '{k}' неизвестный ключ '{k}' @msg must be a list of 6 numbers должно быть списком из 6 чисел diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index bdf7d14ed1..f2e656b5b0 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7508,6 +7508,7 @@ axis Y Axis Y-axel @msg must be a list of at most {MAX_INPUT_RUNS} entries måste vara en lista med högst {MAX_INPUT_RUNS} poster @msg type needs at least one run text behöver minst ett textavsnitt @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte text (gräns {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} stycken (gräns {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mer än {MAX_INPUT_TEXT_TOTAL} byte text i hela utdatan @msg unknown key '{k}' okänd nyckel '{k}' @msg must be a list of 6 numbers måste vara en lista med 6 tal diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 1314fa61b0..852b8adfa6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7568,6 +7568,7 @@ axis Y Axis Y ekseni @msg must be a list of at most {MAX_INPUT_RUNS} entries en fazla {MAX_INPUT_RUNS} girişli bir liste olmalıdır @msg type needs at least one run metnin en az bir parçası olmalıdır @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bayt metin (sınır {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraf (sınır {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output çıktının tamamında {MAX_INPUT_TEXT_TOTAL} bayttan fazla metin @msg unknown key '{k}' bilinmeyen anahtar '{k}' @msg must be a list of 6 numbers 6 sayılık bir liste olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b4db911a41..34917ef772 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7100,6 +7100,7 @@ axis Y Axis Вісь Y @msg must be a list of at most {MAX_INPUT_RUNS} entries має бути списком щонайбільше з {MAX_INPUT_RUNS} елементів @msg type needs at least one run текст повинен мати щонайменше один фрагмент @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байтів тексту (межа {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} абзаців (межа {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output понад {MAX_INPUT_TEXT_TOTAL} байтів тексту в усьому виводі @msg unknown key '{k}' невідомий ключ '{k}' @msg must be a list of 6 numbers має бути списком із 6 чисел diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 440b373486..87ec8f1a34 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7147,6 +7147,7 @@ axis Y Axis Trục Y @msg must be a list of at most {MAX_INPUT_RUNS} entries phải là danh sách có tối đa {MAX_INPUT_RUNS} mục @msg type needs at least one run văn bản cần ít nhất một đoạn chạy @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte văn bản (giới hạn {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} đoạn văn (giới hạn {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output hơn {MAX_INPUT_TEXT_TOTAL} byte văn bản trên toàn bộ đầu ra @msg unknown key '{k}' khóa không xác định '{k}' @msg must be a list of 6 numbers phải là danh sách gồm 6 số diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ba4c8c3cfa..357b1419c8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7328,6 +7328,7 @@ axis Y Axis Y 轴 @msg must be a list of at most {MAX_INPUT_RUNS} entries 必须是最多 {MAX_INPUT_RUNS} 个条目的列表 @msg type needs at least one run 文字至少需要一个文本段 @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文本 {bytes} 字节(上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落 {paragraphs} 个(上限 {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整个输出中的文本超过 {MAX_INPUT_TEXT_TOTAL} 字节 @msg unknown key '{k}' 未知键 '{k}' @msg must be a list of 6 numbers 必须是 6 个数字的列表 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e9654bb319..99c71f648c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7149,6 +7149,7 @@ axis Y Axis Y 軸 @msg must be a list of at most {MAX_INPUT_RUNS} entries 必須是最多 {MAX_INPUT_RUNS} 個項目的清單 @msg type needs at least one run 文字至少需要一個文字段 @msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文字 {bytes} 位元組(上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落 {paragraphs} 個(上限 {MAX_INPUT_RUNS}) @msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整個輸出中的文字超過 {MAX_INPUT_TEXT_TOTAL} 位元組 @msg unknown key '{k}' 未知的鍵 '{k}' @msg must be a list of 6 numbers 必須是 6 個數字的清單 diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..d1fff5a2ee 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -563,14 +563,15 @@ fn installing_a_plugin_over_another_module_asks_first() { } /// A plug-in with two commands: Grow, which adds a triangle (`_context.command` is `grow`), and -/// Size, with a parameter, whose `menu` names another menu. +/// Size, with a parameter, whose `menu` names another menu, which adds a square. fn commands_plugin(id: &str) -> Vec { let manifest = format!( r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Grow"}}, {{"id":"size","label":"Size","menu":"File","params":{{"by":{{"type":"number","min":0,"max":10,"default":2}}}}}}]}}"# ); let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#; - wat::parse_str(tpl::when_given(&manifest, tpl::Given::Params, r#""command":"grow""#, triangle)).unwrap() + let square = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]},{"p":[0,5]}]}]}}]}"#; + wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""command":"grow""#, triangle, square)).unwrap() } fn objects(app: &VectorcraftApp) -> usize { diff --git a/docs/mcp.md b/docs/mcp.md index 242d876fde..98996a5afb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13257,10 +13257,12 @@ transforms and names included: pixels and runs that don't fit come the same way, fit makes `plugin.run` return a memory-budget error naming the object and its size, with nothing changed. A path or compound path that doesn't fit makes it return the memory-budget error `the selection is too large to hand over`, and more than 100,000 of these objects make it return an object-budget error. Its output returns -each of them as `{"id": …}` or exactly as given, otherwise `plugin.run` returns an error naming the object and the -field, and the document and undo history are unchanged. A filter at plug-in API level 3 whose manifest also lists some of +each of them as `{"id": …}` or exactly as given (an image may leave out `opacity`), otherwise `plugin.run` returns an +error naming the object and the field, and the document and undo history are unchanged. A filter at plug-in API level 3 whose manifest also lists some of those kinds in `writes` (with `doc.write`; `writes` in its `plugin.list` entry) may return an object of such a kind with -only the fields it changes: its name and `transform`, type's `text.runs` and `text.paragraphs`, an image's `opacity` and +only the fields it changes: its name and `transform`, type's `text.runs` (at most 4,096 runs and 4,096 paragraphs, and +fills and strokes with only the keys their `type` reads) and `text.paragraphs` (one style per paragraph of the new text, +also when returned as given next to changed runs), an image's `opacity` and an instance's `symbolId`, which must name a symbol in the document. Any other changed field, or a value out of range, makes `plugin.run` return an error naming the object and the field, with nothing changed (docs/plugins.md, "Writing type, images and symbols"). An output that changes nothing records no undo step. A filter at plug-in API level 2 whose manifest lists the diff --git a/docs/plugins.md b/docs/plugins.md index f857f1498f..18f85bfdf8 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -552,7 +552,7 @@ the module's start function, in a run that isn't a filter's run on a document, o filters](#heavy-filters)). Hosts from before it ignore the key, so there the filter gets a light run's budget. - `api`: the plug-in API level, `1` when left out. `permissions`: what the plug-in may do, a list of names ([permissions](#permissions)); without it, what its kind implies. -- `inputs` (filters at `api` 2 only): the kinds of object besides paths and compound paths the filter reads, any of +- `inputs` (filters at `api` 2 or later): the kinds of object besides paths and compound paths the filter reads, any of `"type"`, `"image"` and `"symbolInstance"`, each at most once (`"inputs": ["type", "image"]`). Left out or `[]`, the filter gets paths and compound paths alone, as before. An unknown, repeated or wrongly typed entry, `inputs` on another kind, below `api` 2, or without a `permissions` list that holds `doc.read`, is refused when the plug-in is @@ -717,10 +717,13 @@ every attribute: - A symbol instance (`"symbolInstance"`): `symbolId` is the name of the symbol it shows, with `missing: true` when the document has no symbol of that name. `overrides` is `{}`. -These objects are read only. The output must list each of them exactly once, as `{"id": 17}` alone or exactly as it -was given (numbers compare by value, so `1` and `1.0` are the same). A changed or added field, one left out, an object -listed twice or left out, and a new object with one of these types are refused, and the document and undo history -stay as they were: `objects[1] (id 17): read-only field 'text.runs[0].text' changed`, `objects (id 17): a read-only +Objects of a kind that the manifest's `writes` doesn't list are read only. The output must list each of them exactly +once, as `{"id": 17}` alone or exactly as it was given (numbers compare by value, so `1` and `1.0` are the same). An +image may leave out `opacity`, which hosts before `api` 3 don't give. An object of a kind that `writes` lists is also +listed exactly once, and its entry may give only the fields it changes ([writing type, images and +symbols](#writing-type-images-and-symbols)). An output deletes the paths and compound paths it leaves out +([output](#output)), but none of these objects. A changed or added field, one left out, an object listed twice or left +out, and a new object with one of these types are refused, and the document and undo history stay as they were: `objects[1] (id 17): read-only field 'text.runs[0].text' changed`, `objects (id 17): a read-only object was left out`. The field is named with control and bidirectional characters escaped (`\u{202E}`), cut to 64 characters. New objects listed after one of them go just above it. @@ -758,8 +761,9 @@ exactly as given, or with the fields it changes; a field it leaves out keeps its - `transform` is six finite numbers, each within ±4,000,000, that don't flatten the object to a line. The object moves by the change from its given transform, so an image's distorted corners move with it. - `text.runs` replaces the type's runs: each is `{text, style, inline?}` with the character attributes as the native - file stores them, and an attribute the host doesn't know is refused. There is at least one run, at most 4,096, and at - most 256 KiB of UTF-8 text; the runs written in one output take at most 16 MiB. Every number in every run's style is + file stores them, and an attribute the host doesn't know is refused, as is a key of a fill or stroke that its `type` + doesn't read. There is at least one run, at most 4,096, at most 4,096 paragraphs, and at most 256 KiB of UTF-8 text; + the runs written in one output take at most 16 MiB. Every number in every run's style is checked against the range `charStyle.new` keeps it to, including a style one of the type's runs already has: size 0.1 to 1296 pt, leading 0.1 to 5000 pt, tracking and kerning -1000 to 10000, horizontal and vertical scale 1 to 10000 %, baseline shift -1296 to 1296 pt, rotation -360 to 360°, and the ranges `docs/mcp.md` gives for @@ -771,7 +775,8 @@ exactly as given, or with the fields it changes; a field it leaves out keeps its - `text.paragraphs` holds one paragraph style per paragraph of the new text, each checked as `paraStyle.new` checks its attributes: indents and space before and after within ±1296 pt, the Hyphenation and Justification options in their ranges, at most 256 tab stops at 0 to 100,000 pt, and a custom Kinsoku set only by the name of one of the - document's sets, whose characters the paragraph takes. With `text.runs` alone, each paragraph keeps its style when + document's sets, whose characters the paragraph takes. A `text.paragraphs` list returned as it was given next to + changed `text.runs` must also hold one style per paragraph of the new text. With `text.runs` alone, each paragraph keeps its style when the number of paragraphs stays the same. When runs add or join paragraphs, the host matches the old and new paragraphs by their text: a paragraph whose text is unchanged keeps its style, changed paragraphs take the styles of the paragraphs they replace in order, and a paragraph added between others takes the style of the one before it (of @@ -828,7 +833,9 @@ For an **object filter**, the output is the new state of the input objects: - An object without an `id` is new and needs a `path`. It goes just above the object listed before it, or, listed before any input object, just below the first one listed after it. New objects take a path's defaults: no fills or strokes, full opacity. -- Input objects missing from the output are deleted. The order of the input objects themselves doesn't change. +- Input paths and compound paths missing from the output are deleted; type, images and symbol instances can't be left + out ([reading type, images and symbols](#reading-type-images-and-symbols)). The order of the input objects themselves + doesn't change. - `type` turns a path into a compound path (one member per subpath) or back; `name: ""` clears the name. - `guide: true` makes the object a guide, as View › Guides › Make Guides does (a compound path's members become guide paths), and `guide: false` a plain path again; `locked: true` locks it and `locked: false` unlocks it. Objects From 9562ed9b04d7a89d101e9456bafbbbc54b177ab4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:26:19 -0800 Subject: [PATCH 034/107] 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 3b0823e432f472ec186e49f2db356533e66cc148 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 21:05:59 -0800 Subject: [PATCH 035/107] 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 036/107] 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 b7278c9b2f5c318109e54c904cf06f9368004547 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:05:54 -0800 Subject: [PATCH 037/107] Scripts: test a finally callback that returns a pending promise The result of finally() stays pending until the callback's promise settles in a later run. A fulfilled callback promise keeps the original value or reason, and a rejected one passes on its own reason. --- crates/js/src/promise_tests.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 8e03f2a136..1b258024d8 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -315,6 +315,26 @@ fn a_sliced_run_pauses_inside_a_finally_callback() { assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into())); } +#[test] +fn a_finally_callback_that_returns_a_pending_promise_holds_the_result_until_a_later_run_settles_it() { + let mut r = realm(); + r.run( + "var log = [], settle = {};\n\ + function wait(name) { return function () { return new Promise(function (res, rej) { settle[name] = { res: res, rej: rej }; }); }; }\n\ + function report(name) { return [function (v) { log.push(name + ' kept ' + v); }, function (e) { log.push(name + ' rejected ' + e); }]; }\n\ + var a = report('a'), b = report('b'), c = report('c'), d = report('d');\n\ + Promise.resolve(1).finally(wait('a')).then(a[0], a[1]);\n\ + Promise.reject(2).finally(wait('b')).then(b[0], b[1]);\n\ + Promise.resolve(3).finally(wait('c')).then(c[0], c[1]);\n\ + Promise.reject(4).finally(wait('d')).then(d[0], d[1]);", + ) + .unwrap(); + assert_eq!(r.run("Object.keys(settle).sort().join(' ') + '|' + log.join(' ')").unwrap(), JsValue::String("a b c d|".into())); + r.collect_garbage(); + r.run("settle.a.res('ignored'); settle.b.res('ignored'); settle.c.rej('new c'); settle.d.rej('new d');").unwrap(); + assert_eq!(r.run("log.join(', ')").unwrap(), JsValue::String("a kept 1, b rejected 2, c rejected new c, d rejected new d".into())); +} + #[test] fn an_ended_sliced_run_drops_its_jobs() { let mut r = realm(); From ff9ed631fa5eb5379b5db5a617ff7d2e57299263 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 00:13:32 -0800 Subject: [PATCH 038/107] Scripts: an unhandled rejection's reason is read only up to the report's length The report keeps the first 500 characters of a rejection reason. The reason string is now read up to that length along the rope, instead of being copied whole before it is cut. --- crates/js/src/builtins/promise.rs | 4 +++- crates/js/src/interp.rs | 10 ++++++++-- crates/js/src/promise_tests.rs | 22 ++++++++++++++++++++++ crates/js/src/value.rs | 25 +++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 52c0e229ae..655dcde430 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -741,7 +741,9 @@ impl Interp { if out.len() >= MAX_REPORTED { continue; } - let mut message = self.describe(&reason); + // Two code units per character keeps MAX_REASON_CHARS characters and one more, so the + // cut below still marks a longer reason. + let mut message = self.describe_prefix(&reason, 2 * MAX_REASON_CHARS + 2); if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) { message.truncate(cut); message.push('…'); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 45de3cbe92..e5e1d8a0d9 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3095,9 +3095,15 @@ impl Interp { /// A description of a thrown value that runs no JavaScript: `Name: message` for an error, /// the text of a primitive. pub(crate) fn describe(&mut self, v: &Value) -> String { - let Value::Object(o) = v else { return self.primitive_to_str(v).to_rust_string() }; + self.describe_prefix(v, usize::MAX) + } + + /// [`Interp::describe`] with each string it reads cut to its first `max_units` code units + /// before it is copied. + pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String { + let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) }; let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) { - Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.to_rust_string()), + Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.prefix_to_rust_string(max_units)), _ => None, }; match (data(self, "name"), data(self, "message")) { diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 1b258024d8..8c222c8de3 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -182,6 +182,28 @@ fn an_unhandled_rejection_is_reported_with_its_line() { assert!(r.unhandled_rejections().iter().all(|j| j.authored)); } +#[test] +fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { + let mut r = realm(); + r.run( + "function rep(t, n) { var s = ''; for (var i = 0; i < n; i++) s = s + t; return s; }\n\ + var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + Promise.reject(ab);\n\ + Promise.reject(new RangeError(ab));\n\ + Promise.reject(rep('\\ud83d\\ude00', 600));\n\ + Promise.reject(rep('x', 500));", + ) + .unwrap(); + let got: Vec = r.unhandled_rejections().iter().map(|j| j.message.clone()).collect(); + let want = vec![ + format!("{}…", "ab".repeat(250)), + format!("RangeError: {}…", "ab".repeat(244)), + format!("{}…", "\u{1F600}".repeat(500)), + "x".repeat(500), + ]; + assert_eq!(got, want); +} + #[test] fn a_rejection_handled_in_a_later_job_is_not_reported() { let mut r = realm(); diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index a0fbcd4a53..e0af7d9567 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -194,6 +194,31 @@ impl Str { pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } + + /// The first `max_units` code units as a Rust string, read along the rope without flattening + /// it, so a long string is not copied whole. + pub(crate) fn prefix_to_rust_string(&self, max_units: usize) -> String { + if self.len() <= max_units { + return self.to_rust_string(); + } + let mut units = Vec::with_capacity(max_units); + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + let room = max_units - units.len(); + if room == 0 { + break; + } + match &*s.0.borrow() { + Node::Flat(f) => units.extend_from_slice(&f[..f.len().min(room)]), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + String::from_utf16_lossy(&units) + } } impl PartialEq for Str { From 71d1600dabda2a161cea41f4c72cdf99b1fb2579 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 06:12:42 -0800 Subject: [PATCH 039/107] Scripts: an error's authored check hashes its name and message without copying them An error the interpreter throws keeps a hash of its description, and a run compares the error's current name and message with it to tell whether the text is the script's own. The comparison copied the whole description first, so a rejected error whose message a script had replaced with a long string was copied whole at the end of the run. The hash is now fed the strings' code units a piece at a time along the rope, so nothing is copied, and a change anywhere in the message is still seen. --- crates/js/src/interp.rs | 53 +++++++++++++++++++++++++++++++--- crates/js/src/promise_tests.rs | 22 ++++++++++++++ crates/js/src/value.rs | 15 ++++++++++ 3 files changed, 86 insertions(+), 4 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index e5e1d8a0d9..d1740a239e 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -50,12 +50,37 @@ fn internal(message: &str) -> JsResult { /// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]). fn description_hash(text: &str) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - text.hash(&mut h); + let mut h = DescriptionHash::default(); + h.text(text); h.finish() } +/// A [`description_hash`] fed the description's code units a run at a time, so a long string is +/// hashed without being copied. +#[derive(Default)] +struct DescriptionHash(std::hash::DefaultHasher); + +impl DescriptionHash { + fn units(&mut self, units: &[u16]) { + use std::hash::Hasher; + for &u in units { + self.0.write_u16(u); + } + } + + fn text(&mut self, text: &str) { + use std::hash::Hasher; + for u in text.encode_utf16() { + self.0.write_u16(u); + } + } + + fn finish(&self) -> u64 { + use std::hash::Hasher; + self.0.finish() + } +} + /// The kinds of error object the engine throws. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ErrorType { @@ -591,7 +616,7 @@ impl Interp { let Value::Object(o) = v else { return true }; let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true }; let hash = *hash; - description_hash(&self.describe(v)) != hash + self.describe_hash(*o) != hash } pub(crate) fn type_error(&mut self, message: &str) -> Abrupt { @@ -3113,6 +3138,26 @@ impl Interp { (None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())), } } + + /// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read + /// along its strings without copying them. + fn describe_hash(&self, o: ObjId) -> u64 { + let data = |k: &str| match self.find_property(o, &key(k)) { + Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s), + _ => None, + }; + let mut h = DescriptionHash::default(); + match (data("name"), data("message")) { + (Some(n), Some(m)) if m.len() != 0 => { + n.for_each_chunk(|c| h.units(c)); + h.text(": "); + m.for_each_chunk(|c| h.units(c)); + } + (Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)), + (None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))), + } + h.finish() + } } /// A compile failure, before it becomes an exception or a run error. diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 8c222c8de3..358a97a434 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -204,6 +204,28 @@ fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { assert_eq!(got, want); } +#[test] +fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() { + let mut r = realm(); + r.run( + "var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + var e; try { null.x; } catch (x) { e = x; }\n\ + e.message = ab;\n\ + Promise.reject(e);\n\ + try { null.x; } catch (x) { Promise.reject(x); }", + ) + .unwrap(); + let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect(); + assert_eq!(got.len(), 2); + assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true)); + assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]); + let interp = r.interp(); + match interp.find_property(interp.global, &crate::heap::key("ab")) { + Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"), + other => panic!("{other:?}"), + } +} + #[test] fn a_rejection_handled_in_a_later_job_is_not_reported() { let mut r = realm(); diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index e0af7d9567..9678a1895f 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -219,6 +219,21 @@ impl Str { } String::from_utf16_lossy(&units) } + + /// Calls `f` with each run of code units in order, read along the rope without flattening it. + pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) { + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + match &*s.0.borrow() { + Node::Flat(units) => f(units), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + } } impl PartialEq for Str { From db7810888df07eddeb5431abfff420df495db0f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 15:28:38 -0800 Subject: [PATCH 040/107] 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 041/107] 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 f2d036af34579050930f51e41aeee03009124694 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:58:12 -0800 Subject: [PATCH 042/107] New Document: the Bleed fields stand in two columns inside the dialog, as Document Setup's do The four Bleed fields used the linked fields' default one-row layout, which is wider than the Preset Details column. In a 1280 by 900 window the Right field ended 169 px past the dialog's right edge. They now use LinkedLayout::Columns, as Document Setup's Bleed fields do (dialogs/document_setup.rs:310): Top and Bottom, then Left and Right, with the link between the columns. --- crates/ui-egui/src/dialogs/new_document.rs | 36 +++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 025a5336af..4d7c7c91d1 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -35,7 +35,7 @@ use craft::ui::pickers::Select; use craft::ui::popover::Popover; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::sections::Section; -use craft::ui::text::{LinkMode, LinkedFields, NumberField}; +use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; use super::host::open_held; use crate::VectorcraftApp; @@ -326,6 +326,7 @@ impl DocumentSettings for VcNewDocument { let captions = [text(tl!("Top")), text(tl!("Bottom")), text(tl!("Left")), text(tl!("Right"))]; let out = LinkedFields::<4>::new(bleed.clone(), Bind::given(parts), Bind::bound(&mut linked)) .mode(LinkMode::Equal) + .layout(LinkedLayout::Columns) .captions(captions) .range(0.0..=vectorcraft_doc::setup::MAX_BLEED) .lengths(lengths) @@ -807,6 +808,39 @@ mod tests { assert_eq!(fields(&app)["name"], json!("Untitled-2")); } + /// The four Bleed fields stay inside the dialog in a 1280 by 900 window; in one row, Right ran past the dialog's + /// right edge. + #[test] + fn bleed_fields_stay_inside_the_dialog() { + let mut app = app(); + open(&mut app); + let ctx = ctx(&app); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + // Each frame gives the app's input once, as the hosts do. + let frame = |app: &mut VectorcraftApp, i: u32| { + let mut raw = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() }; + app.adopt_context(&ctx); + app.raw_input(&ctx, &mut raw); + craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out)); + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + out.textures_delta.clear(); + out + }; + (0..3).for_each(|i| drop(frame(&mut app, i))); + let out = frame(&mut app, 3); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let bounds = |label: Option<&str>, role: egui::accesskit::Role| { + let found = nodes.iter().find(|(_, n)| n.role() == role && label.is_none_or(|l| n.label() == Some(l))); + let (_, n) = found.unwrap_or_else(|| panic!("no {role:?} {label:?}")); + n.bounds().expect("bounds") + }; + let dialog = bounds(None, egui::accesskit::Role::Dialog); + for side in ["Top", "Bottom", "Left", "Right"] { + let field = bounds(Some(side), egui::accesskit::Role::SpinButton); + assert!(dialog.x0 <= field.x0 && field.x1 <= dialog.x1, "Bleed {side} {field:?} stays inside the dialog {dialog:?}"); + } + } + /// More Settings edits only the artboard layout, spacing and columns, and creates nothing. #[test] fn more_settings_is_a_popup_holding_only_the_artboard_layout() { From 1a7cb29bf283bf657564a185b3a5cd1e938a0469 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Wed, 25 Nov 2026 10:38:21 +0500 Subject: [PATCH 043/107] Stroke panel: the cap icons mark the end of the path in one place The end-of-path line sat at x=16 in Butt and Projecting but at x=12 in Round, and the stroke bar was as opaque as the line, so the line vanished where it crossed the bar and the three icons looked alike. The line is now at x=13 in all three over a lighter (0.55) bar, as the stroke-align icons draw it, and the caps are larger, so Round and Projecting reach 5 units past the end instead of 4. Fixes #9229 --- assets/icons/dc-cap-butt.svg | 2 +- assets/icons/dc-cap-round.svg | 2 +- assets/icons/dc-cap-square.svg | 2 +- crates/ui-egui/src/icons.rs | 26 ++++++++++++++++++++++++++ 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/assets/icons/dc-cap-butt.svg b/assets/icons/dc-cap-butt.svg index bf39a170a6..dee85e09a0 100644 --- a/assets/icons/dc-cap-butt.svg +++ b/assets/icons/dc-cap-butt.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-cap-round.svg b/assets/icons/dc-cap-round.svg index 06af9d07ea..bcf2e976c4 100644 --- a/assets/icons/dc-cap-round.svg +++ b/assets/icons/dc-cap-round.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-cap-square.svg b/assets/icons/dc-cap-square.svg index 4a82a10d9a..5fcb2e3c5d 100644 --- a/assets/icons/dc-cap-square.svg +++ b/assets/icons/dc-cap-square.svg @@ -1 +1 @@ - + diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 46b96ae2c1..c37f17c103 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -207,6 +207,32 @@ mod tests { assert!(appearance.contains(" String { + let last = icon.rsplit(" f32 { + icon.split(r#"fill-opacity=""#).nth(1).and_then(|s| s.split('"').next()).and_then(|v| v.parse().ok()).unwrap_or(1.0) + }; + let icons = [("butt", svg("dc-cap-butt")), ("round", svg("dc-cap-round")), ("square", svg("dc-cap-square"))]; + let butt_end = end_line(&icons[0].1); + assert!(butt_end.starts_with('M') && butt_end.contains('V'), "the butt cap icon ends with a vertical end-of-path line: {butt_end}"); + for (name, icon) in &icons { + assert_eq!(end_line(icon), butt_end, "the {name} cap icon marks the end of the path where the butt cap icon does"); + assert!(stroke_opacity(icon) < 1.0, "the {name} cap icon's stroke is lighter than its end-of-path line"); + } + } + // Regression test for #479: the Add and Delete Anchor Point tools' icons were drawn apart from // the Pen tool's, so the three tools didn't read as one family. They are the Pen's pen with a // plus or a minus beside it. From 66efae46f270f14d60959179d49738f6abf1fc00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:45:55 -0800 Subject: [PATCH 044/107] Scripts: app.executeMenuCommand runs a menu command app.executeMenuCommand(name) runs the command of a menu item on the active document. It takes the names selectall, deselectall, group, ungroup, makeMask, releaseMask, compoundPath, noCompoundPath and "Fit Artboard to artwork bounds", which fits the active artboard. Names are matched exactly. Any other name throws an error that names it, and a name that is not a string throws a TypeError. A menu item that is not available, with no document open or nothing selected, does nothing and adds no undo step. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 48 +++++++++++++++++++++++++ crates/engine/src/tests/script_dom.rs | 51 +++++++++++++++++++++++++++ docs/mcp.md | 14 ++++++-- docs/target-app-parity.md | 2 +- 4 files changed, 112 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 39c740cb2e..b7873009b9 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -772,6 +772,53 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(open)) } +/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The +/// strings are the ones +/// +/// lists, and `Fit Artboard to artwork bounds` is the one +/// gives for Object › +/// Artboards › Fit to Artwork Bounds. +const MENU_COMMANDS: &[(&str, &str)] = &[ + ("selectall", "select.all"), + ("deselectall", "select.none"), + ("group", "object.group"), + ("ungroup", "object.ungroup"), + ("makeMask", "object.clippingMask.make"), + ("releaseMask", "object.clippingMask.release"), + ("compoundPath", "object.compoundPath.make"), + ("noCompoundPath", "object.compoundPath.release"), + ("Fit Artboard to artwork bounds", "artboard.fitToArt"), +]; + +/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names +/// ([`MENU_COMMANDS`]) on the active document, as +/// describes the method. A +/// name it does not list throws an error that names it. A menu item that is not available, with +/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does +/// (VectorCraft's own rule). `Fit Artboard to artwork bounds` fits the active artboard. +fn app_menu_command(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the menu command is too long".into())); + } + let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else { + return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\""))); + }; + let params = { + let s = h.session.borrow(); + let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) }; + if (spec.enabled)(&s).is_err() { + return Ok(Data::Undefined); + } + match (id, s.active()) { + ("artboard.fitToArt", Some(st)) => json!({"index": active_artboard(st)}), + _ => json!({}), + } + }; + command(h, id, ¶ms)?; + Ok(Data::Undefined) +} + // ---- Documents ---- fn docs_length(h: &Host, _: &[Data]) -> Answer { @@ -2085,6 +2132,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, app_selection, app_set_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("executeMenuCommand", method(l, app_menu_command)), ("toString", class_text("Application")), ]); application.push(later(l, "Application", "beep")); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..108cc647dc 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1363,6 +1363,57 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let _ = std::fs::remove_file(path); } +#[test] +fn a_menu_command_runs_its_command_on_the_selection() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log(&mut s, "app.executeMenuCommand('ungroup'); vc.log(app.activeDocument.selection.length);"); + assert_eq!(out, vec![json!(2)]); + let st = s.active().unwrap(); + assert!(st.doc.node(g).is_none(), "the group is gone"); + assert!(st.doc.node(a).is_some() && st.doc.node(b).is_some()); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + // With nothing selected the menu item does nothing and adds no undo step. + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = s.active().unwrap().doc.clone(); + log(&mut s, "app.executeMenuCommand('ungroup'); app.executeMenuCommand('releaseMask');"); + assert_eq!(undo_steps(&s), steps); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "nothing changed"); + // selectall then group makes one group of both rectangles. + let out = log(&mut s, "app.executeMenuCommand('selectall'); app.executeMenuCommand('group'); vc.log(app.activeDocument.selection[0].typename);"); + assert_eq!(out, vec![json!("GroupItem")]); +} + +#[test] +fn the_fit_to_artwork_menu_command_fits_the_artboard_to_the_art() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.artboards[0].rect; + log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds');"); + let after = s.active().unwrap().doc.artboards[0].rect; + assert!(after.width() < before.width() && after.height() < before.height(), "{before:?} -> {after:?}"); +} + +#[test] +fn an_unknown_menu_command_throws_and_names_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');"); + assert!(e.contains("acmeNoSuchMenu"), "{e}"); + assert!(failure(&mut s, "app.executeMenuCommand('Ungroup');").contains("Ungroup"), "names are matched exactly"); + assert!(failure(&mut s, "app.executeMenuCommand(5);").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand();").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand(new Array(5000).join('a'));").contains("too long")); + assert_eq!(undo_steps(&s), steps, "nothing changed"); + // With no document open a known menu item does nothing, and an unknown one still throws. + let mut s = Session::new(); + assert_eq!(log(&mut s, "app.executeMenuCommand('selectall'); vc.log(app.documents.length);"), vec![json!(0)]); + assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu")); +} + #[test] fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index d3e47680f1..d0bce21b8d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,8 +2622,18 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and - `app.getIsFileOpen(path)`. A script may name the application's members without `app.`, as + `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`, + `app.getIsFileOpen(path)` and `app.executeMenuCommand(name)`. `executeMenuCommand` runs the command of a menu item + on the active document, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts + describe the method, and takes these names from the list at + https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510: + `selectall` (`select.all`), `deselectall` (`select.none`), `group` (`object.group`), `ungroup` + (`object.ungroup`), `makeMask` (`object.clippingMask.make`), `releaseMask` (`object.clippingMask.release`), + `compoundPath` (`object.compoundPath.make`) and `noCompoundPath` (`object.compoundPath.release`), and + `Fit Artboard to artwork bounds` (https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee), which runs + `artboard.fitToArt` on the active artboard. Names are matched exactly. Any other name throws an error that names + it, and a name that is not a string throws a `TypeError`. VectorCraft's own rule: a menu item that is not + available, with no document open or nothing selected that it acts on, does nothing and adds no undo step. A script may name the application's members without `app.`, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f062c9d54b..9adf5df456 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From b1a52160af8ac33c75b49cabf77a44ff7cde547e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 01:49:15 -0800 Subject: [PATCH 045/107] 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 290da5bef2856ea52cd623bf8098f0cdb08d5303 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:38:31 -0800 Subject: [PATCH 046/107] JavaScript: scripts have the global Boolean constructor The engine built Boolean.prototype but defined no global Boolean, so Boolean(x), new Boolean(x), x instanceof Boolean and filter(Boolean) threw a ReferenceError. Boolean now converts a value when called and makes a Boolean object with new (ECMA-262 5.1 sections 15.6.1 and 15.6.2), with Boolean.prototype as its prototype. test262 no longer skips tests that name Boolean, so more of them run; docs/target-app-parity.md has the new counts. --- crates/js/src/builtins.rs | 16 ++++++++++++++-- crates/js/src/builtins_tests.rs | 15 +++++++++++++++ crates/js/src/lib.rs | 2 +- crates/js/tests/test262.rs | 2 +- docs/target-app-parity.md | 4 ++-- 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f2c02bdf4c..78d514f725 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -1,8 +1,8 @@ //! The built-in objects (ECMA-262 5.1 section 15): `Object` with `Object.prototype` and the //! ES5 statics, `Function` with `Function.prototype.call`, `apply`, `bind` and `toString`, //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex -//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with -//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in +//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and +//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in //! their own modules. //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object @@ -129,6 +129,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, function_proto, "bind", function_bind, 1)?; method(interp, function_proto, "toString", function_to_string, 0)?; + let boolean = native(interp, "Boolean", boolean_ctor, 1, NativeKind::Plain, true)?; + constructor(interp, "Boolean", boolean, boolean_proto)?; method(interp, boolean_proto, "toString", boolean_to_string, 0)?; method(interp, boolean_proto, "valueOf", boolean_value_of, 0)?; @@ -390,6 +392,16 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Ok(Value::str(&format!("[object {class}]"))) } +/// `Boolean(value)` and `new Boolean(value)` (sections 15.6.1 and 15.6.2). +fn boolean_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + let b = args.first().is_some_and(Value::truthy); + if !construct { + return Ok(Value::Bool(b)); + } + let proto = interp.intrinsics.boolean_proto; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Boolean(b), Some(proto))))) +} + /// The Boolean a `Boolean.prototype` method was called on (sections 15.6.4.2 and 15.6.4.3): a /// primitive, or the primitive value of a Boolean object. fn this_boolean(interp: &mut Interp, this: &Value, name: &str) -> JsResult { diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 0a70e80433..14a0f8d542 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -407,6 +407,21 @@ fn boolean_prototype_converts_booleans() { throws("Object.getPrototypeOf(true).valueOf.call({})", "TypeError"); } +#[test] +fn the_boolean_constructor_converts_and_wraps() { + // Called as a function it gives ToBoolean of its argument (section 15.6.1). + truth("Boolean() === false && Boolean(0) === false && Boolean('') === false && Boolean(NaN) === false && Boolean(null) === false"); + truth("Boolean(1) === true && Boolean('false') === true && Boolean({}) === true && Boolean(new Boolean(false)) === true"); + truth("['', 'a', 0, 2].filter(Boolean).length === 2"); + // With new it makes a Boolean object (section 15.6.2), which is truthy whatever it holds. + truth("var b = new Boolean(0); typeof b === 'object' && b.valueOf() === false && !!b && b instanceof Boolean"); + assert_eq!(string("Object.prototype.toString.call(new Boolean(1)) + new Boolean('')"), "[object Boolean]false"); + // The constructor and Boolean.prototype are linked, and true and false look methods up there. + truth("Boolean.prototype === Object.getPrototypeOf(true) && Boolean.prototype.constructor === Boolean && true.constructor === Boolean"); + truth("Boolean.length === 1 && Object(false) instanceof Boolean"); + truth("!Object.getOwnPropertyDescriptor(this, 'Boolean').enumerable && !Object.getOwnPropertyDescriptor(Boolean, 'prototype').writable"); +} + #[test] fn array_methods_overwriting_elements_need_no_heap_for_new_ones() { // With the heap exactly at its limit, an array method's write over an existing element diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 84fce24714..f2b501d7ab 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -26,7 +26,7 @@ //! with loops. The realm provides the language (sections 10 to 14 of ECMA-262 5.1) and these //! built-ins: the global functions and constants (15.1, with Annex B's `escape` and `unescape`), //! `Object` (15.2), `Function` with `call`, `apply` and `bind` (15.3), `Array` (15.4), `String` -//! (15.5), `Boolean.prototype`'s `toString` and `valueOf` (15.6.4), `Number` (15.7), `Math` (15.8), +//! (15.5), `Boolean` (15.6), `Number` (15.7), `Math` (15.8), //! `Date` (15.9), `RegExp` (15.10), the error types (15.11) and `JSON` (15.12). The array methods //! visit only the indices an array or array-like object has, so a sparse array of length 2^32-1 //! costs as much as its elements, and `JSON.parse`, `JSON.stringify` and the reviver walk use no diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index ec3c4dd255..d548e96c27 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -354,7 +354,7 @@ fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> { /// Globals and method names the interpreter does not provide yet: a test that names one, in its /// own source or in a harness file it includes, is skipped. -const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ +const MISSING_BUILTINS: &str = "String Number Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array charAt charCodeAt fromCharCode substring substr split replace \ match search exec test toUpperCase toLowerCase trim toFixed toPrecision toExponential now"; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d40a4216cd..622c55f580 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1090,8 +1090,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - `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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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`. + - `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: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. From 232c17b25a87aa5decf555bde457fa46c19ebf0e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:23:08 -0800 Subject: [PATCH 047/107] Plug-ins: removing an installed plug-in whose module can't be deleted fails plugin.remove now deletes an installed plug-in's stored module along with its grant, before its settings and cache are deleted. When the module file can't be deleted, the command returns "can't delete ", the settings and cache are moved back, the plug-in stays installed, and the grant the signed grants file held for it is written back, so the stored module still loads at the next launch. Before, the command returned {removed} and left the module in the plug-in folder. --- crates/engine/src/cmd/plugin.rs | 21 +++++++++++++--- crates/engine/src/store.rs | 7 ++++++ crates/engine/src/tests/plugins.rs | 39 ++++++++++++++++++++++++++++++ docs/mcp.md | 4 ++- docs/plugins.md | 3 ++- 5 files changed, 68 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 72c3fcb780..5fe20bd477 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1252,18 +1252,31 @@ fn remove(s: &mut Session, p: &Value) -> Result { // A module stored for an id that isn't installed (one no grant covers is skipped at startup) // counts as removed once its file is gone. let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id); + // An installed plug-in's stored module is deleted with its grant too, so that one that can't be + // deleted leaves the plug-in installed. Without a plug-in folder it has none. + let unstore = module || (installed && s.plugin_dir.is_some()); + // The grant the store keeps for an installed plug-in, which may differ from the one the session + // holds (an update whose module couldn't be stored): written back when its module can't be + // deleted, so that the stored module still loads at the next launch. + let kept_grant = if installed { s.stored_plugin_grant(id) } else { None }; let module_left = std::cell::Cell::new(false); let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default()); // Installed again, it asks again. A grant that can't be removed may still approve the module, and // so may a grants file that can't be opened or read, or a signed copy of the file put back when // the generation couldn't be raised (the key store can't be reached). Without a plug-in folder - // nothing keeps a grant. The stored module of an id that isn't installed is deleted next, while - // its settings and cache can still be moved back. + // nothing keeps a grant. The stored module is deleted next, while its settings and cache can + // still be moved back. let forget = || { if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() { return false; } - let deleted = !module || s.unstore_plugin(&turn, id); + let deleted = !unstore || s.unstore_plugin(&turn, id); + if !deleted + && let Some(grant) = kept_grant.clone() + && !s.store_grant_in(&turn, id, Some(grant)) + { + log::warn!("plugin.remove: can't keep the grant of {id}, whose module stays: it asks again at the next launch"); + } module_left.set(!deleted); deleted }; @@ -1366,7 +1379,7 @@ pub fn specs() -> Vec { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, or its stored module can't be deleted, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", always, remove ), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 75c3b9fe67..a931ab820c 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -876,6 +876,13 @@ impl Session { }) } + /// The grant the attached plug-in store's signed grants file holds for the plug-in `id` (`None` + /// without a folder, and when the file grants nothing: unsigned, unreadable or without an entry + /// for `id`). + pub(crate) fn stored_plugin_grant(&self, id: &str) -> Option { + self.plugin_dir.as_deref().and_then(|dir| stored_grants(dir).remove(id)) + } + /// Does the attached plug-in store hold a module file for the plug-in `id`, loaded or not (one /// that no grant covers is skipped at startup and stays in the folder)? pub(crate) fn holds_stored_plugin(&self, id: &str) -> bool { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 248b5b3d00..e776276647 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4789,6 +4789,45 @@ fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() { assert_eq!(kept_generation(&keys, &folder.0), Some(2), "a valid id's removal still retires signed copies"); } +/// Removing an installed plug-in whose stored module can't be deleted fails, and the plug-in stays +/// installed with its settings and its stored grant; a second removal, once the module can be +/// deleted, removes it. +#[test] +fn removing_an_installed_plugin_whose_module_cant_be_deleted_keeps_it_installed() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-installed-remove-held"); + let id = "test.engine.permissions.installedremoveheld"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert!(module.is_file(), "the module is stored"); + assert!(s.holds_plugin_grant(id), "and its grant"); + let stored_grant = s.stored_plugin_grant(id); + assert!(stored_grant.is_some(), "in the signed grants file"); + let data_dir = crate::store::plugin_data_dir(&folder.0, id); + std::fs::create_dir_all(&data_dir).unwrap(); + let setting = data_dir.join("settings.json"); + std::fs::write(&setting, b"{}").unwrap(); + + // A folder in the module's place can't be deleted as a file. + std::fs::remove_file(&module).unwrap(); + std::fs::create_dir_all(module.join("held")).unwrap(); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains("can't delete"), "{refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed"); + assert!(module.exists()); + assert!(s.stored_plugin_grant(id) == stored_grant, "the stored grant is kept for the next launch"); + assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back"); + + std::fs::remove_dir_all(&module).unwrap(); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal removes it"); + assert!(vectorcraft_plugins::registry::get(id).is_none() && !module.exists() && !data_dir.exists()); + assert!(!s.holds_plugin_grant(id), "and its grant"); +} + /// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same /// key, generation, grants and folder verifies. A key's bytes are never printed. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e4337ecdf9..9b0150849d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13469,7 +13469,9 @@ need a new approval. A refused install keeps the grant. A failed write of the mo grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When `plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed; so does a `plugin.remove` while the system key store can't be reached, also when `grants.json` is missing or doesn't -name the plug-in. For an id that isn't installed, `plugin.remove` also deletes the module stored for it that didn't +name the plug-in. When `plugin.remove` can't delete an installed plug-in's stored module, it returns an error naming +the file, and the plug-in stays installed with its grant kept in the store. For an id that isn't installed, +`plugin.remove` also deletes the module stored for it that didn't load and returns `{removed}`. When the plug-in's settings and cache can't be moved back from their `.removed` folder then either, the error names that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A filter without `doc.write` or `state` that returns output needing them gets an error and the document is unchanged. diff --git a/docs/plugins.md b/docs/plugins.md index 0e5e2d09be..01ea0407e4 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -286,7 +286,8 @@ capability model proposed for PhotoCraft plug-ins hexadecimal digits covers nothing. `plugin.remove` forgets the grant, and so does a successful `plugin.install` of a module that lists no permissions under that id, so the earlier bytes need a new approval. When `plugin.remove` can't remove the grant from `grants.json`, it returns an error, the plug-in stays installed, and a second `plugin.remove` - tries again. A refused install leaves the grant, the plug-in installed with the id, the `Plug-ins` folder and the + tries again. The same happens when it can't delete the plug-in's stored module, and the grant stays in `grants.json`. + A refused install leaves the grant, the plug-in installed with the id, the `Plug-ins` folder and the list of disabled plug-ins as they are. When another session installs a plug-in with the id or changes its grant while `plugin.install` checks a module, the install is refused, before anything is written to the `Plug-ins` folder, if the other plug-in would need `replace: true` or the changed grant no longer approves the module. A From 0ea397db724e3772f49e25ec55a09fe2181b98d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 06:05:04 -0800 Subject: [PATCH 048/107] Scripts: Fit Artboard to artwork bounds does nothing on a locked or empty artboard app.executeMenuCommand('Fit Artboard to artwork bounds') threw the command's error when the active artboard was locked or had no art on it. The canvas's right-click menu dims Fit to Artwork Bounds then (DocState::any_art_to_fit), so the script now does nothing and adds no undo step, as for the other menu items that are not available. The docs state that an available menu item runs its command and that an error that command returns throws. The host-versus-checker name table lists Application.prototype.executeMenuCommand. --- crates/engine/src/script/dom.rs | 13 +++++++++++-- crates/engine/src/tests/script_dom.rs | 13 +++++++++++++ .../engine/tests/it/script_host_vs_scriptcheck.rs | 4 ++-- docs/mcp.md | 4 +++- 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b7873009b9..67f181e7e0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -795,7 +795,10 @@ const MENU_COMMANDS: &[(&str, &str)] = &[ /// describes the method. A /// name it does not list throws an error that names it. A menu item that is not available, with /// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does -/// (VectorCraft's own rule). `Fit Artboard to artwork bounds` fits the active artboard. +/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error +/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does +/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims +/// the item then ([`DocState::any_art_to_fit`]). fn app_menu_command(h: &Host, a: &[Data]) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) }; if name.len() > MAX_TEXT_BYTES { @@ -811,7 +814,13 @@ fn app_menu_command(h: &Host, a: &[Data]) -> Answer { return Ok(Data::Undefined); } match (id, s.active()) { - ("artboard.fitToArt", Some(st)) => json!({"index": active_artboard(st)}), + ("artboard.fitToArt", Some(st)) => { + let index = active_artboard(st); + if !st.any_art_to_fit(&[index]) { + return Ok(Data::Undefined); + } + json!({"index": index}) + } _ => json!({}), } }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 108cc647dc..6474d1e1fc 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1394,6 +1394,19 @@ fn the_fit_to_artwork_menu_command_fits_the_artboard_to_the_art() { log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds');"); let after = s.active().unwrap().doc.artboards[0].rect; assert!(after.width() < before.width() && after.height() < before.height(), "{before:?} -> {after:?}"); + // An artboard that is locked, or has no art on it, leaves the menu item dimmed: it does nothing. + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let steps = undo_steps(&s); + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, before); + assert_eq!(undo_steps(&s), steps, "locked"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let empty = s.active().unwrap().doc.artboards[0].rect; + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, empty); + assert_eq!(undo_steps(&s), 0, "no art"); } #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 4368ce29b7..d8aa36bdf9 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -82,8 +82,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection selection= toString typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ + getIsFileOpen selection selection= toString typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 471325ae46..596910c197 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2678,7 +2678,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Fit Artboard to artwork bounds` (https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee), which runs `artboard.fitToArt` on the active artboard. Names are matched exactly. Any other name throws an error that names it, and a name that is not a string throws a `TypeError`. VectorCraft's own rule: a menu item that is not - available, with no document open or nothing selected that it acts on, does nothing and adds no undo step. A script may name the application's members without `app.`, as + available, with no document open, nothing selected that it acts on, or a locked active artboard or one with no art + for `Fit Artboard to artwork bounds`, does nothing and adds no undo step. An available menu item runs its command, + and an error that command returns throws. A script may name the application's members without `app.`, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level 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 049/107] 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 050/107] 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 626478c40690c0643fc6fac1962032b4227937f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 09:12:06 -0800 Subject: [PATCH 051/107] Dialogs: Enter runs the default button in Find Font and the perspective grid dialogs Find Font built its dialog without close_on_enter, so Enter in a field did nothing; it now runs Done, as the Effect Gallery and Composite Fonts dialogs do. Define Grid, Save Grid as Preset and the preset editor turned enter_confirms off. The dialog routes Enter to its enabled Accept button, which reports it as the pick of OK, so the held answer is filed as a click files it: Enter defines the grid or saves the preset, a refused name keeps the dialog open, and Enter does nothing while OK is disabled. --- .../ui-egui/src/dialogs/perspective_grid.rs | 1 - .../ui-egui/src/dialogs/tests_perspective.rs | 40 +++++++++++++++++++ crates/ui-egui/src/find_font.rs | 24 ++++++++++- 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index 1afd7dafbf..bed5ab085b 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -482,7 +482,6 @@ impl StackDialog for GridDialog { .opened(Bind::bound(&mut self.open)) .ok_enabled(finish || !self.held.is_waiting()) .accept_stays_open(true) - .enter_confirms(false) .show(ui, |ui, form, draft| { if finish { form.request_close_as(CloseReason::Activated); diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 81ecca1d9b..268694aa6d 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -147,6 +147,46 @@ fn define_grid_loads_and_saves_presets() { assert_eq!(app.session.prefs.perspective_presets.len(), 2); } +/// Enter pressed in the field that has the focus, then the passes that run the filed answer and close the dialog. +fn enter(app: &mut VectorcraftApp) { + let ctx = window(app); + let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + crate::tests::synthetic::key_frame(app, &ctx, vec![key(true)]); + crate::tests::synthetic::key_frame(app, &ctx, vec![key(false)]); + frame(app); + frame(app); +} + +#[test] +fn enter_is_ok_in_define_grid_and_save_grid_as_preset() { + let mut app = app(); + // Define Grid: Enter in the focused field defines the grid and closes the dialog. + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "angle", json!(30)).unwrap(); + frame(&mut app); + frame(&mut app); + assert!(window(&app).memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + enter(&mut app); + assert_eq!(kind(&app), None, "Enter closes Define Grid"); + assert!((grid(&app).viewing_angle() - 30.0).abs() < 1e-9, "Enter defines the grid"); + // Save Grid as Preset: Enter in the name field saves the preset and closes the dialog. + app.run("ui.savePerspectivePreset", json!({})).unwrap(); + frame(&mut app); + frame(&mut app); + assert!(window(&app).memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + enter(&mut app); + assert_eq!(kind(&app), None, "Enter closes Save Grid as Preset"); + assert_eq!(app.session.prefs.perspective_presets.len(), 1, "Enter saves the preset"); + // A name the presets refuse: Enter files it, the refusal shows, and the dialog stays. + app.run("ui.savePerspectivePreset", json!({})).unwrap(); + set(&mut app, "name", json!("[2P-Normal View]")).unwrap(); + frame(&mut app); + frame(&mut app); + enter(&mut app); + assert_eq!(kind(&app).as_deref(), Some(super::perspective_grid::KIND), "a refused name keeps the dialog open"); + assert_eq!(app.session.prefs.perspective_presets.len(), 1); +} + #[test] fn the_presets_manager_creates_edits_and_deletes_presets() { use super::perspective_presets::{self, Action}; diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index cc5e2dda5a..b07e126478 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -511,7 +511,7 @@ impl StackDialog for FindFontDialog { .map_or_else(String::new, |f| format!("{} {} ({})", f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""), f["runs"])) }; let row_text = |at: usize| shown.get(at).and_then(|&i| rows.get(i)).map_or_else(String::new, |r| row_label(&r.family, &r.style)); - let out = Dialog::new(tl!("Find Font").to_string()).buttons(buttons).show(ui, |ui, _| { + let out = Dialog::new(tl!("Find Font").to_string()).buttons(buttons).close_on_enter(true).show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { crate::panels::section(heading.clone()).show(ui, |ui, _| { let docs = Lines { len: count, text: &doc_text }; @@ -1463,6 +1463,28 @@ mod tests { assert_eq!(row(&app)["status"], "missing"); } + /// Enter in the field that has the focus is Done: the dialog closes, and no Find or Change runs. + #[test] + fn enter_is_done() { + let mut app = new_app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Inter"})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let is_open = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::().is_some()); + open(&mut app); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + assert!(is_open(&app)); + assert!(ctx.memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + let undo = app.session.active().unwrap().history.undo.len(); + let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![key(true)]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![key(false)]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + assert!(!is_open(&app), "Enter closes Find Font"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "Enter changes no font"); + } + /// Another document in front, and pattern editing entered and canceled, each give the list of /// the document in front as it is then. #[test] From 5a54b17194895f89714a39675b938f19b03937e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 09:40:33 -0800 Subject: [PATCH 052/107] Gradient panel: rows wrap so the panel stays inside its dock column Rows of side-by-side controls in the Gradient panel did not wrap, so the panel's column grew wider than the panel and controls ran past its right edge. Docked, the Type buttons, Repeats, the gradient slider and the notice reached up to 10.5 pt past the panel in English and 13.9 pt in French. At the narrowest panel width (220 pt), Method, Spread, Repeats, Location and Delete Stop ran 23.5 to 100.5 pt past it. - The header places the type buttons and Edit Gradient beside the thumbnail, level with its top, or under it when the panel is too narrow. - The Type, Method and Spread rows wrap. - The stop row wraps, and each caption stays with its field. A wide panel draws every control where it did before. --- crates/ui-egui/src/panels/gradient.rs | 102 +++++++------ crates/ui-egui/src/panels/gradient/tests.rs | 153 ++++++++++++++++++++ 2 files changed, 212 insertions(+), 43 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 8f9d83a4b1..0a92cde57f 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -25,7 +25,7 @@ //! gradient behind the active proxy, keeping its placement (`gradient.presets.*`). Hide Presets in //! the panel menu leaves the row out. -use craft::behavior::{EditEvent, IconId, Mixed}; +use craft::behavior::{ColumnWidth, EditEvent, IconId, Mixed}; use craft::color_ui::gradient::stops::AltDrop; use craft::color_ui::ui::DropperButton; use craft::color_ui::ui::gradient::{ColorStop, GradientEditor, GradientStops, StopDrop, StopRef, StopRow, StopRows, StopRules}; @@ -35,7 +35,8 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Checkbox, Radio, RadioGroup, Segmented, Swatch}; use craft::ui::contract::{Bind, EditResponse, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::{Divider, Icon, Shade, Text}; -use craft::ui::layout_components::{Row, Stack}; +use craft::ui::layout::CellAlign; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; @@ -66,6 +67,9 @@ use crate::panel_drag::PanelDrag; /// The Angle field's preset menu, degrees. const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0]; +/// The header's columns: the thumbnail with its swatch menu, and the type buttons with Edit Gradient, each as wide +/// as its content. +const BESIDE: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; /// The Aspect Ratio field's preset menu, percent. const ASPECT_PRESETS: [f64; 9] = [10.0, 25.0, 50.0, 75.0, 100.0, 150.0, 200.0, 300.0, 400.0]; // PLAN: the sheet drops `HIDE_OPTIONS` and `HIDE_PRESETS`, but each key is read by `show`, `menu_states` and `run`; kept as the op.A5 hide-store keys. @@ -171,7 +175,7 @@ pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) { (GradientKind::Diamond, "dc-grad-diamond", tl!("Diamond Gradient")), (GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")), ]); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Type:")).shade(Shade::Muted).show(ui); let pick = Segmented::new(tl!("Type"), lit(kind), &entries).show(ui); if let Some(k) = pick.events.committed() { @@ -302,19 +306,23 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let kind = g.gradient.kind; let hidden = part_hidden(app, HIDE_OPTIONS); // Header: the thumbnail and its swatch menu, the type buttons and Edit Gradient. - Row::new().show(ui, |ui, _| { - fill_box(app, ui, &g, is_grad); - if hidden { + if hidden { + Row::new().show(ui, |ui, _| { + fill_box(app, ui, &g, is_grad); super::proxy(app, ui); - return; - } - Stack::new().show(ui, |ui, _| { - type_row(app, ui); - if Button::new(tl!("Edit Gradient")).show(ui).clicked() { - app.select_tool("gradient"); - } }); - }); + } else { + // The type buttons go beside the thumbnail, level with its top, or under it in a narrow panel. + Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| fill_box(app, ui, &g, is_grad)); + Stack::new().show(ui, |ui, _| { + type_row(app, ui); + if Button::new(tl!("Edit Gradient")).show(ui).clicked() { + app.select_tool("gradient"); + } + }); + }); + } let freeform = is_grad && kind == GradientKind::Freeform; if hidden { if !freeform { @@ -442,7 +450,7 @@ fn method_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr ] .map(|(m, label)| Entry::new(m, label)); let current = g.gradient.method; - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Method:")).shade(Shade::Muted).show(ui); let pick = Select::new(tl!("Method"), Bind::given(current), &methods).enabled(is_grad).show(ui); if let Some(m) = pick.events.committed().filter(|m| **m != current) { @@ -459,7 +467,7 @@ fn spread_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr .map(|(s, label)| Entry::new(s, label)); let current = g.gradient.spread; let presets = number_presets(&REPEAT_PRESETS, ""); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Spread:")).shade(Shade::Muted).show(ui); let pick = Select::new(tl!("Spread"), Bind::given(current), &spreads).enabled(is_grad).show(ui); if let Some(s) = pick.events.committed().filter(|s| **s != current) { @@ -667,34 +675,42 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo } }); } - Row::new().show(ui, |ui, _| { - Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui); - let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0); - let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); - apply_number(app, &opacity.edit, |app, v, phase| { - let Some(i) = sel else { return }; - let mut v2 = stops.clone(); - if let Some(s) = v2.get_mut(i) { - s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32; - } - set_stops(app, &v2, Some(i), phase); + // In a narrow panel the row wraps; each caption stays on the line of its field. + Row::new().wrap(true).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui); + let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0); + let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); + apply_number(app, &opacity.edit, |app, v, phase| { + let Some(i) = sel else { return }; + let mut v2 = stops.clone(); + if let Some(s) = v2.get_mut(i) { + s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32; + } + set_stops(app, &v2, Some(i), phase); + }); }); - Text::new(tl!("Location:")).shade(Shade::Muted).show(ui); - let loc = match (mid, stop) { - (Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)), - (None, Some(s)) => percent(s.offset), - _ => 0.0, - }; - let location = - NumberField::new(tl!("Location"), Bind::given(Some(loc))).range(0.0..=100.0).unit("%").enabled(sel.is_some() || mid.is_some()).show(ui); - apply_number(app, &location.edit, |app, v, phase| { - let v = (v / 100.0) as f32; - if let Some(m) = mid { - set_stops(app, &set_midpoint(stops, m, v), None, phase); - } else if let Some(i) = sel { - let (v2, ni) = move_stop(stops, i, v); - set_stops(app, &v2, Some(ni), phase); - } + Row::new().show(ui, |ui, _| { + Text::new(tl!("Location:")).shade(Shade::Muted).show(ui); + let loc = match (mid, stop) { + (Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)), + (None, Some(s)) => percent(s.offset), + _ => 0.0, + }; + let location = NumberField::new(tl!("Location"), Bind::given(Some(loc))) + .range(0.0..=100.0) + .unit("%") + .enabled(sel.is_some() || mid.is_some()) + .show(ui); + apply_number(app, &location.edit, |app, v, phase| { + let v = (v / 100.0) as f32; + if let Some(m) = mid { + set_stops(app, &set_midpoint(stops, m, v), None, phase); + } else if let Some(i) = sel { + let (v2, ni) = move_stop(stops, i, v); + set_stops(app, &v2, Some(ni), phase); + } + }); }); let can_del = sel.is_some() && stops.len() > MIN_STOPS; let delete = IconButton::new(IconId::new("trash-2")).label(tl!("Delete Stop")).tooltip(tl!("Delete Stop")).enabled(can_del).show(ui); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 4324e20f49..6d02ba22cd 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -335,3 +335,156 @@ fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() { assert_eq!(current(&app), paint, "the stop keeps its color"); assert_eq!(app.session.active().unwrap().selection.objects, selected, "the selection stays"); } + +// ---------- the panel in the app window ---------- + +/// Where the panel is shown in the app window. +#[derive(Clone, Copy, Debug)] +enum Place { + /// Docked in its column. + Docked, + /// Floating, this many points wide. + Floating(f32), +} + +/// The Gradient panel as one frame of the app window drew it. +struct Shown { + /// The panel's body. + body: egui::Rect, + /// The name and rect of every named node in the body. + nodes: Vec<(String, egui::Rect)>, + /// Each catalog string asked for, as the panel's language shows it. + names: Vec<(&'static str, String)>, +} + +impl Shown { + /// The rects of the nodes named `name` (a catalog string asked for). + fn rects(&self, name: &str) -> Vec { + let shown = self.names.iter().find(|(asked, _)| *asked == name).map_or(name, |(_, shown)| shown.as_str()); + let found: Vec = self.nodes.iter().filter(|(label, _)| label == shown).map(|(_, r)| *r).collect(); + assert!(!found.is_empty(), "the panel shows no {shown:?}"); + found + } + + /// The nodes that reach past either side of the body, each with its rect. + fn past(&self, nodes: impl IntoIterator) -> Vec { + let outside = |r: &egui::Rect| r.left() < self.body.left() - 0.5 || r.right() > self.body.right() + 0.5; + nodes.into_iter().filter(|(_, r)| outside(r)).map(|(name, r)| format!("{name} at {r:?}")).collect() + } + + /// The vertical middles of the nodes named `names`. + fn middles(&self, names: &[&str]) -> Vec { + names.iter().flat_map(|name| self.rects(name)).map(|r| r.center().y).collect() + } +} + +/// A selected gradient stop: the panel shows its Color row. +fn select_a_stop(app: &mut VectorcraftApp) { + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); +} + +/// The Gradient panel shown at `place` in the whole app window (1440 by 900 pt) over a selected rectangle that +/// `setup` paints, drawn in `lang`, with the catalog strings `names` as `lang` shows them. +fn shown(lang: &str, place: Place, setup: fn(&mut VectorcraftApp), names: &[&'static str]) -> Shown { + use egui::accesskit::{Node, NodeId, Role}; + let mut app = super::super::tests_appearance::app_with_rect(); + setup(&mut app); + app.session.prefs.interface_language = lang.into(); + app.run("window.panel", json!({ "panel": "gradient" })).unwrap(); + match place { + Place::Docked => app.run("window.panel.dock", json!({ "panel": "gradient" })).unwrap(), + Place::Floating(width) => { + app.run("window.panel.float", json!({ "panel": "gradient", "x": 520, "y": 120, "width": width, "height": 700 })).unwrap() + } + }; + app.run("window.panel.activate", json!({ "panel": "gradient" })).unwrap(); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut nodes: Vec<(NodeId, Node)> = Vec::new(); + for at in 1..=8 { + let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; + let out = crate::testing::app_frame(&mut app, &ctx, input); + nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); + } + // The frames set the language from the preference; the names are looked up in it before English is put back. + let names: Vec<(&'static str, String)> = names.iter().map(|name| (*name, crate::i18n::t(name).to_owned())).collect(); + let fill = crate::i18n::t("Gradient Fill").to_owned(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let rect = + |node: &Node| node.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 by_id: std::collections::HashMap = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let under = |root: NodeId| { + let mut found = Vec::new(); + let mut todo = vec![root]; + while let Some(id) = todo.pop() { + let Some(node) = by_id.get(&id) else { continue }; + if let (Some(label), Some(r)) = (node.label(), rect(node)) { + found.push((label.to_owned(), r)); + } + todo.extend(node.children().iter().copied()); + } + found + }; + // The panel's body: the tab panel that holds the Gradient Fill box. + let (body, nodes) = nodes + .iter() + .filter(|(_, n)| n.role() == Role::TabPanel) + .filter_map(|(id, n)| Some((rect(n)?, under(*id)))) + .find(|(_, named)| named.iter().any(|(l, _)| *l == fill)) + .unwrap_or_else(|| panic!("no Gradient panel at {place:?} in {lang}")); + Shown { body, nodes, names } +} + +/// Docked, every control of the panel stays inside its column, with a solid fill (the panel shows its notice) and +/// with a stop selected (its Color row), in languages with longer words. +#[test] +fn the_gradient_panel_stays_inside_its_dock_column() { + for lang in ["en", "fr", "de"] { + for setup in [|_: &mut VectorcraftApp| {}, select_a_stop] { + let panel = shown(lang, Place::Docked, setup, &[]); + let past = panel.past(panel.nodes.clone()); + assert!(past.is_empty(), "past the docked panel in {lang}: {past:?}"); + } + } +} + +/// In a panel at the narrowest panel width the Type, Method, Spread and stop rows wrap: their controls stay inside +/// the panel. +#[test] +fn the_gradient_rows_wrap_in_a_narrow_panel() { + let names = [ + "Linear Gradient", + "Radial Gradient", + "Conic Gradient", + "Diamond Gradient", + "Edit Gradient", + "Method", + "Spread", + "Repeats", + "Opacity", + "Location", + "Delete Stop", + ]; + for lang in ["en", "fr"] { + let panel = shown(lang, Place::Floating(crate::panel_docking::PANEL_MIN_WIDTH), select_a_stop, &names); + let past = panel.past(names.iter().flat_map(|name| panel.rects(name).into_iter().map(|r| (name.to_string(), r)))); + assert!(past.is_empty(), "past the panel in {lang}: {past:?}"); + } +} + +/// In a wide panel the rows stay on one line each, and the thumbnail stays level with the top of the type buttons. +#[test] +fn the_gradient_rows_stay_on_one_line_in_a_wide_panel() { + let rows: [&[&str]; 3] = + [&["Method:", "Method"], &["Spread:", "Spread", "Repeats"], &["Opacity:", "Opacity", "Location:", "Location", "Delete Stop"]]; + let names: Vec<&'static str> = rows.iter().flat_map(|row| row.iter().copied()).chain(["Gradient Fill", "Linear Gradient"]).collect(); + let panel = shown("en", Place::Floating(400.0), select_a_stop, &names); + for row in rows { + let middles = panel.middles(row); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{row:?} is not on one line: {middles:?}"); + } + let (thumb, linear) = (panel.rects("Gradient Fill")[0], panel.rects("Linear Gradient")[0]); + assert!((thumb.top() - linear.top()).abs() < 1.0, "the thumbnail {thumb:?} is not level with the type buttons {linear:?}"); +} From 77a12e40bb8b745079588b42b77f95c4caeaf0c2 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:13:46 +0530 Subject: [PATCH 053/107] Fix floating document raise after Presentation Mode --- crates/ui-egui/src/doc_windows.rs | 9 ++++- crates/ui-egui/src/doc_windows/tests.rs | 47 ++++++++++++++++--------- 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 9c65f48e24..216d3b65b9 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -335,6 +335,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Presentation Mode fits each floating window it shows to the main window: back in their // floating windows, those views fit their windows again. let presenting = presenting(app); + let restoring = !presenting && app.canvas.windows.presented.is_some(); if presenting { let is_floating = current.is_some_and(|k| floating(app, &k)); let shown = app.canvas.windows.presented.get_or_insert_default(); @@ -365,9 +366,15 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { return; } let raise = current.filter(|u| app.canvas.windows.current != Some(*u)); - app.canvas.windows.current = current; let ctx = ui.ctx().clone(); let os_windows = WindowHost::of(&ctx).viewports_available(); + if restoring && !os_windows && raise.is_some() { + // egui raises every reappearing area in this pass, preserving their old order. Repeat + // the current window's raise next frame, when the other windows no longer request it. + ctx.request_repaint(); + } else { + app.canvas.windows.current = current; + } // An OS window's place is in desktop points: the main window's own origin shifts it. let origin = if os_windows { ctx.input(|i| i.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO).to_vec2() diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 3e8ffbff5b..931813e14a 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -417,23 +417,36 @@ fn presentation_mode_shows_the_floating_current_document_in_the_main_window() { #[test] fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { - let mut app = app_with(2); - let ctx = crate::testing::ui_context(); - frame(&mut app, &ctx, vec![]); - app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - // Where the two windows overlap: document 1's title bar, over document 0's body. - let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("document.activate", json!({"index": 0})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - click(&mut app, &ctx, overlap); - assert_eq!(app.session.active_index(), Some(0), "document 0's window is in front where they overlap"); + for change_during_presentation in [false, true] { + let mut app = app_with(2); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + // Where the two windows overlap: document 1's title bar, over document 0's body. + let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); + // Cover both an unchanged current document and one chosen while the windows are hidden. + if !change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + if change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, overlap); + assert_eq!( + app.session.active_index(), + Some(0), + "document 0's window is in front (changed during presentation: {change_during_presentation})" + ); + } } /// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks From ef2409fb318cafdc6493bf235ff7daf18eedbfe3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 09:49:18 -0800 Subject: [PATCH 054/107] Script checker: a Folder variable in parentheses is still a Folder object `(d).write(s)` and `(d).length = 0` on a variable holding `new Folder(p)` counted as file writes, while `d.write(s)` and `d.length = 0` did not. Grouping parentheses now keep what the variable holds, so a Folder variable in them is left out the same way. A variable that may hold a File object still counts, and a grouped assignment (`x = (d)`) still gives `x` a value that may be a File object. --- crates/scriptcheck/src/analyze.rs | 21 ++++++++++++--------- crates/scriptcheck/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 01dc0dfbb2..0e331057d7 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -338,18 +338,19 @@ impl Operand { /// object: `[new] File|Folder(…)`, `new File|Folder`, `File.openDialog(…)`, `File.saveDialog(…)`, /// `Folder.selectDialog(…)`, `Folder.` ([`catalog::FOLDER_PLACES`]) or a variable holding /// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a - /// File or Folder object. + /// File or Folder object, `Some(true)` when it counts as a Folder object whatever the path names. /// - /// Only `new Folder(…)`, `new Folder` and `Folder.` are Folder objects whatever the path - /// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)` - /// gives a File or Folder object for what the user picks, `Folder.current` is the one place a - /// script can assign, and a variable another variable was assigned to may hold a File object. - fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand { + /// Only `new Folder(…)`, `new Folder`, `Folder.` and such a variable are Folder objects + /// whatever the path names. `Folder(…)` gives a File object when the path names a file, + /// `Folder.selectDialog(…)` gives a File or Folder object for what the user picks, and + /// `Folder.current` is the one place a script can assign. A variable another variable is assigned + /// may hold a File object, so a grouped value passes `Some(false)` for any variable. + fn file_step(self, t: &Sig, file: bool, alias: Option) -> Operand { match self { Operand::Start if t.word("new") => Operand::New, Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER }, Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER }, - Operand::Start if alias => Operand::Done(Held::File { folder: false }), + Operand::Start if alias.is_some() => Operand::Done(Held::File { folder: alias == Some(true) }), Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder }, Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false }, Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder }, @@ -1378,7 +1379,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = self.alias(t); + let alias = self.alias(t).then_some(false); let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return }; if after < g.level { // The `)` of the innermost pair: the operand, when complete, is the pair's value and the @@ -1436,7 +1437,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn paren_step(&mut self, t: &Sig<'s>, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = self.alias(t); + // A variable in grouping parentheses is the object it holds now, as it is outside them + // ([`Analyzer::held_file`]). + let alias = self.alias(t).then(|| self.folder(t.text)); if let Some(p) = self.parens.last_mut() { if before == p.level { p.operand = match std::mem::replace(&mut p.operand, Operand::Other) { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 45f5d02d02..dd11c3dd0a 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -619,6 +619,25 @@ fn file_only_calls_on_a_folder_do_nothing() { assert_eq!(lines("file.dialog"), [8]); } +/// A variable holding a Folder object is the same object in grouping parentheses, so `(d).write(s)` +/// and `(d).length = 0` do nothing, as `d.write(s)` and `d.length = 0` do. A variable that may hold +/// a File object still counts in them. +#[test] +fn a_folder_in_parentheses_is_still_a_folder() { + let r = report(concat!( + "var d = new Folder(p);\n", + "(d).write(s); ((d)).copy(q); (d).open('r'); (d).length = 0;\n", + "var f = new File(p);\n", + "(f).write(s);\n", + "var g = Folder(p); (g).open('r');\n", + )); + let lines = |id: &str| feature(&r, id).map(|f| f.lines.clone()).unwrap_or_default(); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[4][..])]); + assert_eq!(lines("file.write"), [4]); + assert_eq!(lines("file.read"), [5]); +} + /// A File object assigned to a function's own variable, its parameter or a `catch` block's /// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter /// starts without what the outer variable of the same name was assigned. From 69b627ddc787ff5ac1605e0c3e77d1319b70c42a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:07:41 -0800 Subject: [PATCH 055/107] Scripts: Other Script's warning runs the script under the file access of the request that asked The warning before a script runs (ui.runScript) now keeps the automation roots and the automation flag in force when it was asked, and Run runs script.run under them, narrowed to any roots in force when it is answered. A request confined to its roots could otherwise open the warning for a script outside them and have it run, with full file access, once Run was pressed. --- crates/ui-egui/src/dialogs/script_run.rs | 14 +++++++-- crates/ui-egui/src/tests/script_run.rs | 40 ++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..2dec50814d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -42,6 +42,7 @@ use craft::ui::text::TextField; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; +use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; @@ -82,6 +83,11 @@ crate::dialogs::confirm::wrapped_dialog!(CloseQuestion, StandardPrompt, CLOSE_KI /// The tag of the warning: the params `script.run` takes once the warning is answered. struct RunWarning { params: Value, + /// The automation roots in force when asked: the script runs under them, and under any in force + /// when the warning is answered. + scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the script runs as automation. + automated: bool, } /// What a script's `alert`, `confirm` or `prompt` dialog answers with. @@ -473,7 +479,7 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result() + && let Some(RunWarning { params, scope, automated }) = answer.take_tag::() { let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) }; - if let Err(e) = stored.and_then(|()| app.run("script.run", params).map(drop)) { + let run = |app: &mut VectorcraftApp| app.run("script.run", params).map(drop); + let automated = automated || app.automation_asked(); + if let Err(e) = stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run))) { app.status(e); } } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4022cb7c65..42d47ab1cd 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -103,6 +103,46 @@ fn a_run_goes_frame_by_frame_and_is_one_undo_step() { let _ = std::fs::remove_dir_all(&dir); } +/// The warning automation asked while confined to a folder: Run runs the script as automation's, +/// with that folder still the only place it may read. +#[test] +fn the_warning_runs_the_script_under_the_access_it_was_asked_with() { + let mut app = app(); + let (inside, outside) = (folder("scope-in"), folder("scope-out")); + let path = outside.join("draw.js"); + std::fs::write(&path, DRAW).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + vectorcraft_engine::file_access::confine(roots.as_ref(), || { + crate::file_asks::as_automated(&mut app, true, |app| { + menus::run_ui_command(app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + }) + }); + assert!(confirm(&mut app, KIND)); + assert!(app.ui.status.contains("outside the read root"), "the script outside the folder is refused: {}", app.ui.status); + assert!(!app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(&inside); + let _ = std::fs::remove_dir_all(&outside); +} + +/// The warning a person asked, answered by automation confined to a folder: the script runs with +/// that folder still the only place it may read. +#[test] +fn the_warning_answered_under_narrower_access_keeps_it() { + let mut app = app(); + let (inside, outside) = (folder("narrow-in"), folder("narrow-out")); + let path = outside.join("draw.js"); + std::fs::write(&path, DRAW).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + assert!(vectorcraft_engine::file_access::confine(roots.as_ref(), || confirm(&mut app, KIND))); + assert!(app.ui.status.contains("outside the read root"), "the script outside the folder is refused: {}", app.ui.status); + assert!(!app.session.script_running()); + let _ = std::fs::remove_dir_all(&inside); + let _ = std::fs::remove_dir_all(&outside); +} + #[test] fn do_not_show_again_is_remembered_and_the_script_still_runs() { let mut app = app(); From 5d5777078ba54a6f4a23fe386f5ee26e836d0d42 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:33:41 -0800 Subject: [PATCH 056/107] Dialogs: Enter runs the default button in Recolor Artwork and Graph Data Recolor Artwork and Graph Data turned enter_confirms off, so Enter in a field that does not use Enter did nothing. The dialog now routes that Enter to its enabled OK button, the same path a click takes, and the held answer is filed: in Recolor Artwork, Enter is OK and the dialog closes; in Graph Data, Enter is Apply and the window stays open. The Graph Data entry box and the sheet still take Enter to move the picked cell down, and nothing is applied. Enter does nothing while OK is disabled. --- crates/ui-egui/src/dialogs/graph_data.rs | 36 ++++++++++++++++++- crates/ui-egui/src/dialogs/recolor.rs | 5 +-- crates/ui-egui/src/dialogs/recolor/fixture.rs | 5 +++ crates/ui-egui/src/tests/recolor.rs | 19 ++++++++++ 4 files changed, 60 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 85bb9503c1..2ac4764bf5 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -712,7 +712,6 @@ impl StackDialog for GraphDataDialog { .ok_label(tl!("Apply")) .ok_enabled(!held.is_waiting()) .accept_stays_open(true) - .enter_confirms(false) // The sheet owns the scroll; the controls above it stay in view. .collection_body(true) .shaped(|dialog| dialog.initial_focus(Initial::Default)) @@ -1015,6 +1014,41 @@ mod tests { assert!(app.dialogs().is_some_and(|d| d.with(|host| host.is_open::()))); } + /// Enter in the entry box and in the sheet moves the picked cell down and applies nothing. Enter in a field that + /// does not use it is Apply: the graph is redrawn and the window stays open. + #[test] + fn enter_moves_in_the_entry_box_and_the_sheet_and_applies_elsewhere() { + let (mut app, id) = app_with(",a,b\nQ1,1,2\nQ2,3,4\nQ3,5,6", "column"); + let before = data(&mut app, id); + open(&mut app).unwrap(); + set_field(&app, "sel", json!([1, 1])).unwrap(); + let mut h = harness(app); + h.run_steps(4); + // The entry box. + h.get_by_label("Cell Value").click(); + h.run_steps(2); + edit(h.state(), |d| d.entry.text = "9".into()); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(read(h.state(), |d| (active(&d.state), cell_of(&d.sheet.grid, 1, 1))), ((2, 1), "9".to_string()), "Enter moves down"); + assert_eq!(data(h.state_mut(), id), before, "Enter in the entry box applies nothing"); + // The sheet. + h.get_by_label("Q1").click(); + h.run_steps(2); + assert_eq!(read(h.state(), |d| active(&d.state)), (1, 0), "the click picks the cell"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(read(h.state(), |d| active(&d.state)), (2, 0), "Enter moves down in the sheet"); + assert_eq!(data(h.state_mut(), id), before, "Enter in the sheet applies nothing"); + // A field that does not use Enter. + h.get_by_label("Column Width").click(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(4); + assert_eq!(data(h.state_mut(), id)["rows"][0][0], json!(9.0), "Enter applies the sheet"); + assert!(h.state().dialogs().is_some_and(|d| d.with(|host| host.is_open::())), "the window stays open"); + } + #[test] fn the_entry_box_writes_its_text_and_moves_the_picked_cell() { let (mut app, id) = app_with(",a,b\nQ1,1,2", "column"); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 9d2ca82832..82131dc76e 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1807,10 +1807,7 @@ impl RecolorDialog { let mut preview = self.fields.bool("preview"); let footer = ResetFooter::new(ui, None, true); let RecolorDialog { fields, feed, filed, ends, row_menu, .. } = self; - // PLAN: Enter is not OK here: a form whose OK stays open closes on Enter without reporting it as its OK - // (form_dialogs/form.rs:429, :534), which would close a held dialog unanswered; the forms owner makes - // `FormDialog` report Enter as the pick of OK when `accept_stays_open` is on. - let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).enter_confirms(false).ok_enabled(!waiting); + let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).ok_enabled(!waiting); if art { form = form.preview(Some(Bind::bound(&mut preview))); } diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs index a773d34093..b254285a5b 100644 --- a/crates/ui-egui/src/dialogs/recolor/fixture.rs +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -103,6 +103,11 @@ impl Recolor { self } + /// The widget that has the keyboard focus. + pub(crate) fn focused(&self) -> Option { + self.fixture.focused() + } + /// Sets `field` as `ui.dialog.set` does, before the next frame; a refused value leaves the /// dialog as it was. pub(crate) fn set(&mut self, field: &str, value: Value) -> Result<(), String> { diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 6ab2abd049..7cacc655d8 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -235,6 +235,25 @@ fn the_dialog_reduces_previews_and_applies_as_one_undo_step() { assert_eq!(colors(&mut r.app()), 5); } +/// Enter in the field that has the focus is OK: the color group is made with the name typed, and the dialog closes. +#[test] +fn enter_in_a_field_is_ok() { + let mut r = open(app(), json!({"colors": ["#ff8000", "#0080ff"]})); + r.settled(); + r.set("groupName", json!("Enter Group")).unwrap(); + r.settled(); + r.click_label("Color Group:"); + r.settled(); + assert!(r.focused().is_some(), "a field of the dialog has the focus"); + let groups = r.app().session.doc().unwrap().doc.swatch_groups.len(); + key(&mut r, Key::Enter); + assert!(!r.is_open(), "Enter closes Recolor Artwork"); + let app = r.app(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), groups + 1, "Enter makes the color group, as OK does"); + assert_eq!(doc.swatch_groups.last().map(|g| g.name.as_str()), Some("Enter Group")); +} + #[test] fn presets_open_colour_jobs_and_libraries_and_both_tabs_draw() { let mut app = app(); From 575f12bffac0140ded13dd6b59ca15cefd20aa43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 05:32:47 -0800 Subject: [PATCH 057/107] 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 4217560cde4aac6422c10afc026221e7b5a25062 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:58:29 -0800 Subject: [PATCH 058/107] Fill Area: ids that name what holds the isolated group take its paths In isolation mode, shapeBuilder.copyRegion with ids already takes every path of the isolated layer or group when ids lists it, or a layer or group that holds it, and ignores the other listed objects. The params text and docs/mcp.md said only the listed objects inside it counted. They now describe that case, and a new engine test pins it. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/tests/fill_area.rs | 33 ++++++++++++++++++++++++++++ docs/mcp.md | 7 +++--- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 5ab9da102c..426f374a5c 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Fill Area", [], None, - "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", + "{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}", has_doc, sb_copy_region ), diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 6703d4f928..0471447010 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -305,6 +305,39 @@ fn fill_area_stays_inside_the_isolated_group() { assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer()); } +/// In isolation mode, `ids` naming the isolated group, or the layer or a group that holds it, takes +/// every path of the isolated group. The other paths of that layer or group, and other listed +/// objects outside the isolated group, do not bound areas. +#[test] +fn fill_area_ids_naming_what_holds_the_isolated_group_take_its_paths() { + let mut s = session(); + let outside = + [line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))]; + let lines = triangle(&mut s); + let ids: Vec = lines.iter().map(|l| l.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let outer = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + deselect(&mut s); + let layer = s.doc().unwrap().doc.default_layer().unwrap(); + let (undo, kids) = (undo_len(&s), stack(&s)); + for named in [vec![layer.0], vec![outer.0], vec![g.0], vec![layer.0, outside[0].0]] { + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named})); + assert!(r.is_err(), "the area outside the isolated group, ids {named:?}"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids.clone())); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).unwrap(); + let new = id_of(&r); + assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g), "ids {named:?}"); + assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new)); + s.execute("edit.undo", &json!({})).unwrap(); + } + let named: Vec = outside.iter().map(|l| l.0).collect(); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).is_err(), "only art outside it listed"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + /// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and /// changes nothing: the compound path cannot hold the new path. The same goes for an isolated /// Objects on Path group, a group with a Transform effect and a group that is a clipping mask. diff --git a/docs/mcp.md b/docs/mcp.md index 3a496a84df..916b251c98 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14074,9 +14074,10 @@ The new path takes the current fill, stroke and stroke weight (`fill` and `strok above the front-most object along the area (one whose outline touches the area's outline, or that covers it) and is selected. When a group, Live Paint group, Shaper group or clipping group holds that object, the new path goes above the outermost group in its layer, not inside it, and the group keeps its members. In isolation mode only the paths in -the isolated layer or group bound areas, for the tool's hover and click and for the command (with `ids`, only the -paths of the listed objects that are in it), and the new path goes inside the isolated layer or group, directly above -the object in it that holds that path. No area is found while the isolated object is not a layer or group (a path +the isolated layer or group bound areas, for the tool's hover and click and for the command. With `ids`, the paths +of the listed objects that are in it bound areas, and all of its paths do when `ids` lists the isolated layer or group +or a layer or group that holds it; the other listed objects are ignored. The new path goes inside the isolated layer +or group, directly above the object in it that holds that path. No area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope. A point in no enclosed area is the error "Fill Area: no enclosed area under the pointer" and records no undo From 387b912010e5844e02fcb2fa0e143dc2f8656d70 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:34:06 -0800 Subject: [PATCH 059/107] 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 060/107] 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 d30f0d863e153e2ee4ac11ecc1e9f09c5a944ed7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:01:44 -0800 Subject: [PATCH 061/107] Gradient: measure Freeform Gradient in the narrow-panel test The narrow-panel test now measures the fifth Type button and holds it to the 2 pt it reaches past the panel at the narrowest width, since `Segmented` keeps its segments on one line. The doc comment states the overflow instead of saying the whole Type row stays inside the panel. --- crates/ui-egui/src/panels/gradient/tests.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 6d02ba22cd..1c84ceb68a 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -451,9 +451,13 @@ fn the_gradient_panel_stays_inside_its_dock_column() { } /// In a panel at the narrowest panel width the Type, Method, Spread and stop rows wrap: their controls stay inside -/// the panel. +/// the panel, except the last type button. The five type buttons are one `Segmented` control, which keeps its +/// segments on one line, so at this width Freeform Gradient reaches 2 pt past the panel's right edge. The test +/// holds that button to the 2 pt until the widget can wrap its segments. #[test] fn the_gradient_rows_wrap_in_a_narrow_panel() { + /// How far Freeform Gradient reaches past the panel's right edge at the narrowest width. + const TYPE_OVERFLOW: f32 = 2.0; let names = [ "Linear Gradient", "Radial Gradient", @@ -468,9 +472,14 @@ fn the_gradient_rows_wrap_in_a_narrow_panel() { "Delete Stop", ]; for lang in ["en", "fr"] { - let panel = shown(lang, Place::Floating(crate::panel_docking::PANEL_MIN_WIDTH), select_a_stop, &names); + let asked: Vec<&'static str> = names.iter().copied().chain(["Freeform Gradient"]).collect(); + let panel = shown(lang, Place::Floating(crate::panel_docking::PANEL_MIN_WIDTH), select_a_stop, &asked); let past = panel.past(names.iter().flat_map(|name| panel.rects(name).into_iter().map(|r| (name.to_string(), r)))); assert!(past.is_empty(), "past the panel in {lang}: {past:?}"); + for freeform in panel.rects("Freeform Gradient") { + let inside = freeform.left() >= panel.body.left() - 0.5 && freeform.right() <= panel.body.right() + TYPE_OVERFLOW + 0.5; + assert!(inside, "Freeform Gradient at {freeform:?} is more than {TYPE_OVERFLOW} pt past {:?} in {lang}", panel.body); + } } } From 0ca2145429c829b5834786028c0b693b8cc88e36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:56:26 -0800 Subject: [PATCH 062/107] Plug-ins: a filter run is given the typing in progress, and a refused output keeps it in progress With Real-time Drawing off, typing in progress is kept as its own step before the run is prepared, in plugin.run, a plug-in command and the app's background start, so the plug-in is given the typed text. A run whose typing started after it was prepared, with its text still out of the document, is refused, and a background run that finishes then asks to be run again. Typing whose text is already in the document is kept only after every check that can refuse the output has passed, so a refused output leaves the document, the history and the typing in progress as they were. When keeping it changes the document, the output is applied to the document as kept. --- crates/engine/src/cmd/plugin.rs | 93 +++++++++++++++++++------ crates/engine/src/tests/plugins.rs | 67 ++++++++++++++++++ crates/ui-egui/src/plugin_runs.rs | 10 ++- crates/ui-egui/src/tests/plugin_runs.rs | 63 +++++++++++++++++ 4 files changed, 209 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 4d4929c910..f8240b08e6 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -394,29 +394,52 @@ impl FilterRun { if s.script_running() { return Err(EngineError::Busy); } - // Typing in progress is kept first, as `s.edit` keeps it, so the copy below holds it. - if !s.previewing && super::typing_in_progress(s) { + // Typing whose text Real-time Drawing off left out of the document isn't in what the + // plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it + // before the run is prepared). + if unapplied_typing(s) { + return Err(err(vectorcraft_plugins::Error::Output( + "typing in progress isn't in what the plug-in was given: nothing was changed".into(), + ))); + } + let data = out.document_data; + // The output applied to `now`, with the checks that refuse it. + let build = |now: &Document, objects: Vec| -> Result<(Document, Vec)> { + let mut d = now.clone(); + let before = (!may_write).then(|| d.layers.clone()); + let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?; + if before.is_some_and(|b| b != d.layers) { + return Err(not_granted(&m.name, Permission::DocWrite)); + } + // Type whose text the output changed is laid out again. + let retyped: Vec = ids + .iter() + .copied() + .filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) { + (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, + _ => false, + }) + .collect(); + super::typecmd::refresh_bounds_of(&mut d, &retyped); + if let Some(data) = data.clone() { + d.set_plugin_data(&m.id, data); + } + Ok((d, ids)) + }; + // Typing in progress, its text already in the document, is kept as `s.edit` keeps it once + // nothing can refuse the output, so a refused output leaves it in progress. Keeping it can + // change the document, and the output is then applied to the document as kept. + let typing = !s.previewing && super::typing_in_progress(s); + let again = typing.then(|| out.objects.clone()); + let mut now = s.doc()?.doc.clone(); + let (mut d, mut ids) = build(&now, out.objects)?; + if let Some(objects) = again { super::settle_interaction(s)?; - } - let now = s.doc()?.doc.clone(); - let mut d = (*now).clone(); - let before = (!may_write).then(|| d.layers.clone()); - let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; - if before.is_some_and(|b| b != d.layers) { - return Err(not_granted(&m.name, Permission::DocWrite)); - } - // Type whose text the output changed is laid out again. - let retyped: Vec = ids - .iter() - .copied() - .filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) { - (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, - _ => false, - }) - .collect(); - super::typecmd::refresh_bounds_of(&mut d, &retyped); - if let Some(data) = out.document_data { - d.set_plugin_data(&m.id, data); + let kept = s.doc()?.doc.clone(); + if !Arc::ptr_eq(&kept, &now) { + now = kept; + (d, ids) = build(&now, objects)?; + } } let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::>(); if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) { @@ -454,6 +477,23 @@ fn not_granted(name: &str, permission: Permission) -> EngineError { err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed"))) } +/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a +/// preview's run)? A run prepared now isn't given that text. +pub fn unapplied_typing(s: &Session) -> bool { + !s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some() +} + +/// Keeps typing in progress whose text Real-time Drawing off left out of the document +/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the +/// typed text; one prepared before it is prepared again. +pub fn keep_unapplied_typing(s: &mut Session) -> Result { + if !unapplied_typing(s) { + return Ok(false); + } + super::settle_interaction(s)?; + Ok(true) +} + /// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its /// parameters and `_context` (what it keeps with the document included), and applies its output as /// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with @@ -470,6 +510,8 @@ fn run(s: &mut Session, p: &Value) -> Result { let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r }; return r.run_with_calls(s); } + // Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it. + let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r }; // Handed in for this very run (the app ran it in the background), it is what running the // plug-in again would return. let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params)); @@ -893,6 +935,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result }; return r.run_with_calls(s).map_err(failed); } + let r = match keep_unapplied_typing(s)? { + true => { + let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + FilterRun::prepare_with(s, plugin, Some(command), id, p)? + } + false => r, + }; let output = r.run().map_err(&failed)?; r.finish(s, &output).map_err(failed) } diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a2819faa32..53b160889c 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4903,6 +4903,73 @@ fn the_document_context_is_capped_and_its_rows_cost_instructions() { refused(&mut s); } +/// A filter that writes type, run while typing is in progress: the plug-in is given the typed +/// text, so an echo keeps it, with Real-time Drawing on and off. An output that is refused leaves +/// the document and the history as they were; with Real-time Drawing on the typing stays in +/// progress, and off it is kept as its own step before the plug-in is given its input. +#[test] +fn a_filter_that_writes_type_is_given_the_typing_in_progress() { + use vectorcraft_doc::NodeKind; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let manifest = |id: &str| { + format!( + r#"{{"id":"{id}","name":"Retype","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ) + }; + let put = |s: &mut Session, src: &str| { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) + }; + let plain = |s: &Session, t: NodeId| match &node(s, t).kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>(); + let typing = |real_time: bool| { + let mut s = session(); + s.prefs.real_time_drawing = real_time; + let v = ViewInfo::default(); + let t = NodeId(run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20}))["id"].as_u64().unwrap()); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("B", v).unwrap(); + assert_eq!(plain(&s, t), if real_time { "AB" } else { "A" }, "real time {real_time}"); + (s, t) + }; + let bang = "test.engine.writes.typing.bang"; + let bad = "test.engine.writes.typing.bad"; + for real_time in [false, true] { + // The plug-in adds "!" to the text it is given: "AB" or, given only "A", "A". + let (mut s, t) = typing(real_time); + let style = match &node(&s, t).kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string(); + put(&mut s, &tpl::when_given_else(&manifest(bang), tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!"))); + run(&mut s, "plugin.run", json!({"id": bang, "ids": [t.0]})); + assert_eq!(plain(&s, t), "AB!", "real time {real_time}: the plug-in is given the typed text"); + let steps = labels(&s); + assert_eq!(steps[steps.len() - 2..], ["Typing", "Retype"], "real time {real_time}"); + + let (mut s, t) = typing(real_time); + put(&mut s, &tpl::returning(&manifest(bad), &json!({"objects": [{"id": t.0, "transform": [0, 0, 0, 0, 0, 0]}]}).to_string())); + let undo = labels(&s); + let e = s.execute("plugin.run", &json!({"id": bad, "ids": [t.0]})).unwrap_err().to_string(); + assert!(e.contains("transform: flattens the object to a line or a point"), "{e}"); + assert_eq!(plain(&s, t), "AB", "real time {real_time}"); + if real_time { + assert_eq!(labels(&s), undo, "the refused output leaves the history as it was"); + assert!(s.in_interaction(), "and the typing in progress"); + } else { + assert_eq!(labels(&s)[undo.len()..], ["Typing"], "only the typing is kept"); + } + } +} + /// A run past its memory budget fails before the plug-in starts, with the document and undo /// history as they were: a read-only object whose other fields don't fit, a path and a compound /// path that don't fit, and parameters past the input's half of the cap, with objects selected or diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index f7c579337c..020260c5d1 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -23,7 +23,7 @@ use std::sync::mpsc::{Receiver, TryRecvError, channel}; use serde_json::{Value, json}; use vectorcraft_engine::EngineError; use vectorcraft_engine::cmd::fileio::progress::{self, Progress}; -use vectorcraft_engine::cmd::plugin::FilterRun; +use vectorcraft_engine::cmd::plugin::{self, FilterRun}; use crate::VectorcraftApp; use crate::export_progress; @@ -74,6 +74,11 @@ pub fn start(app: &mut VectorcraftApp, p: Value) -> Result { } // Bad parameters and a missing document fail here, before anything runs. let run = FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?; + // Typing Real-time Drawing off left out of the document is kept next, so the plug-in is given it. + let run = match plugin::keep_unapplied_typing(&mut app.session).map_err(|e| e.to_string())? { + true => FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?, + false => run, + }; let who = format!("“{}”", run.plugin().manifest().name.trim_end_matches('…')); let mut params = p; params["ids"] = json!(run.inputs().iter().map(|i| i.0).collect::>()); @@ -140,7 +145,8 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { return; } }; - if !run.current(&app.session) { + // Typing started meanwhile with Real-time Drawing off isn't in what the plug-in was given. + if !run.current(&app.session) || plugin::unapplied_typing(&app.session) { app.status(format!("{} finished, but the document or the plug-in changed meanwhile: run it again", r.who)); return; } diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index ed161e797f..ef910a800e 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -201,6 +201,69 @@ fn a_heavy_filter_s_result_needs_the_document_as_it_was() { assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); } +/// A heavy filter that writes type, run while typing is in progress with Real-time Drawing off: +/// the typing is kept before the run starts, so the plug-in is given the typed text and its result +/// applies once it is done. A run that can't start keeps no typing. Typing started with Real-time +/// Drawing off while it runs isn't in what it was given: nothing changes, and the status bar says +/// to run it again. +#[test] +fn a_heavy_filter_is_given_the_typing_in_progress() { + use vectorcraft_doc::{NodeId, NodeKind}; + use vectorcraft_engine::ViewInfo; + use vectorcraft_engine::tools::{PointerEvent, PointerKind}; + let id = "test.ui.heavy.typing"; + let plain = |app: &VectorcraftApp, t: NodeId| match &app.session.doc().unwrap().doc.node(t).unwrap().kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + // Clicks into the end of `t` with the Type tool and types `text`. + let type_into = |app: &mut VectorcraftApp, t: NodeId, text: &str| { + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(text, v).unwrap(); + }; + let mut app = app(); + app.session.prefs.real_time_drawing = false; + let t = NodeId(app.run("text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20})).unwrap()["id"].as_u64().unwrap()); + let style = match &app.session.doc().unwrap().doc.node(t).unwrap().kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string(); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","budget":"heavy","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ); + // It adds "!" to the text it is given: "AB" or, given only "A", "A". + let src = tpl::when_given_else(&manifest, tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!")); + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + app.run("plugin.install", json!({"dataBase64": data, "allowHeavy": true, "grant": ["doc.read", "doc.write"]})).unwrap(); + type_into(&mut app, t, "B"); + assert_eq!(plain(&app, t), "A", "Real-time Drawing off leaves the typing out of the document"); + // A run that can't start leaves the typing in progress, out of the document. + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(plugin_runs::start(&mut app, json!({"id": "test.ui.heavy.missing", "ids": [t.0]})).is_err()); + assert_eq!(plain(&app, t), "A", "a run that can't start keeps no typing"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(app.session.in_interaction(), "the typing is still in progress"); + let p = json!({"id": id, "ids": [t.0]}); + assert_eq!(plugin_runs::start(&mut app, p.clone()).unwrap()["background"], true); + assert_eq!(plain(&app, t), "AB", "the typing is kept before the run starts"); + finish_runs(&mut app); + assert_eq!(plain(&app, t), "AB!", "{}", app.ui.status); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + // Typing started while it runs, Real-time Drawing off. + plugin_runs::start(&mut app, p).unwrap(); + type_into(&mut app, t, "C"); + let doc = app.session.doc().unwrap().doc.clone(); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().doc, doc, "nothing changed"); + assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); +} + /// The progress window is the run's: headed by it, with Cancel and Continue in Background; Cancel /// stops the run, which changes nothing, and the window goes. #[test] From 01d77a45b9a3e98844114f920e1ac38875e49c33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:00:28 -0800 Subject: [PATCH 063/107] Docs: a host at api 3 that doesn't read writes ignores the key Hosts from before api 3 refuse the manifest. A host at api 3 without writes installs the filter, ignores the key and refuses an output that changes the objects it was given. --- docs/plugins.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index 37def47f1a..c7ef338d6c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -641,8 +641,9 @@ the module's start function, in a run that isn't a filter's run on a document, o - `writes` (filters at `api` 3 only): the kinds among `inputs` the filter may change ([writing type, images and symbols](#writing-type-images-and-symbols)), each at most once (`"writes": ["type"]`). Left out or `[]`, everything the filter reads stays read-only. An unknown, repeated or wrongly typed entry, a kind `inputs` doesn't list, `writes` - on another kind, below `api` 3, or without `doc.write` in `permissions`, is refused when the plug-in is installed, and - hosts from before it refuse `api` 3. + on another kind, below `api` 3, or without `doc.write` in `permissions`, is refused when the plug-in is installed. + Hosts from before `api` 3 refuse the manifest. A host at `api` 3 that doesn't read `writes` installs the filter, + ignores the key and keeps everything the filter reads read-only, so an output that changes those objects is refused. - `context` (filters, and live effects with `commands`, at `api` 3 only): the parts of the active document a run reads in `_context.document`, any of `"settings"`, `"artboards"`, `"layers"` and `"swatches"`, each at most once (`"context": ["artboards", "layers"]`). Left out or `[]`, a run gets none, as before. An unknown, repeated or wrongly From 5099ce5e553e4290f35f216be115227d83645155 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:10:16 -0800 Subject: [PATCH 064/107] Plug-ins: unknown keys inside a written style's nested attributes are refused A paragraph style's hyphenation, justification, tab stops and list, and a character style's stroke dash, now refuse a key they don't read, naming the field, as the style's own keys already did. A misspelled nested key no longer leaves that setting unchanged without an error. --- crates/plugins/src/objects/tests.rs | 25 +++++++++++++++++++++++++ crates/plugins/src/objects/writes.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 99baa8dfd7..f69e402719 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1323,6 +1323,31 @@ fn bad_writes_are_refused_naming_the_object_and_the_field() { (text, json!({"text": {"runs": [{"text": "Hi", "style": 5}]}}), &InputKind::ALL, "text.runs[0]: `style` must be an object".into()), (text, json!({"text": {"paragraphs": [5, {}]}}), &InputKind::ALL, "text: `paragraphs[0]` must be an object".into()), (text, json!({"text": {"paragraphs": [{"spaceBefor": 1}, {}]}}), &InputKind::ALL, "text.paragraphs[0]: unknown key 'spaceBefor'".into()), + ( + text, + json!({"text": {"paragraphs": [{"hyphenation": {"wordLongerThen": 3}}, {}]}}), + &InputKind::ALL, + "text.paragraphs[0].hyphenation: unknown key 'wordLongerThen'".into(), + ), + ( + text, + json!({"text": {"paragraphs": [{"justification": {"wordSpacng": [80, 100, 133]}}, {}]}}), + &InputKind::ALL, + "text.paragraphs[0].justification: unknown key 'wordSpacng'".into(), + ), + ( + text, + json!({"text": {"paragraphs": [{}, {"tabs": [{"position": 36}, {"position": 72, "aling": "center"}]}]}}), + &InputKind::ALL, + "text.paragraphs[1].tabs[1]: unknown key 'aling'".into(), + ), + (text, json!({"text": {"paragraphs": [{"list": {"levl": 2}}, {}]}}), &InputKind::ALL, "text.paragraphs[0].list: unknown key 'levl'".into()), + ( + text, + json!({"text": {"runs": styled(&|s| s["stroke_dash"] = json!({"pattern": [2, 2], "ofset": 1}))}}), + &InputKind::ALL, + "text.runs[0].style.stroke_dash: unknown key 'ofset'".into(), + ), ( text, json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}), diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs index 48588e40e2..574ebb6216 100644 --- a/crates/plugins/src/objects/writes.rs +++ b/crates/plugins/src/objects/writes.rs @@ -165,6 +165,28 @@ fn strict(v: &Value, parent: &str, key: &str) -> Result serde_json::from_value(v.clone()).map_err(|e| out_err(&at, e)) } +/// The field `key` of `v`, the style at `at`, holds only attributes `T` reads: an object, or each +/// object of a list. An unknown key is an error at `at.key` (or `at.key[i]`); other values are left +/// to the style's own checks. +fn known_keys(v: &Value, at: &str, key: &str) -> Result<()> { + let names = attr_names::(); + let check = |o: &Map, at: &str| match o.keys().find(|k| !names.contains(&k.as_str())) { + Some(k) => { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + Err(out_err(at, format!("unknown key '{k}'"))) + } + None => Ok(()), + }; + match v.get(key) { + Some(Value::Object(o)) => check(o, &format!("{at}.{key}")), + Some(Value::Array(list)) => list.iter().enumerate().try_for_each(|(i, e)| match e { + Value::Object(o) => check(o, &format!("{at}.{key}[{i}]")), + _ => Ok(()), + }), + _ => Ok(()), + } +} + /// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't /// flatten the object. fn decode_transform(v: &Value, at: &str) -> Result { @@ -267,6 +289,7 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va let text = o.get(key).and_then(Value::as_str).ok_or_else(|| out_err(&at, format!("`{key}` must be a string")))?; let style_v = o.get("style").unwrap_or(&Value::Null); let mut style: CharStyle = strict(style_v, &at, "style")?; + known_keys::(style_v, &format!("{at}.style"), "stroke_dash")?; let inline = match o.get("inline") { None | Some(Value::Null) => None, Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?), @@ -447,6 +470,10 @@ fn range_err(at: &str, e: &AttrRangeError) -> Error { fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result { let mut st: ParaStyle = strict(v, parent, key)?; let at = format!("{parent}.{key}"); + known_keys::(v, &at, "hyphenation")?; + known_keys::(v, &at, "justification")?; + known_keys::(v, &at, "tabs")?; + known_keys::(v, &at, "list")?; let justification = match v.get("justification") { None | Some(Value::Null) => None, Some(j) => Some(serde_json::from_value::(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?), From 6cce77ffb5513751551ab352d6ca3b445285931e Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:13:46 +0530 Subject: [PATCH 065/107] Fix floating document raise after Presentation Mode --- crates/ui-egui/src/doc_windows.rs | 9 ++++- crates/ui-egui/src/doc_windows/tests.rs | 47 ++++++++++++++++--------- 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 9c65f48e24..216d3b65b9 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -335,6 +335,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Presentation Mode fits each floating window it shows to the main window: back in their // floating windows, those views fit their windows again. let presenting = presenting(app); + let restoring = !presenting && app.canvas.windows.presented.is_some(); if presenting { let is_floating = current.is_some_and(|k| floating(app, &k)); let shown = app.canvas.windows.presented.get_or_insert_default(); @@ -365,9 +366,15 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { return; } let raise = current.filter(|u| app.canvas.windows.current != Some(*u)); - app.canvas.windows.current = current; let ctx = ui.ctx().clone(); let os_windows = WindowHost::of(&ctx).viewports_available(); + if restoring && !os_windows && raise.is_some() { + // egui raises every reappearing area in this pass, preserving their old order. Repeat + // the current window's raise next frame, when the other windows no longer request it. + ctx.request_repaint(); + } else { + app.canvas.windows.current = current; + } // An OS window's place is in desktop points: the main window's own origin shifts it. let origin = if os_windows { ctx.input(|i| i.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO).to_vec2() diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 3e8ffbff5b..931813e14a 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -417,23 +417,36 @@ fn presentation_mode_shows_the_floating_current_document_in_the_main_window() { #[test] fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { - let mut app = app_with(2); - let ctx = crate::testing::ui_context(); - frame(&mut app, &ctx, vec![]); - app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - // Where the two windows overlap: document 1's title bar, over document 0's body. - let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("document.activate", json!({"index": 0})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - click(&mut app, &ctx, overlap); - assert_eq!(app.session.active_index(), Some(0), "document 0's window is in front where they overlap"); + for change_during_presentation in [false, true] { + let mut app = app_with(2); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + // Where the two windows overlap: document 1's title bar, over document 0's body. + let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); + // Cover both an unchanged current document and one chosen while the windows are hidden. + if !change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + if change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, overlap); + assert_eq!( + app.session.active_index(), + Some(0), + "document 0's window is in front (changed during presentation: {change_during_presentation})" + ); + } } /// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks From c0495c4e31ec9cabd4e630a8ab642dd2c27b0c2d Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:54:00 +0530 Subject: [PATCH 066/107] Revert "Fix floating document raise after Presentation Mode" This reverts commit 77a12e40bb8b745079588b42b77f95c4caeaf0c2. --- crates/ui-egui/src/doc_windows.rs | 9 +---- crates/ui-egui/src/doc_windows/tests.rs | 47 +++++++++---------------- 2 files changed, 18 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 216d3b65b9..9c65f48e24 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -335,7 +335,6 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Presentation Mode fits each floating window it shows to the main window: back in their // floating windows, those views fit their windows again. let presenting = presenting(app); - let restoring = !presenting && app.canvas.windows.presented.is_some(); if presenting { let is_floating = current.is_some_and(|k| floating(app, &k)); let shown = app.canvas.windows.presented.get_or_insert_default(); @@ -366,15 +365,9 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { return; } let raise = current.filter(|u| app.canvas.windows.current != Some(*u)); + app.canvas.windows.current = current; let ctx = ui.ctx().clone(); let os_windows = WindowHost::of(&ctx).viewports_available(); - if restoring && !os_windows && raise.is_some() { - // egui raises every reappearing area in this pass, preserving their old order. Repeat - // the current window's raise next frame, when the other windows no longer request it. - ctx.request_repaint(); - } else { - app.canvas.windows.current = current; - } // An OS window's place is in desktop points: the main window's own origin shifts it. let origin = if os_windows { ctx.input(|i| i.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO).to_vec2() diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 931813e14a..3e8ffbff5b 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -417,36 +417,23 @@ fn presentation_mode_shows_the_floating_current_document_in_the_main_window() { #[test] fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { - for change_during_presentation in [false, true] { - let mut app = app_with(2); - let ctx = crate::testing::ui_context(); - frame(&mut app, &ctx, vec![]); - app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - // Where the two windows overlap: document 1's title bar, over document 0's body. - let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); - // Cover both an unchanged current document and one chosen while the windows are hidden. - if !change_during_presentation { - app.run("document.activate", json!({"index": 0})).unwrap(); - frame(&mut app, &ctx, vec![]); - } - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - if change_during_presentation { - app.run("document.activate", json!({"index": 0})).unwrap(); - frame(&mut app, &ctx, vec![]); - } - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - click(&mut app, &ctx, overlap); - assert_eq!( - app.session.active_index(), - Some(0), - "document 0's window is in front (changed during presentation: {change_during_presentation})" - ); - } + let mut app = app_with(2); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + // Where the two windows overlap: document 1's title bar, over document 0's body. + let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, overlap); + assert_eq!(app.session.active_index(), Some(0), "document 0's window is in front where they overlap"); } /// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks From e9b593f2ea62425e3e9407852592ce9b0cb1d45f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 16:58:43 -0800 Subject: [PATCH 067/107] Document Info: a click on a value copies it A click on a Document Info value copies the whole value to the clipboard and the status bar shows "Copied the value". Dragging across a value still selects part of it, a Shift-click still extends the selection, and a double click copies the value once and selects a word. Part of #8432. --- crates/ui-egui/src/panels/doc_info.rs | 29 ++++++++++++++++++---- crates/ui-egui/src/tests/selectall.rs | 35 +++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 88ee1d6f6f..7f85921deb 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -31,13 +31,25 @@ pub struct DocInfoView { } /// A `label: value` row. `label` is shown as given: translate an interface label first, a name -/// stays as it is. -pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { +/// stays as it is. Whether the value was clicked to copy it: a click with no key held, other than +/// the second or third click of a double or triple click. +pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool { + let mut clicked = false; Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(true).show(ui, |ui, _| { Text::new(label.to_string()).shade(Shade::Muted).show(ui); - // The value can be selected and copied (#8432). - SelectableText::new(label.to_string(), &value).show(ui); + // The value can be selected and copied, and a click copies all of it (#8432). A drag selects + // and a Shift-click extends the selection, so neither copies. + let shown = SelectableText::new(label.to_string(), value).show(ui); + clicked = shown.contains_pointer() + && ui.input(|i| { + let primary = egui::PointerButton::Primary; + i.pointer.button_clicked(primary) + && !i.pointer.button_double_clicked(primary) + && !i.pointer.button_triple_clicked(primary) + && i.modifiers.is_none() + }); }); + clicked } /// `document.info` with its categories, fetched again only when the document, the scope or the @@ -64,6 +76,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let DocInfoView { selection_only: sel_only, category } = app.ui.doc_info.clone(); + let mut copy = None; Stack::new().show(ui, |ui, _| { let sections = i["sections"].as_array().map_or(&[][..], Vec::as_slice); let shown = sections.iter().filter(|s| category.is_empty() || s["id"] == category.as_str()); @@ -92,11 +105,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Text::new(super::label_or_name(label, !named.contains(&k)).to_string()).shade(Shade::Muted).show(ui); } else { let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); - row(ui, super::label_or_name(label, !named.contains(&k)), shown); + if row(ui, super::label_or_name(label, !named.contains(&k)), &shown) { + copy = Some(shown); + } } } } }); + if let Some(text) = copy { + app.clipboard_out = Some(text); + app.status("Copied the value"); + } } /// A Brushes row's value in the interface language: the brush's type (`Art Brush`), or that the diff --git a/crates/ui-egui/src/tests/selectall.rs b/crates/ui-egui/src/tests/selectall.rs index 9c20603db8..386fe9d14b 100644 --- a/crates/ui-egui/src/tests/selectall.rs +++ b/crates/ui-egui/src/tests/selectall.rs @@ -380,6 +380,41 @@ fn copy_and_cut_copy_the_text_selected_in_a_panel_label() { assert!(copied(&after).iter().any(|t| t.starts_with(">| frames.into_iter().flat_map(|events| copied(&a.frame(events))).collect::>(); + let (status, sets) = (a.app.ui.status.clone(), a.app.ui.status_sets); + let clicked = copies(&mut a, vec![vec![Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false)], vec![]]); + assert_eq!(clicked, [length], "a click copies the value, once"); + assert!(a.app.ui.status_sets != sets && a.app.ui.status != status, "the status bar says it was copied"); + assert_eq!(a.selected(), 1, "the art stays selected"); + assert!(a.app.session.clipboard.is_empty(), "no art copied"); + a.time += 1.0; + let twice = copies(&mut a, vec![vec![click(at, true)], vec![click(at, false)], vec![click(at, true)], vec![click(at, false)], vec![]]); + assert_eq!(twice, [length], "a double click copies the value once"); + a.time += 1.0; + let (from, to) = (text_rect(&out, length).left_center() + vec2(1.0, 0.0), text_rect(&out, length).right_center() - vec2(1.0, 0.0)); + let mut drag = vec![vec![Event::PointerMoved(from)], vec![click(from, true)]]; + drag.extend((1..=4).map(|k| vec![Event::PointerMoved(from + (to - from) * k as f32 / 4.0)])); + drag.extend([vec![click(to, false)], vec![]]); + assert!(copies(&mut a, drag).is_empty(), "a drag selects and copies nothing"); + a.time += 1.0; + let shift = Event::ModifiersChanged(Modifiers::SHIFT); + let extended = copies( + &mut a, + vec![vec![shift, Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false)], vec![Event::ModifiersChanged(Modifiers::NONE)]], + ); + assert!(extended.is_empty(), "a Shift-click copies nothing"); +} + /// Drag across a label in a window of its own (a floating panel's), selecting its text there. The /// main window's labels then copy nothing on Copy or Cut, which run on the art a pass later. fn select_label_text_in_another_window(a: &mut App) { From 52971bc1d67ad0fe017661e790cfee1a62141fbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:22:04 -0800 Subject: [PATCH 068/107] Plug-ins: stored plug-ins loading in the background count only a signed grants file The background load of the plug-in store read the grants file directly and counted its grants whether or not the file was signed, so a grants file changed outside VectorCraft, or an earlier copy put back, still let its plug-ins load. It now takes the grants through the same check as the other reads (signed_grants), and an unsigned file grants nothing. The three load tests that expect a grant in the store now write a signed grants file and read it back in the signed format. --- crates/engine/src/store.rs | 24 +++++++++++------------- crates/engine/src/tests/plugins.rs | 26 +++++++++++++++++++++----- 2 files changed, 32 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 8e3236ba80..29cd6f1bea 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -823,18 +823,10 @@ impl Session { } let dir = load.dir.clone(); // The grants file is read once for this turn. `written` holds whether it names each id - // whose grant this turn removed or put back. + // whose grant this turn removed or put back. Only a signed file grants anything + // ([`signed_grants`]). let file = read_grants(&dir); - let mut grants = self.counted( - &dir, - match &file { - Ok(file) => file.grants.clone(), - Err(e) => { - log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); - BTreeMap::new() - } - }, - ); + let mut grants = self.counted(&dir, signed_grants(&dir, &file)); let mut written: BTreeMap = BTreeMap::new(); let named = |written: &BTreeMap, id: &str| { written.get(id).copied().unwrap_or_else(|| match &file { @@ -2398,8 +2390,14 @@ fn read_grants(dir: &Path) -> Result { /// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a /// list. fn stored_grants(dir: &Path) -> BTreeMap { - match read_grants(dir) { - Ok(file) if file.trust == Trust::Signed => file.grants, + signed_grants(dir, &read_grants(dir)) +} + +/// [`stored_grants`] from `file`, the grants file of the plug-in store `dir` as [`read_grants`] +/// read it. +fn signed_grants(dir: &Path, file: &Result) -> BTreeMap { + match file { + Ok(file) if file.trust == Trust::Signed => file.grants.clone(), Ok(_) => BTreeMap::new(), Err(e) => { log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 84542abcf4..55a047baad 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2625,7 +2625,8 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap(); + let entry = + |hash: String| crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()); std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap(); let held = HeldLoad::new(later.clone()); let mut s = session(); @@ -2642,7 +2643,7 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() { s.finish_plugin_loads(); let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); assert!(vectorcraft_plugins::registry::remove(id)); - let listed: Vec = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap(); + let listed = crate::store::grant_entries(&std::fs::read(&grants).unwrap()); assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed"); assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::>(), [json!(sha256_hex(&other))], "{listed:?}"); } @@ -2661,7 +2662,11 @@ fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); // The first write removes the grant; the second, which puts it back, finds a folder where the // file goes and fails. let blocked = grants.clone(); @@ -2696,7 +2701,11 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); // The first write removes the grant; while the second puts it back, the id is installed // elsewhere. crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { @@ -2711,7 +2720,14 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() { assert!(vectorcraft_plugins::registry::remove(id)); // A grants file that went away holds no grant; one still there must read as a list. let listed: Vec = match std::fs::read(&grants) { - Ok(b) => serde_json::from_slice(&b).unwrap(), + Ok(b) => match serde_json::from_slice::(&b).unwrap() { + Value::Array(entries) => entries, + Value::Object(mut file) => match file.remove("grants") { + Some(Value::Array(entries)) => entries, + other => panic!("the grants file holds no list: {other:?}"), + }, + other => panic!("the grants file holds no list: {other:?}"), + }, Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![], Err(e) => panic!("the grants file could not be read: {e}"), }; From 0fd2672aa331070a4ba4a267c5d64a5d17f88faa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:03:53 -0800 Subject: [PATCH 069/107] Docs: the scripting line names the Layer parent and the members still missing The line said layers were not there yet, while a page item's parent is already a Layer with name, typename and toString. It now names Document.layers and Document.activeLayer as the members still missing. --- 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 ebeac27545..30cff6867d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,7 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 8c97641c4eb3dc5292d1736322f323dd499c5b0d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:07:06 -0800 Subject: [PATCH 070/107] 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 54c84108a1bc46f8957d2a0006fbda6c94f53a45 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:13:02 -0800 Subject: [PATCH 071/107] 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 e60c5e3fa26478ebff55753aa1ad7eeb6b47ca0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:20:17 -0800 Subject: [PATCH 072/107] Tests: the panel harness holds the app-window panel lookup `tests::panel_harness::floated` shows a panel docked or floating in the whole app window and returns its body and named nodes, with `Shown::past`, `past_named` and `middles`. The panel-row tests and the Gradient panel tests both use it instead of their own copies. --- crates/ui-egui/src/panels/gradient/tests.rs | 100 ++--------------- crates/ui-egui/src/panels/tests_panel_rows.rs | 58 +--------- crates/ui-egui/src/tests/panel_harness.rs | 104 +++++++++++++++++- 3 files changed, 118 insertions(+), 144 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 83ab5a2ba2..f4b57b8c8b 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -6,6 +6,7 @@ use egui::{Key, Modifiers, Pos2, pos2, vec2}; use vectorcraft_engine::Session; use super::*; +use crate::tests::panel_harness::{Place, Shown, floated}; #[test] fn dropped_colours_recolour_or_add_an_opaque_stop() { @@ -366,103 +367,20 @@ fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() { // ---------- the panel in the app window ---------- -/// Where the panel is shown in the app window. -#[derive(Clone, Copy, Debug)] -enum Place { - /// Docked in its column. - Docked, - /// Floating, this many points wide. - Floating(f32), -} - -/// The Gradient panel as one frame of the app window drew it. -struct Shown { - /// The panel's body. - body: egui::Rect, - /// The name and rect of every named node in the body. - nodes: Vec<(String, egui::Rect)>, - /// Each catalog string asked for, as the panel's language shows it. - names: Vec<(&'static str, String)>, -} - -impl Shown { - /// The rects of the nodes named `name` (a catalog string asked for). - fn rects(&self, name: &str) -> Vec { - let shown = self.names.iter().find(|(asked, _)| *asked == name).map_or(name, |(_, shown)| shown.as_str()); - let found: Vec = self.nodes.iter().filter(|(label, _)| label == shown).map(|(_, r)| *r).collect(); - assert!(!found.is_empty(), "the panel shows no {shown:?}"); - found - } - - /// The nodes that reach past either side of the body, each with its rect. - fn past(&self, nodes: impl IntoIterator) -> Vec { - let outside = |r: &egui::Rect| r.left() < self.body.left() - 0.5 || r.right() > self.body.right() + 0.5; - nodes.into_iter().filter(|(_, r)| outside(r)).map(|(name, r)| format!("{name} at {r:?}")).collect() - } - - /// The vertical middles of the nodes named `names`. - fn middles(&self, names: &[&str]) -> Vec { - names.iter().flat_map(|name| self.rects(name)).map(|r| r.center().y).collect() - } -} - /// A selected gradient stop: the panel shows its Color row. fn select_a_stop(app: &mut VectorcraftApp) { app.run("paint.setFill", json!({"gradient": {}})).unwrap(); app.run("gradient.selectStop", json!({"index": 1})).unwrap(); } -/// The Gradient panel shown at `place` in the whole app window (1440 by 900 pt) over a selected rectangle that -/// `setup` paints, drawn in `lang`, with the catalog strings `names` as `lang` shows them. -fn shown(lang: &str, place: Place, setup: fn(&mut VectorcraftApp), names: &[&'static str]) -> Shown { - use egui::accesskit::{Node, NodeId, Role}; +/// The Gradient panel shown at `place` in the whole app window over a selected rectangle that `setup` paints, drawn +/// in `lang`, with the catalog strings `names` as `lang` shows them. The Gradient Fill box is always asked for, so a +/// docked panel is found by it. +fn shown(lang: &str, place: Place, setup: fn(&mut VectorcraftApp), names: &[&str]) -> Shown { let mut app = super::super::tests_appearance::app_with_rect(); setup(&mut app); - app.session.prefs.interface_language = lang.into(); - app.run("window.panel", json!({ "panel": "gradient" })).unwrap(); - match place { - Place::Docked => app.run("window.panel.dock", json!({ "panel": "gradient" })).unwrap(), - Place::Floating(width) => { - app.run("window.panel.float", json!({ "panel": "gradient", "x": 520, "y": 120, "width": width, "height": 700 })).unwrap() - } - }; - app.run("window.panel.activate", json!({ "panel": "gradient" })).unwrap(); - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); - let mut nodes: Vec<(NodeId, Node)> = Vec::new(); - for at in 1..=8 { - let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; - let out = crate::testing::app_frame(&mut app, &ctx, input); - nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); - } - // The frames set the language from the preference; the names are looked up in it before English is put back. - let names: Vec<(&'static str, String)> = names.iter().map(|name| (*name, crate::i18n::t(name).to_owned())).collect(); - let fill = crate::i18n::t("Gradient Fill").to_owned(); - crate::i18n::set_current(crate::i18n::Lang::EN); - let rect = - |node: &Node| node.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 by_id: std::collections::HashMap = nodes.iter().map(|(id, n)| (*id, n)).collect(); - let under = |root: NodeId| { - let mut found = Vec::new(); - let mut todo = vec![root]; - while let Some(id) = todo.pop() { - let Some(node) = by_id.get(&id) else { continue }; - if let (Some(label), Some(r)) = (node.label(), rect(node)) { - found.push((label.to_owned(), r)); - } - todo.extend(node.children().iter().copied()); - } - found - }; - // The panel's body: the tab panel that holds the Gradient Fill box. - let (body, nodes) = nodes - .iter() - .filter(|(_, n)| n.role() == Role::TabPanel) - .filter_map(|(id, n)| Some((rect(n)?, under(*id)))) - .find(|(_, named)| named.iter().any(|(l, _)| *l == fill)) - .unwrap_or_else(|| panic!("no Gradient panel at {place:?} in {lang}")); - Shown { body, nodes, names } + let asked: Vec<&str> = names.iter().copied().chain(["Gradient Fill"]).collect(); + floated(app, "gradient", lang, place, &asked) } /// Docked, every control of the panel stays inside its column, with a solid fill (the panel shows its notice) and @@ -500,9 +418,9 @@ fn the_gradient_rows_wrap_in_a_narrow_panel() { "Delete Stop", ]; for lang in ["en", "fr"] { - let asked: Vec<&'static str> = names.iter().copied().chain(["Freeform Gradient"]).collect(); + let asked: Vec<&str> = names.iter().copied().chain(["Freeform Gradient"]).collect(); let panel = shown(lang, Place::Floating(crate::panel_docking::PANEL_MIN_WIDTH), select_a_stop, &asked); - let past = panel.past(names.iter().flat_map(|name| panel.rects(name).into_iter().map(|r| (name.to_string(), r)))); + let past = panel.past_named(&names); assert!(past.is_empty(), "past the panel in {lang}: {past:?}"); for freeform in panel.rects("Freeform Gradient") { let inside = freeform.left() >= panel.body.left() - 0.5 && freeform.right() <= panel.body.right() + TYPE_OVERFLOW + 0.5; diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index 15a8dace13..e249c1ea95 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -1,12 +1,9 @@ //! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width. -use serde_json::json; - use super::tests_appearance::app_with_rect; use super::*; -use crate::i18n::Lang; use crate::panel_docking::PANEL_MIN_WIDTH; -use crate::tests::panel_harness::{Panel, ROOM}; +use crate::tests::panel_harness::{Panel, Place, ROOM, floated}; #[test] fn the_arrowhead_row_stays_inside_the_stroke_panel() { @@ -30,62 +27,19 @@ fn the_color_themes_hex_row_stays_inside_a_narrow_panel() { } } -/// Panel `panel` floated `width` wide in the whole app window, drawn in `lang`: the rect of its body, and the rects of -/// the controls named each of `names` (catalog strings, shown in `lang`). -fn floated(panel: &str, lang: &str, width: f32, names: &[&str]) -> (egui::Rect, Vec<(String, Vec)>) { - use egui::accesskit::Role; - const AT: f32 = 520.0; - let mut app = app_with_rect(); - app.session.prefs.interface_language = lang.into(); - app.run("window.panel", json!({ "panel": panel })).unwrap(); - app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap(); - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); - let mut nodes = Vec::new(); - for at in 1..=8 { - let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; - let out = crate::testing::app_frame(&mut app, &ctx, input); - nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); - } - // The frames set the language from the preference; the names are looked up in it before English is put back. - let shown: Vec<&str> = names.iter().map(|name| crate::i18n::t(name)).collect(); - crate::i18n::set_current(Lang::EN); - let rect = |node: &egui::accesskit::Node| { - node.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))) - }; - // The floating panel's body: the tab panel at the left edge the float asked for. - let body = nodes - .iter() - .filter(|(_, n)| n.role() == Role::TabPanel) - .find_map(|(_, n)| rect(n).filter(|r| (r.left() - AT).abs() < 1.0)) - .unwrap_or_else(|| panic!("{panel} does not float at x {AT}")); - assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for"); - let controls = shown - .into_iter() - .map(|name| { - let found: Vec = nodes.iter().filter(|(_, n)| n.label().is_some_and(|l| l == name)).filter_map(|(_, n)| rect(n)).collect(); - assert!(!found.is_empty(), "{panel} shows no {name:?}"); - (name.to_owned(), found) - }) - .collect(); - (body, controls) -} - /// The controls named `names` (catalog strings, shown in `lang`) that reach past either side of panel `panel`, /// floated at the narrowest panel width in the whole app window, each with its rect. fn past_a_narrow_panel(panel: &str, lang: &str, names: &[&str]) -> Vec { - let (body, controls) = floated(panel, lang, PANEL_MIN_WIDTH, names); - let outside = |r: &egui::Rect| r.left() < body.left() - 0.5 || r.right() > body.right() + 0.5; - controls.iter().flat_map(|(name, found)| found.iter().filter(|r| outside(r)).map(move |r| format!("{name} at {r:?}"))).collect() + floated(app_with_rect(), panel, lang, Place::Floating(PANEL_MIN_WIDTH), names).past_named(names) } #[test] fn the_profile_row_stays_on_one_line_in_a_wide_stroke_panel() { - let (_, controls) = floated("stroke", "en", 360.0, &["Profile", "Flip Along", "Flip Across"]); + let names = ["Profile", "Flip Along", "Flip Across"]; + let panel = floated(app_with_rect(), "stroke", "en", Place::Floating(360.0), &names); // The field, its caption, the list and the two buttons share one line, so their middles are level. - let middles: Vec = controls.iter().flat_map(|(_, found)| found.iter().map(|r| r.center().y)).collect(); - assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{controls:?}"); + let middles = panel.middles(&names); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{middles:?}"); } #[test] diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 0b36cec615..9c61500431 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -6,6 +6,7 @@ use std::{ cell::{RefCell, RefMut}, + collections::HashMap, rc::Rc, }; @@ -13,7 +14,8 @@ use craft::behavior::PartRef; use craft::ui::runtime::frame::take_output; use craft::ui::testing::pointer::part_rect_of_node; use craft::ui::testing::{Fixture, Target}; -use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, vec2}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, pos2, vec2}; +use serde_json::json; use crate::VectorcraftApp; @@ -361,3 +363,103 @@ impl Panel { self.fixture.tree().focused_key() == self.look(name).node } } + +/// Where [`floated`] shows a panel in the app window. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Place { + /// Docked in its column. + Docked, + /// Floating at x 520, this many points wide. + Floating(f32), +} + +/// A panel as one frame of the whole app window drew it. +pub(crate) struct Shown { + /// The panel's body. + pub(crate) body: Rect, + /// The name and rect of every named node in the body. + pub(crate) nodes: Vec<(String, Rect)>, + /// Each catalog string asked for, with the text the panel's language shows for it. + names: Vec<(String, String)>, +} + +impl Shown { + /// The rects of the nodes named `name` (a catalog string asked for). + pub(crate) fn rects(&self, name: &str) -> Vec { + let shown = self.names.iter().find(|(asked, _)| asked == name).map_or(name, |(_, shown)| shown.as_str()); + let found: Vec = self.nodes.iter().filter(|(label, _)| label == shown).map(|(_, r)| *r).collect(); + assert!(!found.is_empty(), "the panel shows no {shown:?}"); + found + } + + /// The nodes of `nodes` that reach past either side of the body, each with its rect. + pub(crate) fn past(&self, nodes: impl IntoIterator) -> Vec { + let outside = |r: &Rect| r.left() < self.body.left() - 0.5 || r.right() > self.body.right() + 0.5; + nodes.into_iter().filter(|(_, r)| outside(r)).map(|(name, r)| format!("{name} at {r:?}")).collect() + } + + /// The nodes named each of `names` (catalog strings asked for) that reach past either side of the body, each with + /// its rect. + pub(crate) fn past_named(&self, names: &[&str]) -> Vec { + self.past(names.iter().flat_map(|name| self.rects(name).into_iter().map(|r| ((*name).to_owned(), r)))) + } + + /// The vertical middles of the nodes named `names`, in order. + pub(crate) fn middles(&self, names: &[&str]) -> Vec { + names.iter().flat_map(|name| self.rects(name)).map(|r| r.center().y).collect() + } +} + +/// Panel `panel` of `app` shown at `place` in the whole app window (1440 by 900 pt), drawn in `lang`, with the catalog +/// strings `names` as `lang` shows them. The test sets `app` up before the call. A floating panel's body is the tab +/// panel at the left edge the float asked for; a docked panel's body is the tab panel that shows every one of `names`. +pub(crate) fn floated(mut app: VectorcraftApp, panel: &str, lang: &str, place: Place, names: &[&str]) -> Shown { + use egui::accesskit::{Node, NodeId, Role}; + const AT: f32 = 520.0; + app.session.prefs.interface_language = lang.into(); + app.run("window.panel", json!({ "panel": panel })).unwrap(); + match place { + Place::Docked => app.run("window.panel.dock", json!({ "panel": panel })).unwrap(), + Place::Floating(width) => app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap(), + }; + app.run("window.panel.activate", json!({ "panel": panel })).unwrap(); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)); + let mut nodes: Vec<(NodeId, Node)> = Vec::new(); + for at in 1..=8 { + let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; + let out = crate::testing::app_frame(&mut app, &ctx, input); + nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); + } + // The frames set the language from the preference; the names are looked up in it before English is put back. + let names: Vec<(String, String)> = names.iter().map(|name| ((*name).to_owned(), crate::i18n::t(name).to_owned())).collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let rect = |node: &Node| node.bounds().map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))); + let by_id: HashMap = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let under = |root: NodeId| { + let mut found = Vec::new(); + let mut todo = vec![root]; + while let Some(id) = todo.pop() { + let Some(node) = by_id.get(&id) else { continue }; + if let (Some(label), Some(r)) = (node.label(), rect(node)) { + found.push((label.to_owned(), r)); + } + todo.extend(node.children().iter().copied()); + } + found + }; + let mut bodies = nodes.iter().filter(|(_, n)| n.role() == Role::TabPanel).filter_map(|(id, n)| Some((rect(n)?, under(*id)))); + let found = match place { + Place::Docked => { + assert!(!names.is_empty(), "a docked panel is found by the names it shows"); + bodies.find(|(_, named)| names.iter().all(|(_, shown)| named.iter().any(|(label, _)| label == shown))) + } + Place::Floating(_) => bodies.find(|(r, _)| (r.left() - AT).abs() < 1.0), + }; + let (body, nodes) = found.unwrap_or_else(|| panic!("no {panel} panel at {place:?} in {lang}")); + if let Place::Floating(width) = place { + assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for"); + } + Shown { body, nodes, names } +} From 0f7844ecb6bdcf9e03056aef50d9a10136bd18d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:22:36 -0800 Subject: [PATCH 073/107] 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 924c4409bb0faf3a5b9a11d0a8381e4a0b9e87f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:43:42 -0800 Subject: [PATCH 074/107] 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 a868058b44133a6198051006fdf402815e5fa34b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:44:51 -0800 Subject: [PATCH 075/107] Shortcuts: panel and dialog commands whose params are all optional can be given a key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit › Keyboard Shortcuts left out UI commands with no default key, no menu bar item and a params doc other than {} or {path…}, so New Swatch…, New Color Group…, Color Group Options…, New Brush…, Brush Options…, the Layers panel's Options for Selection…, Corners…, Placement Options…, Relink…, Perspective Plane Options…, Bullets and Numbering…, Missing Fonts Dialog and Find Fonts in Folder… could not get a key, although each runs with no params. They are now listed through a KEY_ONLY_UI list that replaces the `id ==` checks for Rename and Color Picker…. A key opens the dialog for the selection or the current item, or the status bar says why it cannot. Color Group Options… with no group selected now says "select a color group in the Swatches panel, or pass group" instead of "missing `group`". Docs: docs/mcp.md, docs/ui-parity.md. --- .../src/dialogs/color_group_options.rs | 4 ++- crates/ui-egui/src/shortcut_editor.rs | 29 ++++++++++++++++--- crates/ui-egui/src/shortcuts/tests.rs | 23 +++++++++++++++ docs/mcp.md | 7 +++++ docs/ui-parity.md | 4 ++- 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs index 859d7752f6..36fab4b2a1 100644 --- a/crates/ui-egui/src/dialogs/color_group_options.rs +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -32,7 +32,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let key = "group"; let group = match p.get(key) { Some(Value::String(g)) => g.clone(), - None | Some(Value::Null) => crate::panels::swatches::sole_selected_group(app).ok_or("missing `group`")?, + None | Some(Value::Null) => { + crate::panels::swatches::sole_selected_group(app).ok_or("select a color group in the Swatches panel, or pass group")? + } Some(_) => return Err(format!("`{key}` must be a string")), }; let st = app.session.active().ok_or("no document open")?; diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index c02f72f02e..03e5e5ebfd 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -614,6 +614,29 @@ const NEEDS_A_PARAM: [&str; 77] = [ "type.ruby", ]; +/// UI commands with no default key, no menu bar item and a params doc whose fields are all optional +/// that a key press can run with no params: each opens its dialog for the selection, the current +/// item or the panel's selection, or reports in the status bar why it cannot. Rename names the +/// selection, Color Picker… opens for the proxy in front, Brush Options… for the selected path's +/// brush, and Layer Options for the highlighted rows. +pub(crate) const KEY_ONLY_UI: [&str; 15] = [ + "ui.rename", + "ui.colorPicker", + "ui.newSwatch", + "ui.newColorGroup", + "ui.colorGroupOptions", + "ui.newBrush", + "ui.brushOptions", + "ui.layerOptions", + "ui.corners", + "ui.placementOptionsDialog", + "ui.relinkDialog", + "ui.perspectivePlane", + "ui.bulletsAndNumbering", + "ui.missingFontsDialog", + "ui.findFontsInFolder", +]; + /// The (label, params) of each menu bar item, by command id. fn menu_bar_items() -> &'static HashMap> { static ITEMS: OnceLock>> = OnceLock::new(); @@ -704,11 +727,9 @@ fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool { /// Is UI command `id` (default key `sc`, params doc `params`) listed in Edit › Keyboard Shortcuts /// whether or not an item of the menu bar runs it? It is when it has a default key or a params doc -/// of `{}` or `{path…}`. Rename has no default key, and a key press names the selection: it needs -/// no `id`. Color Picker… has no default key either, and a key press opens it for the proxy in -/// front. +/// of `{}` or `{path…}`, or is one of [`KEY_ONLY_UI`]. fn ui_listed_on_its_own(id: &str, sc: &str, params: &str) -> bool { - !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename" || id == "ui.colorPicker" + !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || KEY_ONLY_UI.contains(&id) } /// Does a menu bar item run the command with no params, so that it does what its label says and opens diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index cabde4b445..491b075729 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1839,3 +1839,26 @@ fn a_filter_plugin_row_translates_its_path_and_not_its_name() { assert_eq!(filter, format!("{path} › Group")); assert_eq!(command, format!("{path} › {}", crate::i18n::tr(zh, "Group"))); } + +/// A UI command whose params are all optional and that no item of the menu bar runs can be given a +/// key: Keyboard Shortcuts lists it, and the key opens its dialog or says in the status bar why it +/// cannot. +#[test] +fn a_key_runs_a_ui_command_whose_params_are_all_optional() { + for id in crate::shortcut_editor::KEY_ONLY_UI { + let mut app = app_with_a_selected_rectangle(); + let listed = app.run("shortcuts.list", json!({"query": id})).unwrap(); + assert!(listed.as_array().is_some_and(|rows| rows.iter().any(|r| r["id"] == id)), "{id} is listed: {listed}"); + // Rename edits the name in place and Color Picker… opens the framework's picker; other tests + // check what they open. + if ["ui.rename", "ui.colorPicker"].contains(&id) { + continue; + } + let ctx = ready(&mut app); + bind(&mut app, id, "Cmd+Alt+Shift+F12"); + app.ui.status.clear(); + key_frame(&mut app, &ctx, tap(Key::F12, cmd() | Modifiers::ALT | Modifiers::SHIFT)); + key_frame(&mut app, &ctx, vec![]); + assert!(dialog_kind(&app).is_some() || !app.ui.status.is_empty(), "{id}: the key opens a dialog or reports why not"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 97cdbff876..c29383140b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8167,6 +8167,13 @@ Commands listed this way include `type.fractionalWidths`, `type.systemLayout`, ` `links.embed`, `links.update`, `object.slice.delete`, `artboard.switchOrientation`, `artboard.distributeSpacing`, `appearance.targetContents` and `paint.invert`. +They also list these UI commands, which have no menu bar item and no default shortcut and whose params are all +optional: `ui.newSwatch`, `ui.newColorGroup`, `ui.colorGroupOptions`, `ui.newBrush`, `ui.brushOptions`, +`ui.layerOptions`, `ui.corners`, `ui.placementOptionsDialog`, `ui.relinkDialog`, `ui.perspectivePlane`, +`ui.bulletsAndNumbering`, `ui.missingFontsDialog` and `ui.findFontsInFolder`. A key assigned to one runs it with no +params, as `{}` does: it opens the dialog for the selection or the current item, or the status bar shows why it cannot, +for example "no brush selected". + Edit › Keyboard Shortcuts and `shortcuts.list` leave out a command with no default shortcut when a key press cannot run it: no item of the menu bar runs it, it opens no dialog when run without params, and it is one of these: diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c74a8a8d7b..16eeae3941 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -416,7 +416,9 @@ the type shortcuts (tracking/kerning/leading/baseline steps with Alt/Shift), and Layers panel. The shortcut editor also lists the commands that are in no menu but run without parameters (Edit › Duplicate, panel-menu commands such as Break Link to Symbol), so they can be given shortcuts (#1539). It lists each button of the Align panel's Align Objects, Distribute Objects and Distribute Spacing rows under Align, with no default shortcut, and a -shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). +shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. +It also lists the panel and dialog commands whose parameters are all optional, such as New Swatch…, Brush Options… +and Corners…, and a shortcut set there opens the dialog for the selection or says in the status bar why it cannot. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Cmd/Ctrl+Alt+. (`stroke.weightUp`, Stroke Weight Up) and Cmd/Ctrl+Alt+, (`stroke.weightDown`, Stroke Weight Down), the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) gives them, step the weight of each selected stroke from its own weight: by a quarter unit of Units › Stroke up to one unit, then by whole units, down to a quarter unit; with nothing selected they step the weight of the next object drawn (#5797). From 476437f29dd11064dd18ff53ed1cf1487ce5d199 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:03:30 -0800 Subject: [PATCH 076/107] 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 077/107] 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 617e00a3a47a35259bdffc3850791ab3fd1dd39c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:10:39 -0800 Subject: [PATCH 078/107] Keyboard Shortcuts: commands without a menu path are grouped by their menu or panel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit › Keyboard Shortcuts grouped a command that no menu holds by the first part of its id, so UI commands showed under "Ui", and others under "Addon", "App", "Css", "ImageTrace", "Plugin" and similar names that no catalog translates. Such a command now takes the menu path of the menu bar item that runs it (Recolor Artwork… goes under Edit › Edit Colors). Otherwise it takes the path its family's menu bar items share (Remove Corners goes under Object › Plug-ins › Path Precision Tools), or the menu or panel that holds it from a table (Rename under Window › Layers, Justification under Window › Paragraph). Only a command none of these cover keeps the group of its id. When a command the menu bar runs now has the group and label of an engine command no menu bar item runs, both are listed and the engine command shows its key: Object › Expand… is the Expand dialog, and object.expand shows as Object › Expand… (object.expand). --- crates/ui-egui/src/shortcut_editor.rs | 196 ++++++++++++++++++++++---- 1 file changed, 172 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index c02f72f02e..3417515bf1 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -226,7 +226,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(c.id); } - let group = if c.menu.is_empty() { id_group(c.id) } else { c.menu.join(" › ") }; + let group = command_group(c.id, c.menu); v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false }); } v.extend(crate::state::all_panels().map(|(id, label)| Entry { @@ -246,28 +246,30 @@ fn fixed_entries() -> &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(id); } - tail.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false, shows_key: false }); + tail.push(Entry { key: id.to_string(), label: label.to_string(), group: command_group(id, &[]), is_tool: false, shows_key: false }); } // A command listed only because an item of the menu bar runs it can have the group and // label of another entry. When that entry is an engine command that no item of the menu bar - // runs, the command the item runs keeps the name and the other entry is shown in the group - // of its id: File › Export Selection… runs `file.exportSelection`, as the menu item does, - // and `document.exportSelection` shows as Document › Export Selection…. Otherwise the - // command is left out: Window › Learn stays the Learn panel's entry. Entries that still - // have the same name, plug-ins included, are given names of their own by - // [`distinct_names`]. + // runs, the command the item runs keeps the name and the other entry is shown in its own + // group ([`own_group`]): File › Export Selection… runs `file.exportSelection`, as the menu + // item does, and `document.exportSelection` shows as Document › Export Selection…. When + // that is the group the other entry has already, both are listed: Object › Expand… runs + // the Expand dialog, and `object.expand` shows its key. Otherwise the command is left out: + // Window › Learn stays the Learn panel's entry. Entries that still have the same name, + // plug-ins included, are given names of their own by [`distinct_names`]. let name = |e: &Entry| (e.group.clone(), e.label.clone()); - let new_names: HashSet<_> = v.iter().chain(&tail).filter(|e| by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); - for e in v.iter_mut().chain(tail.iter_mut()) { - if new_names.contains(&name(e)) - && !by_the_menu_bar.contains(e.key.as_str()) + let movable = |e: &Entry| { + !by_the_menu_bar.contains(e.key.as_str()) && vectorcraft_engine::find_command(&e.key).is_some() && !menu_bar_items().contains_key(e.key.as_str()) - { - e.group = id_group(&e.key); + }; + let new_names: HashSet<_> = v.iter().chain(&tail).filter(|e| by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); + for e in v.iter_mut().chain(tail.iter_mut()) { + if new_names.contains(&name(e)) && movable(e) { + e.group = own_group(&e.key); } } - let names: HashSet<_> = v.iter().chain(&tail).filter(|e| !by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); + let names: HashSet<_> = v.iter().chain(&tail).filter(|e| !by_the_menu_bar.contains(e.key.as_str()) && !movable(e)).map(name).collect(); let keep = |e: &Entry| !by_the_menu_bar.contains(e.key.as_str()) || !names.contains(&name(e)); v.retain(keep); tail.retain(keep); @@ -402,6 +404,102 @@ fn name_of(e: &Entry, group: &str, label: &str) -> String { if e.shows_key { format!("{name} ({})", e.key) } else { name } } +/// The group of command `id`, whose menu path is `menu`: that path, or for a command no menu holds +/// the menu path of the item of the menu bar that runs it ([`menu_bar_path`]: Recolor Artwork… +/// goes under Edit › Edit Colors), or else [`own_group`]. +fn command_group(id: &str, menu: &[&str]) -> String { + if !menu.is_empty() { + return menu.join(" › "); + } + menu_bar_path(id).map_or_else(|| own_group(id), str::to_string) +} + +/// The group of a command that neither a menu nor an item of the menu bar holds: the menu path the +/// items of the menu bar that run the commands of its id's first two parts share (Remove Corners +/// goes under Object › Plug-ins › Path Precision Tools with Set Corners), else its [`GROUPS`] +/// entry, else [`id_group`]. +fn own_group(id: &str) -> String { + if let Some(path) = family_path(id) { + return path.to_string(); + } + GROUPS + .iter() + .find(|(key, _)| if key.ends_with('.') { id.starts_with(key) } else { id == *key }) + .map_or_else(|| id_group(id), |(_, g)| g.to_string()) +} + +/// The one menu path of the items of the menu bar that run the other commands whose id starts with +/// the first two parts of an id of three or more parts (`addon.pathtools.`). +fn family_path(id: &str) -> Option<&'static str> { + let mut parts = id.splitn(3, '.'); + let (Some(a), Some(b), Some(_)) = (parts.next(), parts.next(), parts.next()) else { return None }; + let prefix = format!("{a}.{b}."); + let mut paths = menu_bar_paths().keys().filter(|k| k.starts_with(&prefix) && k.as_str() != id).filter_map(|k| menu_bar_path(k)); + let first = paths.next()?; + paths.all(|p| p == first).then_some(first) +} + +/// The groups of the commands of Keyboard Shortcuts that no menu holds and whose id's first part +/// is no name: (id, or the start of ids when it ends with `.`; group). A panel's commands go under +/// the panel's Window menu item (Window › Layers), and a dialog's under the menu or panel that +/// opens it. +const GROUPS: &[(&str, &str)] = &[ + ("addon.", "Object › Plug-ins"), + ("app.", "Application"), + ("css.", "Window › CSS Properties"), + ("docInfo.", "Window › Document Info"), + ("imageTrace.", "Window › Image Trace"), + ("livePaint.", "Object › Live Paint"), + ("plugin.", "Object › Plug-ins"), + ("svgFilter.", "SVG Filters"), + ("svgInteractivity.", "Window › SVG Interactivity"), + ("threeD.", "Window › 3D and Materials"), + ("ui.action.", "Window › Actions"), + ("ui.actionSet.", "Window › Actions"), + ("ui.blendOptions", "Window › Properties"), + ("ui.brushObjectOptions", "Window › Brushes"), + ("ui.colorGuideOptions", "Window › Color Guide"), + ("ui.colorPicker", "Color"), + ("ui.colorRgbPercent", "Window › Color"), + ("ui.dialogReset", "Dialogs"), + ("ui.dxfOptionsDialog", "File"), + ("ui.epsOptionsDialog", "File"), + ("ui.fileInfoDialog", "File"), + ("ui.findAndReplace", "Window › Properties"), + ("ui.hpglOptionsDialog", "File"), + ("ui.hyphenation", "Window › Paragraph"), + ("ui.javascriptFilesDialog", "Window › SVG Interactivity"), + ("ui.justification", "Window › Paragraph"), + ("ui.layersPanelOptions", "Window › Layers"), + ("ui.loadAllStyles", "Window › Character Styles"), + ("ui.loadCharStyles", "Window › Character Styles"), + ("ui.loadParaStyles", "Window › Paragraph Styles"), + ("ui.newArtboard", "Window › Artboards"), + ("ui.newCharStyle", "Window › Character Styles"), + ("ui.newLayer", "Window › Layers"), + ("ui.newParaStyle", "Window › Paragraph Styles"), + ("ui.pdfSummary.", "File"), + ("ui.perspectiveUserPreset1.", "View › Perspective Grid › One Point Perspective"), + ("ui.perspectiveUserPreset2.", "View › Perspective Grid › Two Point Perspective"), + ("ui.perspectiveUserPreset3.", "View › Perspective Grid › Three Point Perspective"), + ("ui.rasterEffectsSettingsDialog", "Effect"), + ("ui.recolorRedo", "Edit › Edit Colors › Recolor Artwork"), + ("ui.recolorUndo", "Edit › Edit Colors › Recolor Artwork"), + ("ui.rename", "Window › Layers"), + ("ui.retype", "Window › Properties"), + ("ui.runInstalledScript", "File › Scripts"), + ("ui.sampleScreenColor", "Color"), + ("ui.savePdfDialog", "File"), + ("ui.shortcutImportDialog", "Shortcuts"), + ("ui.simplifyAuto", "Object › Path › Simplify"), + ("ui.simplifyMoreOptions", "Object › Path › Simplify"), + ("ui.smoothAuto", "Object › Path › Smooth"), + ("ui.spotColors", "Window › Swatches"), + ("ui.symbolOptions", "Window › Symbols"), + ("ui.tateChuYokoSettings", "Window › Character"), + ("ui.warichuSettings", "Window › Character"), +]; + /// The group of a command no menu holds: the first part of its id, capitalised (`edit.x` → "Edit"). fn id_group(id: &str) -> String { let mut c = id.split('.').next().unwrap_or_default().chars(); @@ -410,7 +508,7 @@ fn id_group(id: &str) -> String { /// Gives entries that have the same group and label names of their own, and leaves the others as /// they are. It runs on the whole snapshot, plug-ins included, after [`fixed_entries`] has shown an -/// engine command in the group of its id or left out a command listed only because an item of the +/// engine command in its own group ([`own_group`]) or left out a command listed only because an item of the /// menu bar runs it: /// 1. A command that an item of the menu bar runs, as a key press would run it, is shown under /// that item's menu path ([`menu_bar_path`]): the four Other Library… commands go under Window › @@ -2219,8 +2317,8 @@ mod tests { /// params, or with the one set of params all its items give) is listed in Edit › Keyboard /// Shortcuts, also when the command has no menu path of its own: Set Corners…, whose params doc /// names a field a call must give, the Perspective Grid toggles, Edit Custom Dictionary…, a - /// query, and Recolor Artwork…, a UI command. Such a command is listed in the group of its id, - /// next to the commands of its family that were listed before. A shortcut given to one survives + /// query, and Recolor Artwork…, a UI command. Such a command is listed under the menu path of + /// the item that runs it. A shortcut given to one survives /// a saved set's round trip. Find Next is left out: its menu item gives `find` empty, which the /// command rejects. When another entry has the same group and label, the command the menu item /// runs keeps the name if no menu item runs the other: File › Export Selection… is @@ -2244,7 +2342,9 @@ mod tests { assert_eq!(shown("file.exportSelection"), Some(("File".into(), "Export Selection…".into()))); assert_eq!(shown("document.exportSelection"), Some(("Document".into(), "Export Selection…".into()))); // No command listed only because an item of the menu bar runs it shares its group and label - // with another entry. + // with another entry, except an engine command that no item of the menu bar runs, whose own + // group is the same: that one shows its key. + let off_the_bar = |k: &str| vectorcraft_engine::find_command(k).is_some() && !menu_bar_items().contains_key(k); let own = |k: &str| { vectorcraft_engine::command_specs() .iter() @@ -2258,13 +2358,19 @@ mod tests { for e in v.iter().chain(tail) { names.entry((e.group.as_str(), e.label.as_str())).or_default().push(e.key.as_str()); } - let shared: Vec<_> = names.iter().filter(|(_, keys)| keys.len() > 1 && keys.iter().any(|k| !own(k))).collect(); + let shared: Vec<_> = names + .iter() + .filter(|(_, keys)| keys.len() > 1 && keys.iter().any(|k| !own(k)) && !keys.iter().filter(|k| own(k)).all(|k| off_the_bar(k))) + .collect(); assert!(shared.is_empty(), "{shared:?}"); + let keyed = |id: &str| entry(id).map(|e| (e.group, e.label, e.shows_key)); + assert_eq!(keyed("ui.expandDialog"), Some(("Object".into(), "Expand…".into(), false))); + assert_eq!(keyed("object.expand"), Some(("Object".into(), "Expand…".into(), true))); for (id, group) in [ - (crate::addons::pathtools::set_corners::COMMAND, "Addon"), - ("perspective.grid.snap", "Perspective"), - (crate::dialogs::custom_dictionary::COMMAND, "Text"), - ("ui.recolorDialog", "Ui"), + (crate::addons::pathtools::set_corners::COMMAND, "Object › Plug-ins › Path Precision Tools"), + ("perspective.grid.snap", "View › Perspective Grid"), + (crate::dialogs::custom_dictionary::COMMAND, "Edit"), + ("ui.recolorDialog", "Edit › Edit Colors"), ] { let e = entry(id).unwrap_or_else(|| panic!("{id} is listed")); assert_eq!(e.group, group, "{id}"); @@ -2575,4 +2681,46 @@ mod tests { assert!(needs_a_value("document.setUnits")); assert!(crate::palette::items().iter().all(|(_, id)| id != "document.setUnits")); } + + /// A command no menu holds is grouped under the menu path of the item of the menu bar that runs + /// it, or under the menu or panel it belongs to: no entry's group is a run-together id part + /// such as "Ui", "ImageTrace" or "ThreeD". + #[test] + fn commands_no_menu_holds_are_grouped_by_their_menu_or_panel() { + let menu_less = + |key: &str| vectorcraft_engine::find_command(key).map_or_else(|| menus::UI_COMMANDS.iter().any(|c| c.0 == key), |c| c.menu.is_empty()); + let mut names: HashSet = ["Tools", "Window"].into_iter().map(String::from).collect(); + names.extend(crate::state::all_panels().map(|(_, label)| label.to_string())); + names.extend(menus::menu_tree().into_iter().map(|(top, _)| top.to_string())); + names.extend(menu_bar_paths().values().flatten().flat_map(|(path, _)| path.split(" › ")).map(String::from)); + // A dialog's commands go under its command's label: Recolor Artwork, Character Style Options. + let labels = menus::UI_COMMANDS.iter().map(|c| c.1).chain(vectorcraft_engine::command_specs().iter().map(|c| c.label)); + names.extend(labels.map(|label| label.trim_end_matches('…').to_string())); + let mut wrong = vec![]; + for e in entries().iter().filter(|e| !e.is_tool && !e.key.contains(':') && menu_less(&e.key)) { + if let Some(path) = menu_bar_path(&e.key) + && e.group != path + { + wrong.push(format!("{}: {} is not under {path}", e.key, e.group)); + } + for part in e.group.split(" › ") { + let one_word = !part.contains(' ') && part.chars().skip(1).all(|c| !c.is_uppercase()); + if !names.contains(part) && (!one_word || ["Ui", "App", "Addon", "Css", "Plugin"].contains(&part)) { + wrong.push(format!("{}: {}", e.key, e.group)); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + // Every row of GROUPS groups a listed command. + let unused: Vec<_> = GROUPS + .iter() + .filter(|(key, _)| !entries().iter().any(|e| if key.ends_with('.') { e.key.starts_with(key) } else { e.key == *key })) + .collect(); + assert!(unused.is_empty(), "{unused:?}"); + let group = |id: &str| entry(id).map(|e| e.group); + assert_eq!(group("ui.recolorDialog").as_deref(), Some("Edit › Edit Colors")); + assert_eq!(group("ui.rename").as_deref(), Some("Window › Layers")); + assert_eq!(group("ui.justification").as_deref(), Some("Window › Paragraph")); + assert_eq!(group("addon.pathtools.cornerRemove").as_deref(), Some("Object › Plug-ins › Path Precision Tools")); + } } From 9ddded7242b185eb036addd9149fcce24415fc72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:17:15 -0800 Subject: [PATCH 079/107] 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 3e5299a1d688fc4cca919748088ee953331070df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:22:21 -0800 Subject: [PATCH 080/107] Shape tools: a huge circle through Shift-clicked points is previewed solid The Ellipse tool previewed the circle through two Shift-clicked points and the pointer as a dashed outline at any size. The canvas dashes an outline along its whole length, so points nearly on one line (a radius of about 1,250,000 pt) gave about a million dashes every frame. The preview now uses the Circle tool's limit: a circle more than 50,000 screen points around is drawn solid. Both tools call one helper, `circle::preview_dashed`. --- crates/tools/src/circle.rs | 11 +++++++---- crates/tools/src/shape.rs | 4 ++-- crates/tools/src/shape/tests.rs | 31 +++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 37c0e33bcd..52c3de1664 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -224,6 +224,12 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } } +/// Whether a circle preview of radius `r` is drawn dashed. The canvas draws a dashed outline dash by +/// dash along its whole length, so a circle longer than [`DASHED_PX`] on screen is drawn solid. +pub(crate) fn preview_dashed(cx: &ToolContext, r: f64) -> bool { + std::f64::consts::TAU * r <= cx.tol(DASHED_PX) +} + /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? fn too_large(points: &[Point], centered: bool, standard_anchors: bool) -> bool { @@ -573,10 +579,7 @@ impl Tool for CircleTool { let on_outline = if self.centered { points.get(1..).unwrap_or(&[]) } else { &points[..] }; shapes::circle_with_anchors_at(c, r, on_outline).to_bezpath() }; - // The canvas draws a dashed outline dash by dash along its whole length: a circle longer - // than DASHED_PX on screen is drawn solid instead. - let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); - o.push(Overlay::Path { path, color, width: 1.0, dashed }); + o.push(Overlay::Path { path, color, width: 1.0, dashed: preview_dashed(cx, r) }); let opts = self.options; let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb); if opts.radii { diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index b93c94dddc..cb288e5938 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -999,7 +999,7 @@ impl Tool for ShapeTool { let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() }; o.extend(self.guides.iter().cloned()); // The points Shift-clicks placed, and after two of them the circle through them and the - // pointer, dashed. + // pointer, dashed (solid when it is too long on screen, as the Circle tool draws it). for p in &self.through { o.push(Overlay::Anchor { p: *p, color: crate::draw2::FEEDBACK, filled: true, size: 6.0 }); } @@ -1007,7 +1007,7 @@ impl Tool for ShapeTool { && let Some((c, r)) = vectorcraft_geom::shapes::circle_through(*a, *b, h) { let path = vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); - o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: true }); + o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: crate::circle::preview_dashed(cx, r) }); } if let Some((p, text)) = &self.measure { o.push(Overlay::Measure { p: *p, text: text.clone() }); diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index fa089bf4e7..993fc9c104 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -667,6 +667,37 @@ fn the_circle_preview_passes_through_the_snapped_pointer() { assert!(matches!(&a[..], [Action::Exec(_, v)] if v["points"][2] == json!([100.0, 100.0])), "{a:?}"); } +/// A circle through the Shift-clicked points more than 50,000 screen points around is previewed +/// solid, as the Circle tool previews it: points nearly on one line give a radius of about +/// 1,250,000 pt. +#[test] +fn a_huge_circle_through_shift_clicked_points_is_previewed_solid() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + for (x, y) in [(0.0, 0.0), (1000.0, 0.0)] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)); + } + let paths = |t: &ShapeTool| { + t.overlays(&cx) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { dashed, .. } => Some(dashed), + _ => None, + }) + .collect::>() + }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 0.1)); + assert_eq!(paths(&t), vec![false]); + // At 100% a circle 100 pt across is dashed. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 300.0)); + assert_eq!(paths(&t), vec![true]); +} + /// Escape, a plain click and a drag drop the points Shift-clicks placed, so the next Shift-click /// starts a new circle. #[test] From eb27774471493535a90f9529058b0110b3e4748a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:17:24 -0800 Subject: [PATCH 081/107] Canvas: Shift+F10 and the Menu key open the menu for the selection as it is A key request for the canvas menu reaches the app at the view's centre. The menu treated it as a right-click there: it selected the object under the centre, listed the locked objects and the misspelled word found there, and with the Artboard tool selected the artboard there. The canvas now passes the request's source on. A key request keeps the selection, opens the menu at the part of the selection in view (the selected artboards with the Artboard tool), or at the view's centre when none of it is in view, and looks up nothing under a point. A right-click still selects what is under the pointer. --- crates/ui-egui/src/canvas.rs | 20 +++- crates/ui-egui/src/canvas/context_menu.rs | 66 ++++++++++-- crates/ui-egui/src/panels/artboards.rs | 10 +- crates/ui-egui/src/tests/contextmenu.rs | 122 ++++++++++++++++++++++ 4 files changed, 202 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 596cb119f0..38bbc5c78e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,7 +5,8 @@ use craft::behavior::{CanvasView, PressPhase}; use craft::keymap::Mods; use craft::ui::canvas::{ - Canvas, CanvasScrollbars, CanvasSpace, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass, + Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, + canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; use craft::ui::runtime::env::Env; @@ -133,6 +134,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { struct Body { reply: Option, context_at: Option, + /// The pasteboard's `context_at` answers the Menu key or Shift+F10, not a secondary click. + context_key: bool, /// A view a compass or scroll bar edit made this pass. edited: Option, } @@ -210,8 +213,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, edited } = body; - let request = reply.as_ref().and_then(|r| r.context.as_ref()).map(|c| c.at).or(context_at); + let Body { reply, context_at, context_key, edited } = body; + let request = reply + .as_ref() + .and_then(|r| r.context.as_ref()) + .map(|c| context_menu::Request { at: c.at, key: c.source == ContextSource::Key }) + .or(context_at.map(|at| context_menu::Request { at, key: context_key })); let jumped = edited.is_some(); // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own. let view_now = @@ -242,7 +249,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin 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; - let mut out = Body { context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), ..Body::default() }; + let background = space.background(); + let mut out = Body { + context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), + context_key: background.context.is_none() && background.context_key, + ..Body::default() + }; grids(app, ui, space, win); if live { find_shown_tool(app, ui.ctx(), space); diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index 146e91d039..853ec2e038 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -4,25 +4,39 @@ use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; use craft::ui::menu::Menu; use egui::Pos2; use serde_json::json; +use vectorcraft_geom::Point; use super::marks; use super::outline::{hit_with, selection_hit_at}; use crate::VectorcraftApp; -/// The canvas context menu (right-click, Menu key, Shift+F10). A `request` (screen points: the pointer, or -/// the view centre for a key) selects the object under it unless it already is, then the menu lists what -/// applies to the selection ([`crate::menus::context_items`]) at that point until it closes. The locked -/// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` -/// for its Unlock submenu. With the Intertwine tool, a right-click where three or more objects of the group -/// overlap keeps the selection and puts what it arranges in `ui.context_intertwine` -/// ([`vectorcraft_tools::intertwine::menu_target`]). With the Artboard tool, an artboard takes the place of -/// the object ([`crate::panels::artboards::right_click`]). +/// A request for the canvas menu at `at` (screen points): a secondary click at the pointer, or the Menu key or +/// Shift+F10 (`key`), which the canvas reports at the view centre. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Request { + pub(crate) at: Pos2, + pub(crate) key: bool, +} + +/// The canvas context menu (right-click, Menu key, Shift+F10). A right-click selects the object under the +/// pointer unless it already is, then the menu lists what applies to the selection +/// ([`crate::menus::context_items`]) at that point until it closes. The locked objects under the pointer +/// ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` for its Unlock submenu. With +/// the Intertwine tool, a right-click where three or more objects of the group overlap keeps the selection and +/// puts what it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). With the +/// Artboard tool, an artboard takes the place of the object ([`crate::panels::artboards::right_click`]). A key +/// request keeps the selection and opens the menu at it ([`prepare_key`]). /// /// Called on every pass after the canvas shows, with its response as `opener`: the menu is shown from the /// point stored in `ui.context_menu_at`, so a later pass without a request keeps it open. -pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { - if let Some(at) = request { - prepare(app, space, at); +pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { + if let Some(request) = request { + let at = if request.key { + prepare_key(app, space) + } else { + prepare(app, space, request.at); + request.at + }; app.ui.context_menu_at = Some(at); } let Some(at) = app.ui.context_menu_at else { return }; @@ -69,3 +83,33 @@ fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let _ = app.run("select.set", json!({ "ids": [top.0] })); } } + +/// The one-shot work of a key request: the menu is for the selection as it is (the selected artboards with the +/// Artboard tool), at the centre of the part of it in view, or at the view centre when none of it is in view. +/// Nothing under a point is looked up: no locked objects, word or Intertwine target. Returns the menu's point. +fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { + app.ui.context_locked = None; + app.ui.context_intertwine = None; + app.ui.context_spelling = None; + let on_artboards = app.session.tool_id() == "artboard"; + let bounds = if on_artboards { + app.session.active().and_then(|st| { + let picked = crate::panels::artboards::picked(app, st.doc.artboards.len()); + picked.iter().filter_map(|&i| st.doc.artboards.get(i).map(|a| a.rect)).reduce(|a, b| a.union(b)) + }) + } else { + app.selection_bounds() + }; + let view = &space.view; + let at = bounds + .map(|b| { + egui::Rect::from_points(&[b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)].map(|p| view.to_screen(p))) + }) + .map(|r| r.intersect(view.rect)) + .filter(|r| !r.is_negative()) + .map_or(view.rect.center(), |r| r.center()); + if on_artboards { + crate::panels::artboards::measure_menu(app, view.to_doc(at)); + } + at +} diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 19ab69b734..68e297cd44 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -324,10 +324,18 @@ pub(crate) fn fit_has_art(app: &VectorcraftApp, indices: &[usize]) -> bool { /// isn't selected becomes the only selected one, and the menu's facts are measured. pub(crate) fn right_click(app: &mut VectorcraftApp, p: vectorcraft_geom::Point) { let Some(st) = app.session.active() else { return }; - let (uid, n, hit) = (st.uid, st.doc.artboards.len(), st.doc.artboard_at(p)); + let (n, hit) = (st.doc.artboards.len(), st.doc.artboard_at(p)); if let Some(i) = hit.filter(|i| !picked(app, n).contains(i)) { select(app, i); } + measure_menu(app, p); +} + +/// The canvas menu's facts for the selected artboards, with the menu opened at `p` (a right-click, or the Menu key or +/// Shift+F10, which select nothing). +pub(crate) fn measure_menu(app: &mut VectorcraftApp, p: vectorcraft_geom::Point) { + let Some(st) = app.session.active() else { return }; + let (uid, n) = (st.uid, st.doc.artboards.len()); let all = picked(app, n); let any_empty = vectorcraft_engine::find_command("artboard.deleteEmpty").is_some_and(|c| (c.enabled)(&app.session).is_ok()); let any_art = fit_has_art(app, &all); diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 2ec147e593..441817c8b8 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -134,6 +134,128 @@ fn right_click_on_empty_canvas_offers_the_view_and_selects_nothing() { assert_eq!(app.session.active().unwrap().doc.art_bounds(), None); } +/// The document point at the centre of the canvas view, where a key request reports itself. +fn view_centre(app: &VectorcraftApp) -> Point { + let view = app.canvas_view().unwrap(); + view.to_doc(view.rect.center()) +} + +/// `key` with `modifiers`, pressed on the focused canvas, then a frame to show the result. +fn menu_key(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + frame(app, ctx, vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + frame(app, ctx, vec![]); +} + +/// Rectangle A, selected with a click (which also gives the canvas the keyboard focus), and an unselected +/// rectangle B under the view's centre with a locked rectangle over it. +fn selection_away_from_the_centre(app: &mut VectorcraftApp, ctx: &egui::Context) -> (NodeId, NodeId) { + let a = rect(app, 0.0, 0.0); + frame(app, ctx, vec![]); + let c = view_centre(app); + let b = rect(app, c.x - 50.0, c.y - 50.0); + let locked = rect(app, c.x - 25.0, c.y - 25.0); + app.run("layer.setProps", json!({"ids": [locked.0], "locked": true})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let p = screen(app, 50.0, 50.0); + click(app, ctx, p, PointerButton::Primary); + assert_eq!(app.session.active().unwrap().selection.objects, [a]); + (a, b) +} + +/// Asserts the menu opened for `a` as selected, at a point over it, without what lies under the view's centre. +fn opened_for_the_selection(app: &VectorcraftApp, a: NodeId) { + assert_eq!(app.session.active().unwrap().selection.objects, [a], "a key request keeps the selection"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let over_a = Rect::from_two_pos(screen(app, 0.0, 0.0), screen(app, 100.0, 100.0)); + assert!(over_a.contains(at), "the menu opens at the selection: {at:?} in {over_a:?}"); + assert!(has(app, "Arrange") && has_command(app, "object.arrange.bringToFront"), "{:?}", labels(app)); + assert!(app.ui.context_locked.is_none() && !has(app, "Unlock"), "nothing under the view's centre is measured"); +} + +#[test] +fn shift_f10_opens_the_menu_for_the_selection_without_changing_it() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (a, _) = selection_away_from_the_centre(&mut app, &ctx); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + opened_for_the_selection(&app, a); +} + +#[cfg(not(target_os = "macos"))] +#[test] +fn menu_key_opens_the_menu_for_the_selection_without_changing_it() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (a, _) = selection_away_from_the_centre(&mut app, &ctx); + menu_key(&mut app, &ctx, egui::Key::Menu, egui::Modifiers::NONE); + opened_for_the_selection(&app, a); +} + +/// With nothing selected, Shift+F10 opens the menu at the view's centre and selects nothing, even over an object. +#[test] +fn shift_f10_with_nothing_selected_opens_the_menu_at_the_view_centre() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let c = view_centre(&app); + rect(&mut app, c.x - 50.0, c.y - 50.0); + app.run("select.none", json!({})).unwrap(); + // A click on the empty artboard gives the canvas the focus and keeps the selection empty. + let p = screen(&app, 380.0, 280.0); + click(&mut app, &ctx, p, PointerButton::Primary); + assert!(app.session.active().unwrap().selection.objects.is_empty()); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "the object under the view's centre stays unselected"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let centre = app.canvas_view().unwrap().rect.center(); + assert!(at.distance(centre) < 0.5, "{at:?} at {centre:?}"); + assert!(has(&app, "Select All") && !has(&app, "Arrange"), "{:?}", labels(&app)); +} + +/// With the Artboard tool, Shift+F10 opens the menu for the selected artboard, at it, and selects no other artboard; +/// the menu's Paste would put artboards on it. +#[test] +fn shift_f10_with_the_artboard_tool_keeps_the_selected_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + crate::menus::invoke(&mut app, "view.fitAll", json!({})); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + let boards: Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let centre = view_centre(&app); + let away = boards.iter().position(|r| !r.contains(centre)).unwrap(); + app.select_tool("artboard"); + // A click on the artboard selects it and gives the canvas the focus. + let c = boards[away].center(); + let p = screen(&app, c.x, c.y); + click(&mut app, &ctx, p, PointerButton::Primary); + assert_eq!(crate::panels::artboards::picked(&app, boards.len()), [away]); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + assert_eq!(crate::panels::artboards::picked(&app, boards.len()), [away], "a key request keeps the selected artboard"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let on_board = Rect::from_two_pos(screen(&app, boards[away].x0, boards[away].y0), screen(&app, boards[away].x1, boards[away].y1)); + assert!(on_board.contains(at), "the menu opens at the selected artboard: {at:?} in {on_board:?}"); + let pasted_at = app.ui.context_artboards.as_ref().map(|f| f.at).expect("the menu's artboard facts"); + assert!(boards[away].contains(pasted_at), "{pasted_at:?} on {:?}", boards[away]); +} + +/// A right-click on an object that is not selected still selects it, with another object selected before. +#[test] +fn right_click_still_selects_the_object_under_the_pointer() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (_, b) = selection_away_from_the_centre(&mut app, &ctx); + // Inside B, outside the locked rectangle over its middle. + let c = view_centre(&app); + let p = screen(&app, c.x - 40.0, c.y - 40.0); + click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [b]); + assert!(app.ui.context_menu_at.is_some_and(|at| at.distance(p) < 0.5), "the menu opens at the pointer"); +} + /// A right-click over a locked object adds an Unlock submenu that lists the object by its name; once /// the menu is closed, the menu lists no Unlock items. #[test] From 55ff5e033e2c5d91a48073d59ada09347058f54a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:21:57 -0800 Subject: [PATCH 082/107] Control bar: the Paragraph: link stays after its Align buttons leave, as production kept it The Paragraph group was one ranked member at its call site, and a narrowing row drops a ranked member whole, so the link left with the Align left, Align center and Align right buttons. `panels/paragraph.rs::control_bar` now shows the link and the buttons as two members of `rank::TYPE`, and within one rank the bar drops the last member first. --- crates/ui-egui/src/chrome/control_bar.rs | 5 ++--- crates/ui-egui/src/chrome/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/panels/paragraph.rs | 8 ++++---- crates/ui-egui/src/panels/paragraph/tests.rs | 1 - 4 files changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ab90d71dc2..a0d69c55c5 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -609,9 +609,8 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) { }); } if typed && paragraph { - ranked(ui, rank::TYPE, |ui| { - crate::panels::paragraph::control_bar(app, ui); - }); + // The Paragraph group ranks its link and its Align buttons as two members, so the buttons leave first. + crate::panels::paragraph::control_bar(app, ui); } let vertical = group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some(); if vertical { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 2c3b214c69..ce79f1b608 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2551,6 +2551,26 @@ fn the_type_groups_leave_the_control_bar_before_opacity_and_style() { assert!(seen.iter().any(|s| s[2] && !s[0]), "some width shows Opacity without the Character group"); } +/// With type selected, the Paragraph group's Align left, Align center and Align right buttons leave the Control bar +/// before its Paragraph: link: some width shows the link without them, and no width shows them without the link. +#[test] +fn the_paragraph_link_stays_on_the_control_bar_after_its_align_buttons_leave() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [text] })).unwrap(); + let mut bar = control_shown(app); + let names = ["Paragraph:", "Align left", "Align center", "Align right"]; + let seen = control_bar_widths(&mut bar, &names); + assert!(seen.iter().any(|s| s.iter().all(|shown| *shown)), "a wide bar shows {names:?}"); + for s in &seen { + assert!(s[1..].iter().all(|shown| *shown == s[1]), "the three Align buttons show or go together: {s:?}"); + assert!(!s[1] || s[0], "the Align buttons show only with the Paragraph: link: {s:?}"); + } + assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Paragraph: link without the Align buttons"); +} + /// With area type selected, its vertical alignment buttons leave the Control bar before Opacity and the Style group, /// and after the Align buttons that follow them, with the Character and Paragraph groups shown and with both off. #[test] diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 2dd7f1f39f..26102b5311 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -434,19 +434,19 @@ pub(crate) fn alignment_toggles(app: &mut VectorcraftApp, ui: &mut Ui, count: us /// The Control bar's paragraph controls while type is selected or edited (#5372), after its /// Character controls: the Paragraph link, which opens the Paragraph panel in a popover under it, /// and the Align left, Align center and Align right buttons. Always `true`: the bar trims these -/// itself as it narrows. +/// itself as it narrows, the link and the buttons as two members of the type groups' rank, so the +/// buttons leave before the link. pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { if text_style(app).is_none() { return true; } - // PLAN: the members' `Row::fit_rank` (ch.K30: toggles out before the link) belongs to chrome-w16's row. - Row::new().show(ui, |ui, _| { + Row::new().fit_rank(crate::chrome::rank::TYPE).show(ui, |ui, _| { let link = crate::panels::option_link(tl!("Paragraph:")).tooltip(tl!("Paragraph options")).show(ui); Popover::new(tl!("Paragraph"), Bind::kept()) .overlay(|overlay| overlay.opened_by(&link.response, Trigger::Click)) .show(ui, |ui, _| show(app, ui)); - alignment_toggles(app, ui, CONTROL_BAR_ALIGNMENTS); }); + Row::new().fit_rank(crate::chrome::rank::TYPE).show(ui, |ui, _| alignment_toggles(app, ui, CONTROL_BAR_ALIGNMENTS)); true } diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 48b324ccf4..0d56471f6d 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -751,7 +751,6 @@ fn bar_names(app: &mut VectorcraftApp) -> Vec { /// #5372: with type selected the Control bar shows a Paragraph section: the Paragraph: link and the /// Align left, Align center and Align right buttons (the justifying four are in the panel the link /// opens); with no type selected it shows none of them. -// PLAN: the trimming order as the bar narrows (toggles out before the link, ch.K30) is chrome-w16's `Row::fit_rank` and is tested with its fixture. #[test] fn the_control_bar_shows_its_paragraph_section_for_selected_type_only() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); From 4d75149f13f07c48d67066726a864ad149d9cdf6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:41:32 -0800 Subject: [PATCH 083/107] Color Picker: pickers opened from dialogs have the Color Swatches view A Color Picker opened from a dialog's color row (effect dialogs, Artboard Options, Layer Options, Recolor Artwork), from the Dimension options and from Preferences had no Color Swatches button, because only the Fill/Stroke proxy's picker was given the swatch view. Recolor Artwork's Pick from Swatches asked for the swatches, but the picker drew its color models. - Every picker now has the swatch view: the document's swatches and the color libraries. - A picker over Recolor Artwork shows the library that Limit to Library limits the rows to. --- crates/ui-egui/src/dialogs/color_picker.rs | 28 ++++++++++++++++--- crates/ui-egui/src/dialogs/dimension.rs | 3 ++- crates/ui-egui/src/dialogs/recolor.rs | 6 +++++ crates/ui-egui/src/prefs_dialog.rs | 2 +- crates/ui-egui/src/tests/recolor.rs | 31 ++++++++++++++++++++++ 5 files changed, 65 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..e0ad66addf 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -6,7 +6,8 @@ //! `artboard.setProps {index, color}`. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog -//! and answers the row with its OK. The OK for a Save for Web colour table cell shifts the cell's +//! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor +//! Artwork shows the library that Limit to Library limits to. The OK for a Save for Web colour table cell shifts the cell's //! colour in the table instead ([`super::save_for_web::take_palette_pick`]). //! //! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`, @@ -104,7 +105,7 @@ pub(crate) fn open_picker(app: &VectorcraftApp) -> Option { /// The document's swatches and the swatch libraries as the picker's Color Swatches view: solid /// colours only, tints as their colour. -fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { +pub(crate) fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { let solid = |swatches: &[vectorcraft_color::Swatch]| -> Vec<(Label, Srgba)> { swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect() }; @@ -124,6 +125,15 @@ fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { PickerSwatches::new(libraries, tl!("Open a document to see its swatches.")) } +/// The index in [`swatch_view`]'s libraries of the library a Limit to Library key names +/// (`"document"` or a library id); `None` when the view does not list it. +fn library_index(app: &VectorcraftApp, limit: &str) -> Option { + if limit == swatchlib::DOCUMENT_SWATCHES { + return Some(0); + } + colour_libraries(app).iter().position(|lib| lib.id == limit).map(|i| i + 1) +} + /// The working CMYK profile as the picker's CMYK converter, so its CMYK fields follow the document's /// inks; `None` (the picker's built-in coated CMYK) when the profile can't link to sRGB. fn working_cmyk() -> Option { @@ -204,8 +214,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { while let Some((parent, request)) = dialogs.with(|h| h.take_color_request()) { let start = request.color.unwrap_or(Srgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }); let key = request.key.clone(); - let child = ColorPickerDialog::from_request(request).eyedropper(true).add_to_swatches(false).gamut(gamut(app)).working_rgb(WorkingRgb); + let library = super::recolor::limit_to(&dialogs, parent).and_then(|limit| library_index(app, &limit)); + let child = ColorPickerDialog::from_request(request) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); let id = dialogs.with(|h| h.open_child(child, parent)); + // Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to. + if let Some(i) = library + && let Err(e) = dialogs.with(|h| h.set_json_field(ctx, id, "library", json!(i))) + { + app.status(e); + } app.color_dialogs.pickers.push(Open { id, target: Target::Answer { parent, key }, start, keep: false, preview: LivePreview::default() }); } let busy = app.screen_pick.busy(); diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 805a502223..b53bab2351 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -718,7 +718,8 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { && let Some(dialogs) = app.dialogs() { let key = request.key.clone(); - let picker = dialogs.with(|host| host.open(ColorPickerDialog::from_request(request))); + let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app)); + let picker = dialogs.with(|host| host.open(picker)); app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) }); } Row::new().show(ui, |ui, _| { diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index c219fe1eed..1c5cfff224 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1621,6 +1621,12 @@ fn preview_params(d: &Fields) -> Option<(bool, &'static str, Value)> { }) } +/// The Limit to Library key (`"document"` or a library id) of `parent` when it is a Recolor Artwork +/// dialog that limits to a library: the library a Color Picker over it shows in its swatches view. +pub(super) fn limit_to(dialogs: &craft::ui::shell::WindowDialogs, parent: DialogId) -> Option { + dialogs.with(|host| host.get_by_id::(parent).map(|d| d.fields.str("limitTo"))).filter(|limit| !limit.is_empty()) +} + /// Runs the open dialog's live preview with `(on, command, params)`. fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) { let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return }; diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index a60148af5e..903c9bdd02 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -166,7 +166,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { }; w.state = state; if let Some(request) = out.pick_color { - w.nested.open(ColorPickerDialog::from_request(request)); + w.nested.open(ColorPickerDialog::from_request(request).swatch_view(crate::dialogs::color_picker::swatch_view(app))); } if out.closed.is_none() { app.prefs = Some(w); diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index f904500cdf..f46d94dccc 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1318,6 +1318,37 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { } } +/// A Color Picker opened over the dialog, on its color models, has the Color Swatches button that +/// switches it to the swatches. +#[test] +fn a_picker_over_the_dialog_offers_the_color_swatches_view() { + let mut r = edit(&["#ff0000", "#0000ff"]); + let at = marker(&r, 0); + right_click(&mut r, at); + tap(&mut r, "Color Picker"); + assert!(picker(&r).is_some(), "the marker's Color Picker opens the picker"); + assert!(has(&r, "Color Swatches"), "the picker has the Color Swatches button"); + tap(&mut r, "Color Swatches"); + assert!(has(&r, "Color Models"), "the button switches the picker to its swatches"); +} + +/// Pick from Swatches opens the picker on its swatches, showing the library that Limit to Library +/// limits the rows to. +#[test] +fn pick_from_swatches_shows_the_limit_to_library_library() { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let lib = library_of(&mut app, &[json!({"name": "Lib Teal", "color": "#008080"}), json!({"name": "Lib Plum", "color": "#8e4585"})]); + let mut r = assign(app, json!({"library": lib})); + assert_eq!(field(&r, "limitTo"), json!(lib)); + let at = rect(&r, "New 1").center(); + right_click(&mut r, at); + tap(&mut r, "Pick from Swatches"); + assert!(picker(&r).is_some(), "Pick from Swatches opens the Color Picker"); + assert!(has(&r, "Color Models"), "the picker shows its swatches, with the button back to the color models"); + assert!(has(&r, "Lib Teal") && has(&r, "Lib Plum"), "the swatches are the Limit to Library library's"); +} + /// Undo Changes and Redo Changes step back and forward through the dialog's own color edits, and /// the art previews each step; the document's undo history is unchanged until OK, which records /// one step. Both buttons start disabled, and a new edit after Undo Changes leaves nothing to redo. From 465c85ab33a69ee9a07a302a05ea1b858bbb0435 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:51:44 -0800 Subject: [PATCH 084/107] Workspaces: Painting shows the Tools panel in two columns again Every built-in workspace took its layout from default_workspace, which lays the Tools panel out in one column, so Painting lost the two-column Tools it had before the craft framework port, and Window > Toolbars > Double Column read unchecked after switching to it. A built-in now names its Tools column count, and Painting asks for two. No other built-in set a toolbar option of its own before the port. --- crates/ui-egui/src/panel_docking.rs | 8 ++++- crates/ui-egui/src/workspaces.rs | 52 ++++++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index dce3c4aa7b..eca959e802 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -155,6 +155,12 @@ fn rail_owner_among(toolbars: impl Iterator, id: &str) -> Option Workspace { + builtin_workspace(fronts, 1) +} + +/// [`default_workspace`] with the Tools panel laying its tools out in `tools_steps` columns, as a +/// built-in workspace defines it. +pub(crate) fn builtin_workspace(fronts: &[&str], tools_steps: u16) -> Workspace { let mut placed: Vec = Vec::new(); let mut group = |ids: &[&str]| { let fresh: Vec = ids.iter().filter(|id| registered(id) && !placed.iter().any(|p| p == *id)).map(|id| (*id).to_owned()).collect(); @@ -168,7 +174,7 @@ pub(crate) fn default_workspace(fronts: &[&str]) -> Workspace { if !icons.is_empty() { columns.push(Column::new(icons).with_iconic(true)); } - let tools = Column::new(vec![Group::new(vec![crate::toolbar::TOOLS.to_owned()], 0)]).with_steps(1); + let tools = Column::new(vec![Group::new(vec![crate::toolbar::TOOLS.to_owned()], 0)]).with_steps(tools_steps); let centre = Node::split(Axis::X, BESIDE_DOCK, Node::tabs(vec![CANVAS.to_owned()], 0), Node::dock(DockEdge::End, columns)); let root = Node::split(Axis::X, BESIDE_DOCK, Node::dock(DockEdge::Start, vec![tools]), centre); Workspace::new(Layout::new(Some(root), Vec::new())) diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 6e5f44988c..8db8048d65 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -209,13 +209,23 @@ pub const TOUCH: &str = "Touch"; /// The id of [`ESSENTIALS`]. const ESSENTIALS_ID: &str = "essentials"; -/// A built-in workspace: its name, the panels it brings to the front of their groups, and its record. +/// A built-in workspace: its name, the panels it brings to the front of their groups, the number +/// of columns its Tools panel lays the tools out in, and its record. pub struct Builtin { pub name: &'static str, pub fronts: &'static [&'static str], + pub tools_steps: u16, pub record: WorkspaceRecord, } +impl Builtin { + /// The workspace with its Tools panel in two columns (Window › Toolbars › Double Column on). + fn double_tools(mut self) -> Self { + self.tools_steps = 2; + self + } +} + /// The id of a built-in workspace: its lower-case name with dashes. fn builtin_id(name: &str) -> String { name.to_lowercase().replace(' ', "-") @@ -226,7 +236,7 @@ pub fn builtins() -> Vec { let w = |name: &'static str, fronts: &'static [&'static str], f: &dyn Fn(&mut WorkspaceRecord)| { let mut record = WorkspaceRecord::default(); f(&mut record); - Builtin { name, fronts, record } + Builtin { name, fronts, tools_steps: 1, record } }; vec![ w(ESSENTIALS, &[], &|_| {}), @@ -248,7 +258,8 @@ pub fn builtins() -> Vec { w("Painting", &["brushes"], &|x| { x.control_bar = true; x.toolbar_advanced = true; - }), + }) + .double_tools(), w("Printing and Proofing", &["info"], &|x| { x.control_bar = true; x.rulers = true; @@ -279,7 +290,10 @@ pub fn builtins() -> Vec { /// The built-ins as the framework's named workspaces. fn builtin_set() -> Vec> { - builtins().into_iter().map(|b| NamedWorkspace::new(builtin_id(b.name), b.name, crate::panel_docking::default_workspace(b.fronts))).collect() + builtins() + .into_iter() + .map(|b| NamedWorkspace::new(builtin_id(b.name), b.name, crate::panel_docking::builtin_workspace(b.fronts, b.tools_steps))) + .collect() } /// The chrome the set stores beside a layout, from `record`. Never read back: the record is the truth. @@ -745,6 +759,36 @@ mod tests { } } + /// Painting lays the Tools panel out in two columns and Window › Toolbars › Double Column reads + /// checked; every other built-in workspace has one column. Switching back to Essentials brings + /// back its own column count, as it was left, and Reset Painting gives two columns again. + #[test] + fn painting_shows_tools_in_two_columns_and_essentials_keeps_its_own() { + let steps = |app: &VectorcraftApp| { + crate::panel_docking::column_of(crate::panel_docking::layout_of(&app.ui), crate::toolbar::TOOLS).and_then(|(_, column)| column.steps) + }; + let double = |app: &VectorcraftApp| crate::menus::checked(app, "window.toolbarColumns", &json!({})); + let mut app = app(); + assert_eq!((steps(&app), double(&app)), (Some(1), Some(false)), "Essentials starts with one column"); + for b in builtins() { + switch(&mut app, b.name).unwrap(); + let painting = b.name == "Painting"; + assert_eq!(steps(&app), Some(if painting { 2 } else { 1 }), "{}", b.name); + assert_eq!(double(&app), Some(painting), "Double Column in {}", b.name); + } + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!((steps(&app), double(&app)), (Some(1), Some(false)), "Essentials has one column again"); + app.run("window.toolbarColumns", json!({"double": true})).unwrap(); + switch(&mut app, "Painting").unwrap(); + app.run("window.toolbarColumns", json!({"double": false})).unwrap(); + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!(double(&app), Some(true), "Essentials keeps the two columns it was left with"); + switch(&mut app, "Painting").unwrap(); + assert_eq!(double(&app), Some(false), "Painting keeps the one column it was left with"); + reset(&mut app); + assert_eq!((steps(&app), double(&app)), (Some(2), Some(true)), "Reset Painting gives two columns again"); + } + /// A file saved before `WorkspaceSet` names workspaces in any case: the layout remembered under /// another spelling belongs to the saved workspace, once; a name no workspace has is dropped, /// and a saved name equal to a built-in's is refused and reported. From 129eeb35902aaffee940e9c62567d3f9234264b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:52:02 -0800 Subject: [PATCH 085/107] macOS menu bar: every item shows its shortcut and takes it as its key equivalent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The native menu bar handed AppKit items without shortcuts: only the Window rows carried one, and Settings › General… carried the default ⌘K. Save, Open, Undo, Group and the other items showed no keys and had no key equivalents. - The native menu now gives each item the shortcut the menus show for it, else its command's chord in the window's keymap, the user's own set included, as the in-window bar's rows look it up. A rebound command shows its new key. - Settings › General… shows Preferences' current shortcut instead of the default one. - The Window rows' and Settings' shortcuts are read when the native menu is laid out, so they no longer stay empty after the first frame. --- crates/ui-egui/src/menus.rs | 4 +- crates/ui-egui/src/menus/labels.rs | 16 ++++++-- crates/ui-egui/src/menus/model.rs | 3 +- crates/ui-egui/src/menus/native.rs | 20 ++++++---- crates/ui-egui/src/menus/state.rs | 38 +++++++++++++------ crates/ui-egui/src/menus/tree.rs | 14 +++---- crates/ui-egui/src/tests/nativemenu.rs | 51 ++++++++++++++++++++++++++ 7 files changed, 112 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 0ce4ff457a..5291000751 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -83,14 +83,14 @@ pub(crate) use invoke::graph_dialog; pub use invoke::{click_target, invoke}; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; -pub(crate) use labels::{holds_plugin_commands, lists_plugin}; +pub(crate) use labels::{holds_plugin_commands, item_shortcut_in, lists_plugin}; pub(crate) use model::{MAC_LABELS, home_key, home_showing}; pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; -pub(crate) use state::why_off; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; +pub(crate) use state::{command_shortcuts, why_off}; pub(crate) use submenus::PATH_EFFECTS; pub use tree::{Listed, menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index bce650899b..1467de23c8 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -1,9 +1,10 @@ use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; -use super::state::{hidden_when_disabled, shortcut_of}; +use super::state::{command_shortcuts, hidden_when_disabled}; use super::tree::menu_tree; use super::ui_commands::UI_COMMANDS; use super::{Node, Value, VectorcraftApp, unbound}; -use craft::keymap::Chord; +use craft::keymap::{Chord, CommandRef}; +use vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES; /// Label for toggles whose text flips (Outline/Preview, Hide/Show …). pub fn dynamic_label(app: &VectorcraftApp, id: &str, label: &str) -> String { @@ -250,11 +251,18 @@ pub(super) fn spelling_item_label(id: &str, p: &Value) -> Option { /// The shortcut a menu item shows: its command's (items without params), a panel's for the /// Window menu's `window.panel {panel}` items, an effect's for the Effect menu's items, or a filter -/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. +/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. Settings' first page shows +/// Preferences' shortcut. pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option { + item_shortcut_in(&command_shortcuts(app), id, p) +} + +/// [`item_shortcut`] with each entry's command looked up in `chord` ([`command_shortcuts`]). +pub(crate) fn item_shortcut_in(chord: &dyn Fn(&CommandRef) -> Option, id: &str, p: &Value) -> Option { let field = |name: &str| p.get(name).and_then(Value::as_str); let key = match (id, field("panel")) { ("window.panel", Some(panel)) => format!("panel:{panel}"), + ("edit.preferences", _) if field("category") == PREF_CATEGORIES.first().copied() => id.to_string(), ("effect.dialog" | "effect.apply", _) => format!("effect:{}", field("effect")?), ("plugin.dialog", _) => format!("plugin:{}", field("id")?), // The Artboard tool's canvas menu passes the point its Paste goes to. @@ -265,7 +273,7 @@ pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option _ if p.is_null() => id.to_string(), _ => return None, }; - shortcut_of(app, &key) + chord(&crate::keymap::command_of(&key)) } /// Labels only the canvas context menu ([`context_items`]) shows, so the catalog tests can insist diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 421b763038..f00174b4ac 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -485,7 +485,8 @@ impl Build<'_> { match id { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. - "window.panel" => { + // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. + "window.panel" | "edit.preferences" if !params.is_null() => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 62fbc97da3..b9004c1ebb 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -1,12 +1,13 @@ //! The macOS menu bar on craft-menu's native menu: installed once, polled and run before the UI //! each frame, and synced after it. +use craft::keymap::{Chord, CommandRef}; use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac, mac_layout}; use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder}; use crate::VectorcraftApp; use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label}; -use crate::menus::unbound; +use crate::menus::{command_shortcuts, item_shortcut_in, unbound}; /// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its /// translation of the labels the layout writes itself. @@ -56,16 +57,20 @@ pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { app.services.native_menu = Some(menu); } -/// The menus with each item's title, and whether it is on and checked, as they are now: AppKit's items show their own, -/// where the in-window bar reads them from the command states. Read here and not from the model, which is built before -/// the frame's input: a drag released or an Escape in this frame already shows. +/// The menus with each item's title, shortcut, and whether it is on and checked, as they are now: AppKit's items show +/// their own, where the in-window bar reads them from the command states. Read here and not from the model, which is +/// built before the frame's input: a drag released or an Escape in this frame already shows. Each item's shortcut is +/// the one the menus show for it ([`crate::menus::item_shortcut`]), else its command's chord in the keymap, the user's +/// set included, as the in-window bar's rows show it. It is also the item's key equivalent. The model's own shortcuts +/// (Window rows, Settings' first page) are read again here: the model built before the window's first keymap has none. fn stated(app: &VectorcraftApp) -> MenuBar { - fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, nodes: &mut [Node]) { + fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, chord: &dyn Fn(&CommandRef) -> Option, nodes: &mut [Node]) { for node in nodes { match node { Node::Item(it) if unbound(&it.command.id) => it.enabled = false, Node::Item(it) => { let (id, params) = (it.command.id.as_str(), &it.command.params); + it.shortcut = item_shortcut_in(chord, id, params).or_else(|| chord(&it.command)); if let Some((enabled, checked)) = crate::menus::shown_state(app, id, params) { it.enabled = enabled; if let Some(on) = checked { @@ -78,15 +83,16 @@ fn stated(app: &VectorcraftApp) -> MenuBar { it.label = title; } } - Node::Submenu { children, .. } => walk(app, lang, children), + Node::Submenu { children, .. } => walk(app, lang, chord, children), _ => {} } } } let mut bar = app.menus.bar.clone(); let lang = crate::i18n::current(); + let chord = command_shortcuts(app); for menu in &mut bar.menus { - walk(app, lang, &mut menu.children); + walk(app, lang, &chord, &mut menu.children); } bar } diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b608e72feb..bce31f0fd0 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -2,7 +2,7 @@ use super::run::{normalize_panel, toolbar_double, toolbar_panel}; use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::{Brightness, Value, VectorcraftApp}; use crate::i18n::LangExt as _; -use craft::keymap::Chord; +use craft::keymap::{Chord, CommandRef}; use craft::ui::runtime::commands; /// Checked state for toggle items. @@ -190,17 +190,33 @@ pub fn plugin_revision() -> u64 { /// the window's keymap, under the user's set in use (Edit → Keyboard Shortcuts). `None` before the /// window's first frame. pub fn shortcut_of(app: &VectorcraftApp, key: &str) -> Option { - let ctx = app.ui_ctx.as_ref()?; - let command = crate::keymap::command_of(key); - let window = commands::keymap(ctx)?; - let (now, built) = (&*app.shortcut_overrides, window.overrides()); - if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { - return commands::chord(ctx, &command); - } + command_shortcuts(app)(&crate::keymap::command_of(key)) +} + +/// The shortcut each command shows, as [`shortcut_of`] reads it, for a caller that asks for many: the +/// keymap is read once. `None` for every command before the window's first frame. +pub(crate) fn command_shortcuts(app: &VectorcraftApp) -> impl Fn(&CommandRef) -> Option + '_ { + let ctx = app.ui_ctx.as_ref(); + let window = ctx.and_then(commands::keymap); // The window's keymap takes a change of the set (`shortcuts.set`) from its next frame; the set is read until then. - let mut keymap = (*window).clone(); - keymap.set_overrides(now.clone()); - keymap.bindings(&command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + let pending = window.as_ref().and_then(|window| { + let (now, built) = (&*app.shortcut_overrides, window.overrides()); + if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { + return None; + } + let mut keymap = (**window).clone(); + keymap.set_overrides(now.clone()); + Some(keymap) + }); + move |command| { + let ctx = ctx.filter(|_| window.is_some())?; + match &pending { + None => commands::chord(ctx, command), + Some(keymap) => { + keymap.bindings(command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + } + } + } } /// Is a command currently enabled? diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index c1ea0a7b84..2e1ce41559 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -890,15 +890,11 @@ fn not_mac() -> Platforms { fn app_menu() -> Vec { let settings: Vec = vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES .iter() - .enumerate() - .map(|(i, page)| { - let mut item = - Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings); - // Only the first page carries Preferences' shortcut. - if i == 0 { - item.shortcut = crate::shortcut_editor::default_command_shortcut("edit.preferences").and_then(crate::keymap::stored::parse_vc); - } - Node::Item(item) + // Only the first page carries Preferences' shortcut, which the menus' model gives it from the keymap. + .map(|page| { + Node::Item( + Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings), + ) }) .collect(); let mut language = vec![cp("Automatic", "app.language", json!({ "lang": "auto" })), Sep]; diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index 8a13fbda07..f1f6bcd09c 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -63,6 +63,57 @@ fn settings_lists_every_preferences_page() { assert_eq!(crate::prefs_dialog::page(&m.app), Some("Units")); } +/// The default shortcut of command `id`, as the shortcut editor lists it. +fn default_chord(id: &str) -> Option { + crate::shortcut_editor::default_command_shortcut(id).and_then(crate::keymap::stored::parse_vc) +} + +/// The Settings › General… item of `bar`. +fn general(bar: &MenuBar) -> &Item { + let page = PREF_CATEGORIES[0]; + bar.items().into_iter().find(|it| it.command.id == "edit.preferences" && it.command.params["category"] == page).expect("Settings › General…") +} + +/// The menu bar hands every item its command's shortcut, so Save, Open, Undo and Group show their keys and AppKit +/// takes them as key equivalents. +#[test] +fn native_items_carry_their_commands_shortcuts() { + let m = Mac::new(true); + let bar = m.fake.last(); + for id in ["file.save", "file.open", "edit.undo", "object.group"] { + let chord = default_chord(id); + assert!(chord.is_some(), "{id} has a default shortcut"); + assert_eq!(find(&bar, id).shortcut, chord, "{id}"); + } +} + +/// A command bound to another key shows that key in the menu bar, and its old key is no longer the item's. +#[test] +fn a_rebound_command_shows_its_new_key_in_the_menu_bar() { + let mut m = Mac::new(true); + let old = default_chord("object.group"); + m.app.run("shortcuts.set", json!({"id": "object.group", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = find(&m.fake.last(), "object.group").shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + +/// Settings › General… carries Preferences' shortcut as the user set it, not the default one. +#[test] +fn settings_general_follows_a_rebound_preferences() { + let mut m = Mac::new(true); + let old = default_chord("edit.preferences"); + assert_eq!(general(&m.fake.last()).shortcut, old); + m.app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = general(&m.fake.last()).shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + /// A native menu can't turn a plain item into a check item in place: the app's read of the menus /// is guarded by a state key, and these tests count the reads through a fake backend. /// From aa907c82e6ad51724dbaaa33a81532f99c7c1c05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:05:10 -0800 Subject: [PATCH 086/107] Status bar: the zoom field and the Navigator set the zoom typed at any UI Scaling The status bar's zoom field and the Navigator edit the canvas view, whose zoom is the view's zoom divided by UI Scaling. Both sent that canvas zoom to view.setZoom, which stores the zoom it is given, so at 150% UI Scaling typing 200% zoomed the view to 133.33%. View::zoom_of_canvas turns a canvas view's zoom back into the view's zoom, the inverse of View::canvas, and View::set_canvas uses it. The status bar and the Navigator convert the edited zoom with it before they run view.setZoom. --- crates/ui-egui/src/chrome/status_bar.rs | 4 +-- crates/ui-egui/src/chrome/tests.rs | 22 ++++++++++++++ crates/ui-egui/src/panels/navigator.rs | 38 ++++++++++++++++++++----- crates/ui-egui/src/state.rs | 8 +++++- 4 files changed, 62 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index c4b6f8a5fe..dcf3081dd2 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -68,9 +68,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let zoom = Field::new(tl!("Zoom")) .side(SideLabel::new().kind(LabelKind::Hidden)) .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); - // PLAN: assumed CanvasView::zoom and crate::state::zoom_display_percent(zoom, print) through the scheme (cv.S4). + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) { - zoom_to = Some(crate::state::zoom_display_percent(view.zoom, print)); + zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print)); } Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { // Entries are keyed by index: an angle is not a hashable value. diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 2c3b214c69..318ecf738c 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -806,6 +806,28 @@ fn set_zoom_100_matches_actual_size_with_display_print_size() { assert!((app.view().unwrap().zoom - 96.0 / 72.0).abs() < 1e-12); } +/// At UI Scaling 150% the zoom field shows the zoom `view.setZoom` set, and a zoom typed into it is the zoom the view +/// gets, as at 100%: 200% gives the view the zoom `view.setZoom` gives for 200%. +#[test] +fn the_zoom_field_sets_the_typed_zoom_at_any_ui_scaling() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.session.prefs.ui_scaling = 1.5; + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(460.0, 260.0)); + app.run("view.setZoom", json!({"zoom": 200})).unwrap(); + let wanted = app.view().unwrap().zoom; + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, super::status_bar); + assert!((bar.ctx().zoom_factor() - 1.5).abs() < 1e-6, "the interface is zoomed by UI Scaling"); + let shown = |bar: &crate::tests::panel_harness::Panel| bar.value("Zoom").unwrap_or_default(); + assert!(shown(&bar).starts_with("100"), "the field shows the zoom view.setZoom set: {}", shown(&bar)); + bar.type_into("Zoom", "200"); + let zoom = bar.app().view().unwrap().zoom; + assert!((zoom - wanted).abs() < 1e-9, "typing 200% gives the zoom of view.setZoom 200%: {zoom}, not {wanted}"); + assert!(shown(&bar).starts_with("200"), "the field shows the typed zoom: {}", shown(&bar)); +} + /// Read the painted coordinates while checking that drawing never changes the source /// position, document, selection or either branch of its edit history. fn assert_status_coordinates(bar: &mut Shown, expected: Option<&str>) { diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index e2096de5d5..31bb7ebd9f 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -230,11 +230,12 @@ fn shifted(mut view: CanvasView, region: DRect) -> CanvasView { view } -/// The `view.setZoom` params for `edited`, a view of the region's frame: the zoom as the status bar -/// shows it (with `print` screen points to an inch at 100%, [`crate::state::print_ppi`]), and the -/// centre back in document units. -fn view_params(edited: &CanvasView, region: DRect, print: Option) -> Value { - json!({"zoom": crate::state::zoom_display_percent(edited.zoom, print), "center": [edited.center.x + region.x0, edited.center.y + region.y0]}) +/// The `view.setZoom` params for `edited`, a canvas view of the region's frame at `ui_scaling`: the +/// zoom as the status bar shows it (with `print` screen points to an inch at 100%, +/// [`crate::state::print_ppi`]), and the centre back in document units. +fn view_params(edited: &CanvasView, region: DRect, print: Option, ui_scaling: f32) -> Value { + let zoom = crate::state::View::zoom_of_canvas(edited, ui_scaling); + json!({"zoom": crate::state::zoom_display_percent(zoom, print), "center": [edited.center.x + region.x0, edited.center.y + region.y0]}) } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -280,7 +281,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && *edited != given { let print = app.print_ppi(); - app.run("view.setZoom", view_params(edited, region, print)).ok(); + let scaling = app.ui_scaling(); + app.run("view.setZoom", view_params(edited, region, print, scaling)).ok(); } } @@ -299,7 +301,29 @@ mod tests { assert_eq!((given.center.x, given.center.y), (210.0, 170.0), "the centre minus the region's corner"); let mut edited = given; edited.center = (100.0, 100.0).into(); - assert_eq!(view_params(&edited, region, None)["center"], json!([90.0, 80.0]), "the edit plus the region's corner"); + assert_eq!(view_params(&edited, region, None, 1.0)["center"], json!([90.0, 80.0]), "the edit plus the region's corner"); + } + + /// At UI Scaling 150% the panel's zoom field shows the zoom `view.setZoom` set, and a zoom typed into it is the + /// zoom the view gets, as at 100%: 200% gives the view the zoom `view.setZoom` gives for 200%. + #[test] + fn the_zoom_field_sets_the_typed_zoom_at_any_ui_scaling() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.session.prefs.ui_scaling = 1.5; + app.view_mut().unwrap().rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(460.0, 260.0)); + app.run("view.setZoom", json!({"zoom": 200})).unwrap(); + let wanted = app.view().unwrap().zoom; + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + assert!((panel.ctx().zoom_factor() - 1.5).abs() < 1e-6, "the interface is zoomed by UI Scaling"); + let shown = |panel: &crate::tests::panel_harness::Panel| panel.value("Zoom").unwrap_or_default(); + assert!(shown(&panel).starts_with("100"), "the field shows the zoom view.setZoom set: {}", shown(&panel)); + panel.type_into("Zoom", "200"); + let zoom = panel.app().view().unwrap().zoom; + assert!((zoom - wanted).abs() < 1e-9, "typing 200% gives the zoom of view.setZoom 200%: {zoom}, not {wanted}"); + assert!(shown(&panel).starts_with("200"), "the field shows the typed zoom: {}", shown(&panel)); } /// The panel menu's rows are titled, checked and enabled as the option says, and each row's diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b37805eb57..1ed56d8faa 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -156,10 +156,16 @@ impl View { /// Takes the view the canvas reports back, the inverse of [`Self::canvas`]. pub fn set_canvas(&mut self, view: &CanvasView, ui_scaling: f32) { self.center = view.center; - self.zoom = view.zoom * f64::from(ui_scaling); + self.zoom = Self::zoom_of_canvas(view, ui_scaling); self.rotation = view.rotation; self.rect = view.rect; } + + /// The zoom [`Self::zoom`] holds for the canvas view `view` at `ui_scaling`, the inverse of the + /// zoom in [`Self::canvas`]: the zoom `view.setZoom` and the View menu set and the status bar shows. + pub fn zoom_of_canvas(view: &CanvasView, ui_scaling: f32) -> f64 { + view.zoom * f64::from(ui_scaling) + } } /// The status bar's angle menu and View › Rotate View list these preset view angles, each as From 6b3f1646bcd8b4e5a6cda27c0eeca768a1b298cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:13:35 -0800 Subject: [PATCH 087/107] Status bar: the Rotation box shows an angle between the presets When the view was turned to an angle that is not one of the Rotate View presets (with the Rotate View tool, or view.rotate with angle 17), the status bar's Rotation box showed no text: the select held no entry for the angle and had no placeholder. The box now shows the angle rounded to a whole degree as its placeholder, as Crop Image's PPI select does for a resolution outside its list. A preset angle still shows its row, and a pick from the list still turns the view. --- crates/ui-egui/src/chrome/status_bar.rs | 10 ++++++++- crates/ui-egui/src/chrome/tests.rs | 27 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index c4b6f8a5fe..7a70dcd4c7 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -34,6 +34,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let rotation = app.view().map_or(0.0, |v| v.rotation); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); + // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 + // turns the -0 of a small negative angle into 0. + let angle = format!("{}°", rotation.round() + 0.0); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); let unit = app.session.general_unit(); @@ -74,7 +77,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { // Entries are keyed by index: an angle is not a hashable value. - rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles).look(SelectLook::Filled).show(ui).value().copied(); + rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) + .placeholder(angle.clone()) + .look(SelectLook::Filled) + .show(ui) + .value() + .copied(); }); Divider::vertical().show(ui); for (icon, to, tip, enabled) in diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 2c3b214c69..2838bbdc33 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -716,6 +716,33 @@ fn the_status_bar_show_choice_is_checked_and_saved() { ); } +/// The status bar's Rotation box shows the view's angle: a preset angle shows its row's label, an angle between the +/// presets shows rounded to a whole degree, and a pick from the list still turns the view. +#[test] +fn the_status_bar_rotation_box_shows_the_view_angle() { + let mut bar = status_readout_app(); + let rotation = |bar: &mut Shown, angle: f64| { + bar.app().run("view.rotate", json!({ "angle": angle })).unwrap(); + let rotation = bar.settle().find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + let value = bar.tree().value_of(rotation.node).map(str::to_owned); + (rotation, value) + }; + for (angle, shown) in [(17.0, "17°"), (37.4, "37°"), (-0.3, "0°"), (-122.6, "-123°")] { + let (_, value) = rotation(&mut bar, angle); + assert_eq!(value.as_deref(), Some(shown), "the box at {angle}°"); + assert!(bar.texts().iter().any(|t| t.text == shown), "the box draws {shown}"); + } + let (_, value) = rotation(&mut bar, 45.0); + assert_eq!(value.as_deref(), Some("45°")); + // From an angle between the presets, the list still turns the view to the row picked. + let (opener, _) = rotation(&mut bar, 17.0); + bar.click_on(&opener).settle(); + bar.click("-45°").settle(); + assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0)); + let rotation = bar.find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + assert_eq!(bar.tree().value_of(rotation.node), Some("-45°")); +} + /// While background work runs the status bar shows it where the message was, with the count of the jobs after the /// first, and the message of the work's result takes the same place when it ends. Screen readers find the progress. #[test] From 595d6f864d2eb00ba1ee61c242b79373a819bcb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:23:10 -0800 Subject: [PATCH 088/107] Docs: the Image Trace panel saves and renames presets in its Preset row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/mcp.md still listed ui.imageTracePresetDialog, which main no longer has: the UI port (#8800) removed the Save as New Preset and Rename dialog and the command. The Image Trace section now describes the Preset row's Manage presets menu: Save as New Preset… and Rename… open a name field in the row, Enter or OK runs imageTrace.presets.save, Escape or Cancel saves nothing, a taken name keeps the field open, and Delete runs imageTrace.presets.delete. --- docs/mcp.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..0227c0473a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5006,9 +5006,13 @@ already walks Image Trace. Short agent entry points: `replace` is true. Every preset in the file is checked first, and a file with a built-in preset's or `Custom`'s name, two presets of one name, a preset without a name or `params`, settings `imageTrace.presets.save` refuses, or a newer `version` changes nothing. In the app, opening a `.vctracepresets` file (File › Open, a drop, or the file picked - for Import… on the web) imports it as Import… does. Also in the app, - `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog, - and `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) + for Import… on the web) imports it as Import… does. Also in the app, the Image Trace panel's Preset row has a Manage + presets menu. Its Save as New Preset… and Rename… (a saved preset; also F2 on the picker) open a name field in the + row, which starts with the first free "Tracing Preset N" for a new preset and with the preset's name for a rename. + Enter or OK runs `imageTrace.presets.save` (with the panel's settings for a new preset, with `newName` for a rename), + and Escape or Cancel saves nothing. A built-in preset's name, `Custom` or another saved preset's name shows a message + under the field and keeps it open. Its Delete (a saved preset) runs `imageTrace.presets.delete`. + `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) and the saved ones, with the selected preset's settings. Its New… (from the selected preset) and Edit… (a saved preset) open an editor with the Image Trace panel's settings; OK saves with `imageTrace.presets.save` and Cancel saves nothing, and a built-in preset's name, `Custom` or another saved preset's name keeps the editor open. Delete selects From a9c4e259f92d3e803686c5c6cf28b2e41ee887be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:26:27 -0800 Subject: [PATCH 089/107] Canvas: a drag over a frame the render worker drew shows the edit in the frame it is made in In a document whose frames take over 8 ms, every frame of an edit went to the render worker once the frame shown came from it, so a Pen drag's curve trailed the pointer by the worker's render time plus the wait for a busy worker. The changed part of a worker's frame is now drawn again on the UI thread, as it already was for frames rendered there, when the part's share of the frame's last render time is at most 8 ms. The part is not drawn there, and the frame goes to the worker as before, when the frame shown drew raster effects made before their objects moved, holds pixels copied from the worker's last frame, or drew art in a way that depends on the frame's size, or when the part itself draws such art. A worker frame on its way blocks the part only when it is of another document or not older than the edit. Part of #8296. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 4 + crates/ui-egui/src/canvas/raster.rs | 67 ++++++++++++---- crates/ui-egui/src/canvas/tests.rs | 117 ++++++++++++++++++++++++++-- crates/ui-egui/src/render_worker.rs | 5 +- 5 files changed, 170 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6c4f808359..07ca962d4f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -120,6 +120,7 @@ impl VectorcraftApp { last_ms: 0.0, moved: false, from_worker: false, + worker_parts: false, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 90875851d4..e2cb1d7355 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,6 +25,10 @@ pub struct CanvasCache { /// The frame shown was rendered on the worker: an interaction's frames stay there /// ([`canvas::show`]). pub from_worker: bool, + /// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn + /// again on this thread would not have matched the frame around it: until the worker's next + /// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]). + pub worker_parts: bool, /// The frame shown holds pixels the worker copied from its last frame, and when it was shown /// (seconds, egui's input time): it renders whole once it has been shown for /// [`canvas::STILL_SECS`] with the view unmoved. diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 8243444d39..780dd5f7a8 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -48,13 +48,19 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// The pixels of the `w`×`h` frame through `view` to render again for `doc`, when only the document /// changed, or placed documents' bitmaps were made, since the frame shown (its key `key` but for -/// the revision and [`CacheKey::placed`], and its render options `opts`), which this thread -/// rendered, and no frame is on its way from the worker: those it changed in, and those the -/// objects showing those bitmaps' files cover (`Some(None)`: none), grown to whole eighths of the -/// frame, as long as they are at most half of it. None: render the whole frame. Frames the worker -/// renders stay whole: its renderer keeps the rasters of the art's effects, this thread's doesn't. -/// What changed is measured by this thread's renderer, which drew the frame shown: it keeps what -/// it measures (a 3D effect's art) to draw the part again. +/// the revision and [`CacheKey::placed`], and its render options `opts`), and no frame of another +/// document, or of this revision or a later one, is on its way from the worker: those it changed +/// in, and those the objects showing those bitmaps' files cover (`Some(None)`: none), grown to +/// whole eighths of the frame, as long as they are at most half of it. None: render the whole +/// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve) +/// shows in the frame it is made in, when the part's share of the frame's last whole render time +/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their +/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame +/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn +/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]): +/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What +/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to +/// draw the part again. pub(super) fn changed_pixels( app: &mut VectorcraftApp, key: &CacheKey, @@ -71,19 +77,25 @@ pub(super) fn changed_pixels( } let shown_key = app.canvas.key.as_ref()?; let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() }; - if !same_view || app.canvas.texture.is_none() || app.canvas.from_worker || app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) { + let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some()); + // A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]). + let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision); + if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way { return None; } // The placed documents' files whose bitmaps were made since the frame shown. let entry = app.session.documents().iter().find(|d| d.uid as usize == key.doc).and_then(|d| app.canvas.placed_keys.get(&d.uid)); let placed = placed_changes(entry, shown_key.placed, key.placed, doc, vectorcraft_render::placed_document::made_between)?; + // Over a frame the worker rendered, the part's share of the whole frame's time is at most 8 ms. + let budget = if app.canvas.from_worker { 8.0 / app.canvas.last_ms } else { 0.5 }; match app.canvas.renderer.changed(shown, doc, opts).and(placed) { vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), Some([x0, y0, x1, y1]) => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); - (u64::from(x1 - x0) * u64::from(y1 - y0) * 2 <= u64::from(w) * u64::from(h)).then_some(Some([x0, y0, x1, y1])) + let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h)); + (share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1])) } }, vectorcraft_render::Changed::Everything => None, @@ -122,6 +134,9 @@ pub(crate) struct WorkerFrame { pub(crate) moved: usize, /// The frame holds pixels copied from the last frame. pub(crate) reused: bool, + /// The frame drew art in a way that depends on its size + /// ([`vectorcraft_render::FrameStats::view_sized`]). + pub(crate) view_sized: bool, } /// Nothing but the position of the view differs between the frame `kept` and the job `job`, in @@ -239,6 +254,8 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option let moved = r.stats.moved; (img, moved) }); + // A copied frame's parts draw nothing that depends on the frame's size ([`composed_frame`]). + let view_sized = !reused && r.stats.view_sized > 0; let keeps = job.may_keep && moved == 0 && r.stats.view_sized == 0 && img.pixels.len() <= MAX_KEPT_BYTES && (img.width, img.height) == (job.w, job.h); *kept = @@ -246,7 +263,7 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option // The kept frame stays sRGB, so the next frame's copied pixels are converted only once. let width = img.width; crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over()); - WorkerFrame { img, moved, reused } + WorkerFrame { img, moved, reused, view_sized } } /// Upload the art's raster directly into the canvas texture without reallocating or copying pixels; @@ -580,6 +597,7 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: app.canvas.reused = done.reused.then(|| frame::clock(ctx)); app.canvas.moved = done.moved > 0; app.canvas.from_worker = true; + app.canvas.worker_parts = done.view_sized; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -667,7 +685,13 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f /// Draw `region` of `frame` again, into the texture of the frame shown, which then shows `frame`'s /// key: only the document changed since the frame shown, in that part of it /// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's. -fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) { +/// +/// Over a frame the worker rendered, a part that drew raster effects from rasters made before +/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]), +/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]), +/// would not match the frame around it: it is not drawn, false is returned, and the edits after it +/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]). +fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool { let Frame { key, doc, effects, view, opts, pixel, .. } = frame; let t0 = monotonic_ms(); if region.is_none() { @@ -679,6 +703,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let renderer = &mut app.canvas.renderer; let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); + if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) { + app.canvas.worker_parts = true; + return false; + } let width = part.width; crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); let color = color_image(&part); @@ -689,6 +717,7 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] app.canvas.key = Some((*key).clone()); app.canvas.shown = Some(((*doc).clone(), opts.clone())); app.perf.render_ms = monotonic_ms() - t0; + true } /// With `waits_for_still` set (the web build) and the last render slow, an edit while the view @@ -736,7 +765,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // Frames that would be slow on this thread (the last one took over 8 ms) go // to the worker. An interaction's frames stay on the worker once it drew the frame shown: // its renderer keeps the rasters of the art's effects that make those frames fast, and this - // thread's renderer has none, so a frame fast on the worker would be slow here. + // thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a + // part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]). let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; @@ -751,11 +781,14 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let may_copy = app.canvas.key.as_ref() != Some(key); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); let mut landed = None; - match (&mut app.canvas.worker, heavy, changed) { - // Only the document changed since the frame shown, in a part of it: that part is - // rendered again, here, into the texture. `last_ms` stays the whole frame's. - (_, _, Some(region)) => draw_changed(app, &Frame { key, doc, effects, size: (w, h), view, opts, pixel }, region), - (Some(worker), true, None) => { + // Only the document changed since the frame shown, in a part of it: that part is rendered + // again, here, into the texture. `last_ms` stays the whole frame's. + let part = Frame { key, doc, effects, size: (w, h), view, opts, pixel }; + let drawn = changed.is_some_and(|region| draw_changed(app, &part, region)); + let Frame { opts, .. } = part; + match (&mut app.canvas.worker, heavy, drawn) { + (_, _, true) => {} + (Some(worker), true, false) => { // The worker draws the frame: what this thread's renderer made to measure the edit // isn't drawn here. app.canvas.renderer.let_go_of_measured(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..8ea2a85bba 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1613,6 +1613,89 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { } } +/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the +/// frame of the move: once the press's frame arrives from the worker, every move shows the +/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters +/// from before their objects moved, when a part drawn here would have differed from it, or when +/// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker, +/// and the moves after the worker's frame are drawn here again. A frame of an older revision on +/// its way does not hold a move back. +#[test] +fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..60 { + let (x, y) = (f64::from(i % 10) * 40.0, f64::from(i / 10) * 50.0); + app.session.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 30, "height": 30})).unwrap(); + } + app.session.execute("select.none", &json!({})).unwrap(); + app.ui.view.smart_guides = false; + app.canvas.worker_started = true; // the first frame renders on this thread + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); + app.canvas.last_ms = 50.0; + app.select_tool("pen"); + let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision); + let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true)]); + assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker"); + assert!(side.render()); + let mut drag = |app: &mut VectorcraftApp| { + at += vec2(9.0, 5.0); + frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); + }; + for step in 0..6 { + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "move {step}: the curve is drawn in its own frame"); + assert!(side.jobs.try_recv().is_err(), "move {step}: nothing is queued on the worker"); + } + for case in ["moved", "differs", "slow"] { + match case { + "moved" => app.canvas.moved = true, + "differs" => app.canvas.worker_parts = true, + _ => app.canvas.last_ms = 10_000.0, + } + drag(&mut app); + assert!(shown(&app) < revision(&app), "{case}: the move is not drawn here"); + assert!(side.render(), "{case}: the move renders on the worker"); + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here"); + assert!(!app.canvas.worker_parts, "{case}"); + } + // A worker's frame that drew art in a way that depends on its size: the move after it renders + // on the worker too. + app.canvas.worker_parts = true; + drag(&mut app); + let job = side.jobs.try_iter().last().expect("the move is on the worker"); + let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job); + side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap(); + drag(&mut app); + assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size"); + assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker"); + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here"); + // A frame on its way of an older revision: the next move is drawn here, and that frame is not + // shown when it arrives. + app.canvas.worker_parts = true; + drag(&mut app); + assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way"); + app.canvas.worker_parts = false; + for late in [false, true] { + if late { + assert!(side.render()); + } + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "drawn here, the frame on its way arrived: {late}"); + } + frame(&mut app, &ctx, vec![button(at, false)]); + app.canvas.worker = None; +} + /// The frame after an interaction renders without `interacting` also when the interaction /// leaves the document as it was (#1257): here a drag back to where it started. #[test] @@ -1777,7 +1860,9 @@ fn cached_frames_keep_their_scale() { // Deliver the actual replacement and verify that it replaces the cached key. let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); - completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false }).unwrap(); + completed + .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); frame(&mut app, size, new_ppp); assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame arrived"); } @@ -1917,7 +2002,9 @@ fn a_pan_fills_the_area() { // The fill arrives; the next frame draws it, and asks for no other fill. let img = app.canvas.renderer.render(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts); let (doc, opts) = (fill_job.doc, fill_job.opts); - fill_completed.send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false }).unwrap(); + fill_completed + .send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); let (meshes, pixels) = frame(&mut app); assert!(fill_jobs.try_recv().is_err(), "the fill covers the canvas"); assert_eq!(app.canvas.key.as_ref(), Some(&old), "the last frame is still shown"); @@ -1962,11 +2049,15 @@ fn a_pan_fills_the_area() { app.view_mut().unwrap().center = Point::new(250.0, 150.0); // That fill finishes after the worker's frame: it is taken and not kept. let img = app.canvas.renderer.render(&next.doc, next.w, next.h, next.view, &next.opts); - fill_completed.send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false }).unwrap(); + fill_completed + .send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); // The worker's frame arrives: it covers the canvas, and the fill is no longer drawn or kept. let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); - completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false }).unwrap(); + completed + .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); let (meshes, _) = frame(&mut app); assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame is shown"); assert!(app.canvas.fill.is_none() && meshes.iter().all(|m| m.texture_id != fill_tex), "the fill is dropped"); @@ -5043,6 +5134,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5066,6 +5158,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5088,6 +5181,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5110,6 +5204,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5170,7 +5265,16 @@ fn the_contour_bar_sets_corners_and_bakes() { /// A frame the render worker finished for `job`: white pixels of the job's size. fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done { let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] }; - crate::render_worker::Done { key: job.key.clone(), doc: job.doc.clone(), opts: job.opts.clone(), img, ms: 40.0, moved: 0, reused: false } + crate::render_worker::Done { + key: job.key.clone(), + doc: job.doc.clone(), + opts: job.opts.clone(), + img, + ms: 40.0, + moved: 0, + reused: false, + view_sized: false, + } } /// A job for the render worker to pan over a document of `doc`: a view at 100% moved by `(dx, dy)` @@ -5636,7 +5740,8 @@ fn a_pan_after_the_settling_frame() { let job = jobs.try_recv().unwrap_or_else(|_| panic!("{name}: the canvas asks for a frame")); let f = render_job(&mut r, &mut kept, &job); assert_eq!(f.reused, copies, "{name}"); - let done = crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img: f.img, ms: 40.0, moved: f.moved, reused: f.reused }; + let (key, doc, opts, img) = (job.key, job.doc, job.opts, f.img); + let done = crate::render_worker::Done { key, doc, opts, img, ms: 40.0, moved: f.moved, reused: f.reused, view_sized: f.view_sized }; done_tx.send(done).unwrap(); }; frame(&mut app, 1.0); diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 9f1fcecb71..d7545f2df7 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -51,6 +51,9 @@ pub struct Done { /// The frame holds pixels copied from the worker's last frame ([`crate::canvas::render_job`]), /// and `ms` is the time of the copy and of the parts rendered. pub reused: bool, + /// The frame drew art in a way that depends on its size + /// ([`vectorcraft_render::FrameStats::view_sized`]): a part of it drawn on its own may differ. + pub view_sized: bool, } /// Render `job` as the worker thread does: inside the job's automation roots and deferred @@ -59,7 +62,7 @@ pub(crate) fn render(r: &mut Renderer, kept: &mut Option Date: Wed, 25 Nov 2026 21:37:15 -0800 Subject: [PATCH 090/107] Cursors: the Live Paint Bucket and Knife cursors click where their glyphs point The Live Paint Bucket's three cursors and the Knife's put the hotspot at (2, 22), the lower-left corner of the icon box, where none of their icons draws anything, so a click landed away from the drop, the brush or the blade. Each hotspot now sits on the point its cursors.toml entry names: the bottom of the drop for the bucket and the filled diamond, the middle of the brush's bristle edge, and the blade's point. The Eyedropper keeps its pipette tip at (2, 22). A new test draws every tool cursor's image and checks that the icon's own mark color, not only its halo, covers the hotspot pixel or one next to it. --- crates/ui-egui/src/cursors.rs | 22 ++++++++++++------ crates/ui-egui/src/cursors/tests.rs | 35 +++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 2b3f5c31d1..2f9c594ab7 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -39,10 +39,18 @@ pub static CURSOR_ICONS: AppIcons = AppIcons::new( /// Where the glyphs that start at the box's upper left have their tip, in the icon's 24-unit box. const TIP: Vec2 = Vec2::new(2.0, 2.0); -/// The tip of the glyphs that point down-left (a pipette, a brush, a bucket, a knife). -const LOWER_LEFT: Vec2 = Vec2::new(2.0, 22.0); +/// The pipette's sampling tip, at the box's lower left. +const PIPETTE_TIP: Vec2 = Vec2::new(2.0, 22.0); /// The middle of the Anchor Point caret's square. const CARET: Vec2 = Vec2::new(12.0, 6.0); +/// The blade's point of the knife, at the box's upper right. +const BLADE_POINT: Vec2 = Vec2::new(20.0, 4.0); +/// The bottom of the drop below the paint bucket. +const BUCKET_DROP: Vec2 = Vec2::new(20.0, 22.0); +/// The bottom of the drop beside the Live Paint diamond. +const DIAMOND_DROP: Vec2 = Vec2::new(20.0, 18.0); +/// The middle of the brush's bristle edge, at its lower left. +const BRISTLE_TIP: Vec2 = Vec2::new(6.0, 17.5); fn system(icon: CursorIcon) -> cb::Cursor { cb::Cursor::System(icon) @@ -111,7 +119,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::HandGrab => system(CursorIcon::Grabbing), Cursor::ZoomIn => PaintedCursor::zoom(false).into(), Cursor::ZoomOut => PaintedCursor::zoom(true).into(), - Cursor::Eyedropper => tool("pipette", LOWER_LEFT, None), + Cursor::Eyedropper => tool("pipette", PIPETTE_TIP, None), Cursor::NotAllowed => system(CursorIcon::NotAllowed), Cursor::Busy => system(CursorIcon::Progress), Cursor::AddStop => badged(CursorBadge::Add), @@ -136,10 +144,10 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::PencilContinue => marked(Crosshair, "cursor-mark-line-rising"), // Only the centre: the tool draws the tip's outline round it, at the zoom. Cursor::BlobBrush | Cursor::Eraser => PaintedCursor::circle(1.25).into(), - Cursor::Knife => tool("dc-knife", LOWER_LEFT, None), - Cursor::LivePaintBucket => tool("paint-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketFace => tool("dc-live-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketEdge => tool("paintbrush", LOWER_LEFT, None), + Cursor::Knife => tool("dc-knife", BLADE_POINT, None), + Cursor::LivePaintBucket => tool("paint-bucket", BUCKET_DROP, None), + Cursor::LivePaintBucketFace => tool("dc-live-bucket", DIAMOND_DROP, None), + Cursor::LivePaintBucketEdge => tool("paintbrush", BRISTLE_TIP, None), Cursor::LivePaintSelectFace => marked(Arrow, "cursor-mark-square"), Cursor::LivePaintSelectEdge => marked(Arrow, "cursor-mark-edge"), Cursor::LivePaintSelectOutside => marked(Arrow, "x"), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 68357f6b65..c3e9fc92e4 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -10,6 +10,41 @@ fn every_tool_cursors_hotspot_lies_inside_its_icon_box() { } } +/// A click lands where the glyph points: in every painted tool cursor's image, the icon's own +/// mark color (not only its halo) covers the hotspot pixel or one next to it. +#[test] +fn every_tool_cursors_hotspot_is_on_its_glyph() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + register_app_icons(&crate::icons::APP_ICONS); + register_app_icons(&CURSOR_ICONS); + let mut missed = Vec::new(); + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + let ink = rgba_color(env.tokens.tokens().color.overlay.stroke); + let near_ink = |px: &[u8]| px[3] == 255 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + for c in GLYPHS { + let cb::Cursor::Painted(painted @ PaintedCursor::Tool { .. }) = tool_cursor(c) else { continue }; + let Some(image) = painted_image(&env, &painted, 2.0) else { + missed.push(format!("{c:?}: no image")); + continue; + }; + let ([w, h], [hx, hy]) = (image.size.map(usize::from), image.hotspot.map(usize::from)); + let on_glyph = (hy.saturating_sub(1)..=(hy + 1).min(h - 1)) + .flat_map(|y| (hx.saturating_sub(1)..=(hx + 1).min(w - 1)).map(move |x| (y * w + x) * 4)) + .any(|i| near_ink(&image.rgba[i..i + 4])); + if !on_glyph { + missed.push(format!("{c:?}")); + } + } + }) + .textures_delta + .clear(); + assert!(missed.is_empty(), "hotspots off their glyphs: {missed:?}"); +} + /// A `cursor-` icon name a cursor uses must be in the set the host registers. #[test] fn every_cursor_icon_the_app_names_is_in_its_set() { From 013cf4dacb0a45b820defb2ff90f4c0f65b7ab31 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:39:58 -0800 Subject: [PATCH 091/107] Fill Area: outline pieces on a clipping mask's edge count as shown clip_to kept a piece of an unfilled outline only when its middle tested inside the mask, and a point on the mask's own outline tests inside on some sides and outside on others. A square clipped by the same square kept two sides, so Fill Area found no area inside it. A piece whose middle lies on the mask's outline now counts as shown when the mask's filled area lies on one side of it. A piece just outside the mask, and a piece on an outline of the mask that bounds no filled area, stay hidden. --- crates/engine/src/tests/fill_area.rs | 23 +++++++++++++ crates/tools/src/builder/fill_area.rs | 49 +++++++++++++++++++++++---- crates/tools/src/builder/tests.rs | 26 ++++++++++++++ 3 files changed, 92 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 67de26acd7..b0b511e661 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -232,6 +232,29 @@ fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() { assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); } +/// Parts of an outline that lie on the mask's edge show: a square without a fill, clipped by a mask +/// of the same square, keeps all four sides and bounds its whole area. A square just outside the +/// mask is hidden and bounds nothing. +#[test] +fn fill_area_keeps_outline_parts_on_the_mask_edge() { + let mut s = session(); + let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 10000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + + let mut s = session(); + let square = rect(&mut s, -0.005, -0.005, 100.01, 100.01); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + /// In a clipping group inside another, clipped art shows only where both masks show it. #[test] fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it() { diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 2ce72b15f3..adb16b8f79 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -2,6 +2,7 @@ //! closed path of that area with the current fill and stroke (`shapeBuilder.copyRegion`). The //! paths around the area stay as they are, and nothing needs to be selected. +use vectorcraft_geom::kurbo::ParamCurveDeriv; use vectorcraft_geom::path::segment_bounds; use vectorcraft_geom::{ParamCurve, PathSeg}; @@ -171,13 +172,39 @@ fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks Some(shape) } +/// How far (pt) the middle of a piece of an outline may lie from a mask's outline and still count +/// as on the mask's edge, which [`clip_to`] keeps. It covers rounding only, so a piece just outside +/// the mask is still left out. +const ON_MASK: f64 = 1e-6; + +/// How far (pt) to each side of a piece [`shows_through`] looks for the mask's filled area: past +/// [`ON_MASK`], and within a filled strip of the mask as narrow as this. +const MASK_SIDE: f64 = 1e-4; + +/// Does the piece of an outline whose middle is `p`, running in direction `dir` there, show +/// through `mask` filled with `rule`? A piece off the mask's outline shows when the filled area +/// holds `p`. A piece on the outline ([`ON_MASK`]) shows when the filled area lies on one side of +/// it ([`MASK_SIDE`]), so every side of a square clipped by the same square shows, and an outline +/// of the mask that bounds no filled area (two copies of one outline under even-odd) hides it. +fn shows_through(mask: &PathData, rule: FillRule, p: Point, dir: vectorcraft_geom::Vec2) -> bool { + if !mask.nearest(p).is_some_and(|(.., d)| d <= ON_MASK) { + return path_contains(mask, rule, p); + } + let len = dir.hypot(); + if !(len > 0.0 && len.is_finite()) { + return false; + } + let side = dir.turn_90() * (MASK_SIDE / len); + path_contains(mask, rule, p + side) || path_contains(mask, rule, p - side) +} + /// `shape` cut to `mask` (filled with `rule`). With `filled` (the path's fill draws), its closed /// subpaths are cut to their overlap with the mask, whose edge then bounds the fill. Its other -/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask, -/// so a hidden part of an outline does not close an area. A subpath with more segments or -/// crossings than [`po::addons::pathtools::crossings_on`] takes is left out. None when nothing of -/// it is inside. -fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option { +/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask or +/// on its edge ([`shows_through`]), so a hidden part of an outline does not close an area. A +/// subpath with more segments or crossings than [`po::addons::pathtools::crossings_on`] takes is +/// left out. None when nothing of it is inside. +pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option { let (b, mb) = (shape.path.bounds()?, mask.bounds()?); if !meet(&b, &mb) { return None; @@ -195,7 +222,17 @@ fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> O let (cut, at) = po::addons::pathtools::insert_at(sp, &places); subs.extend(cut.cut_at(&at).into_iter().filter(|piece| { let n = piece.segment_count(); - n > 0 && path_contains(mask, rule, piece.segment(n / 2).eval(0.5)) + n > 0 && { + let seg = piece.segment(n / 2); + // Where the tangent vanishes (a cusp at the middle), the curve runs along its second + // derivative there, and a straight segment with that degenerate form along its chord. + let d1 = seg.deriv(); + let dir = [d1.eval(0.5).to_vec2(), d1.deriv().eval(0.5).to_vec2(), seg.p3 - seg.p0] + .into_iter() + .find(|v| v.hypot2() > 0.0) + .unwrap_or_default(); + shows_through(mask, rule, seg.eval(0.5), dir) + } })); } if subs.is_empty() { diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 0cdaad3434..a0d210f566 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -3796,6 +3796,32 @@ fn fill_area_press_does_not_search_a_hover_position_it_passed() { assert_eq!(super::fill_area::hover_searches_started() - started, 1, "only the search that was running"); } +/// An outline without a fill, cut to a clipping mask, keeps the pieces on the mask's edge: a square +/// clipped by the same square keeps all four sides. A square just outside the mask, and a square on +/// an outline of the mask that bounds no filled area (two copies of the square under even-odd), +/// keep nothing. +#[test] +fn fill_area_clip_keeps_outline_pieces_on_the_mask_edge() { + let unit = Rect::new(0.0, 0.0, 100.0, 100.0); + let clip = + |shape: PathData, mask: &PathData, rule: FillRule| super::fill_area::clip_to(po::Shape::new(shape, FillRule::NonZero, 1), false, mask, rule); + let kept = clip(shapes::rectangle(unit), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge"); + assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::(), 4, "{:?}", kept.path); + let outside = shapes::rectangle(Rect::new(-0.005, -0.005, 100.005, 100.005)); + assert!(clip(outside, &shapes::rectangle(unit), FillRule::NonZero).is_none()); + let mut twice = shapes::rectangle(unit); + let mut back = shapes::rectangle(unit).subpaths; + back[0].anchors.reverse(); + twice.subpaths.extend(back); + assert!(clip(shapes::rectangle(unit), &twice, FillRule::EvenOdd).is_none()); + // A top side drawn as a cubic whose tangent vanishes at its middle shows as well. + let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Corner }; + let (o, x, xy, y) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)); + let cusp = SubPath::new(vec![a(o, o, x), a(x, o, x), a(xy, xy, xy), a(y, y, y)], true); + let kept = clip(PathData::single(cusp), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge"); + assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::(), 4, "{:?}", kept.path); +} + #[test] fn create_builds_the_three_tools() { for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] { From fb6825120342a56de0ee596c57cb7619cd4f3757 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:43:49 -0800 Subject: [PATCH 092/107] Cursors: Use Precise Cursors and Caps Lock hide the brush tip outline again The view info the canvas gives the tools never set its precise flag, so the Blob Brush and the Eraser drew their tip outline around the precise crosshair whatever the setting. Nothing passed the host's Caps Lock state to the session either, so `view.capsLock` changed nothing. - The view info's precise flag is on while Use Precise Cursors or Caps Lock is on, as before the move to the shared canvas. - The canvas passes each change of the host's Caps Lock state to `view.capsLock`; a `view.capsLock` call stays in effect until the next change. - The canvas's pointer follows the same flag, so with both on the drawing tools keep the crosshair. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/view.rs | 23 ++++++- crates/ui-egui/src/caches.rs | 3 + crates/ui-egui/src/canvas.rs | 7 +- .../ui-egui/src/canvas/tool_adapter/tests.rs | 69 +++++++++++++++++++ 5 files changed, 101 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6c4f808359..300674555d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -150,6 +150,7 @@ impl VectorcraftApp { carry_target: None, last_drag: None, escaped_press: false, + host_caps_lock: None, committed_preview: false, panes: Default::default(), windows: crate::doc_windows::Windows::new(known), diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 874146e102..fa5eaf858d 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -406,7 +406,28 @@ impl VectorcraftApp { shape_widgets: self.ui.view.shape_widgets, screen: self.screen_frame(), artboard: self.view().map_or(0, |v| v.artboard), - ..ViewInfo::default() + precise: self.precise_cursors(), + } + } + + /// Whether the drawing tools show precise cursors: General › Use Precise Cursors is on, or Caps Lock is + /// (`Session::caps_lock`, which the canvas keeps at the host's state and `view.capsLock` sets). The canvas's pointer + /// and the tools' brush tips both follow it. + pub(crate) fn precise_cursors(&self) -> bool { + self.session.prefs.use_precise_cursors || self.session.caps_lock + } + + /// Takes the host's Caps Lock state `on` when it changes: the session follows it until the next change, and a + /// `view.capsLock` call between changes stays in place. + pub(crate) fn follow_caps_lock(&mut self, on: bool) { + if self.canvas.host_caps_lock == Some(on) { + return; + } + self.canvas.host_caps_lock = Some(on); + if self.session.caps_lock != on + && let Err(err) = self.run("view.capsLock", serde_json::json!({ "on": on })) + { + log::error!("Could not update the Caps Lock state: {err}"); } } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 90875851d4..fdad07b1b7 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -107,6 +107,9 @@ pub struct CanvasCache { /// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up, /// which gives back a selection tool Cmd lent. pub escaped_press: bool, + /// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the + /// next reading; `None` before the first pass. + pub host_caps_lock: Option, /// A press on the canvas committed a panel field's running preview before the tool took the press, as the field's /// commit came first in production: the field's own commit later in the pass has nothing left to run. pub committed_preview: bool, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e0bc44b304..45d5e60d05 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -194,6 +194,11 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin }; let pasteboard = app.session.documents().get(win.0).map(|st| artboards::pasteboard_color(app, st, app.outline_view())); let layers = move || bounds; + let host_caps_lock = craft::ui::runtime::lock_keys::caps_lock(ui.ctx()); + app.follow_caps_lock(host_caps_lock); + // The canvas reverses the state it is given while the host's Caps Lock is on: given this, it shows the precise + // cursors the tools are told about. + let precise = app.precise_cursors() != host_caps_lock; let prefs = &app.session.prefs; let mut canvas = Canvas::new("Document") .id(canvas_id(win)) @@ -205,7 +210,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin .body_nudges(ARROWS) .rulers(x, y) .with_rulers(strips) - .precise_cursors(prefs.use_precise_cursors); + .precise_cursors(precise); if let Some(pasteboard) = pasteboard { canvas = canvas.pasteboard(pasteboard); } diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index 88e1c533be..be5c619a2e 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -67,3 +67,72 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() { assert_ne!(alt, plain, "Alt shows the Eyedropper's cursor"); assert_eq!(shown(&mut app, egui::Modifiers::NONE), plain, "and letting go brings the bucket back"); } + +/// The Blob Brush's or the Eraser's tip outline at the pointer, as the canvas draws it this pass. +fn shows_tip(app: &mut VectorcraftApp) -> bool { + let view = app.view_info(); + app.session.overlays(view).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. })) +} + +/// Use Precise Cursors or Caps Lock, or both, gives the Blob Brush and the Eraser only the crosshair: the tool draws no +/// tip outline around it. With both off, each shows its own pointer and the tip outline. +#[test] +fn precise_cursors_hide_the_brush_tip_outline() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + for tool in ["blobBrush", "eraser"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + for (preference, caps_lock) in [(false, false), (true, false), (false, true), (true, true), (false, false)] { + app.run("prefs.set", serde_json::json!({"key": "usePreciseCursors", "value": preference})).unwrap(); + WindowHost::of(&ctx).set_caps_lock(Some(caps_lock)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + let precise = preference || caps_lock; + let case = format!("{tool}, Use Precise Cursors {preference}, Caps Lock {caps_lock}"); + assert_eq!(app.session.caps_lock, caps_lock, "{case}: the session takes the host's Caps Lock state"); + assert_eq!(app.view_info().precise, precise, "{case}"); + assert_eq!(shows_tip(&mut app), !precise, "{case}"); + assert_eq!(craft::ui::runtime::cursor::current(&ctx) == crosshair, precise, "{case}"); + } + } +} + +/// `view.capsLock` sets the Caps Lock state the tools and the canvas's pointer follow until the host's state changes. +#[test] +fn the_caps_lock_command_gives_the_brushes_the_crosshair() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(app.session.caps_lock, "the host's unchanged state leaves the command's in place"); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); + // With the host's Caps Lock on, the command turns it off for the tools and the canvas's pointer alike. + WindowHost::of(&ctx).set_caps_lock(Some(true)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(!app.session.caps_lock); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); +} From 0eec4f510f56dbe2d1e37adb4e74cb6e135ac68f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:46:05 -0800 Subject: [PATCH 093/107] Toolbars: Dock Toolbar and Float Toolbar run again on the dock window.toolbar.dock and window.toolbar.float were still listed in the command catalogs, but the move to the framework dock removed their handlers, so both returned "unknown command". - window.toolbar.dock docks a toolbar made with New Toolbar as a column of the left or right edge's dock, at the column `order` asks for. Without `side` it uses the edge it docks at, else the edge of the docked panel it left, else the left. - window.toolbar.float floats it at x, y, or as the dock floats a panel. - A hidden toolbar that either command shows brings back the groups torn off it, and both commands end a Tab hide. - window.toolbar.list reports that same edge for a floating toolbar instead of always "left". - place_floating moves an open OS window's record with its rect, as float_actions does. Docs: the params text in both catalogs, docs/mcp.md and docs/control-protocol.md describe dock columns instead of lanes. --- crates/mcp/src/ui_catalog.rs | 6 +- crates/ui-egui/src/custom_toolbars.rs | 263 +++++++++++++++++- crates/ui-egui/src/menus/ui_commands.rs | 6 +- crates/ui-egui/src/panel_docking.rs | 16 +- .../ui-egui/src/panel_docking/native_tests.rs | 16 ++ docs/control-protocol.md | 5 +- docs/mcp.md | 45 ++- 7 files changed, 307 insertions(+), 50 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 17f665d58f..c81248afc6 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -658,19 +658,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.dock", "Dock Toolbar", "", - "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}", + "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` as a column of the dock along the window's left or right edge (omitted: the edge it docks at, else the edge it docked at last, the left at first), as dragging its title bar to that edge does; a hidden toolbar shows; `order` is its column's place in that edge's dock, 0 at the window's edge (omitted: the innermost, or where it is when it docks at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}, `pos` its top-left corner while it floats (else null)", ), ( "window.toolbar.float", "Float Toolbar", "", - "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}", + "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in window points (both or neither, each from -1000000 to 1000000; omitted: where the dock floats a panel, and a floating toolbar stays where it is), as dragging its title bar out of the dock does; a hidden toolbar shows; returns {toolbar, floating, side, order, pos}", ), ( "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 9a89308e38..b1d1c3b356 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -23,7 +23,7 @@ use std::collections::BTreeSet; use craft::behavior::IconId; -use craft::behavior::dock::{Action, DockEdge}; +use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target}; use craft::ui::buttons::IconButton; use craft::ui::contract::{PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::DialogResult; @@ -345,6 +345,133 @@ fn set_shown(app: &mut VectorcraftApp, name: &str, show: Option) -> Result Ok(show) } +// ---------- docking and floating ---------- + +/// The window edge and column index from that edge where `panel` docks; none while it floats or is hidden. +fn docked_at(ui: &UiState, panel: &str) -> Option<(DockEdge, usize)> { + panel_docking::column_of(panel_docking::layout_of(ui), panel).and_then(|(slot, _)| slot) +} + +/// The window edge toolbar panel `panel` docks at: while docked, its edge; while it floats or is +/// hidden, the edge of the docked panel the dock records it left; else the left edge. +fn last_edge(ui: &UiState, panel: &str) -> DockEdge { + let ws = &ui.dock_workspace; + let left = ws.floated().iter().chain(ws.hidden()).find(|(p, _)| p == panel).and_then(|(_, at)| at.anchor.as_deref()); + docked_at(ui, panel).or_else(|| left.and_then(|anchor| docked_at(ui, anchor))).map_or(DockEdge::Start, |(edge, _)| edge) +} + +/// The `side` param's name of `edge`. +fn side_name(edge: DockEdge) -> &'static str { + if edge == DockEdge::End { "right" } else { "left" } +} + +/// Where toolbar `bar` is: `{toolbar, floating, side, order, pos}`, as `window.toolbar.dock` and +/// `window.toolbar.float` return it. +fn placement(app: &VectorcraftApp, bar: &str) -> Result { + let b = find(&app.ui, bar).ok_or_else(|| format!("no toolbar named `{bar}`"))?; + let panel = panel_id(b.id); + let docked = docked_at(&app.ui, &panel); + let pos = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| [w.rect.min.x, w.rect.min.y]); + Ok(json!({ + "toolbar": b.name, + "floating": docked.is_none(), + "side": side_name(last_edge(&app.ui, &panel)), + "order": docked.map(|(_, n)| n), + "pos": pos, + })) +} + +/// `window.toolbar.dock`: docks the toolbar named `name` as a column of the dock on the `side` edge +/// (omitted: [`last_edge`]), at column `order` from the window edge (omitted: the innermost, or where it +/// is when it docks at that edge already). Bad params are errors and change nothing. +fn dock(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?; + let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone()); + let edge = match p.get("side") { + None | Some(Value::Null) => last_edge(&app.ui, &panel), + // `Start` and `End`, as panels take them, too. + Some(Value::String(s)) if s.eq_ignore_ascii_case("left") || s.eq_ignore_ascii_case("start") => DockEdge::Start, + Some(Value::String(s)) if s.eq_ignore_ascii_case("right") || s.eq_ignore_ascii_case("end") => DockEdge::End, + Some(Value::String(s)) => return Err(format!("side is left or right, not `{s}`")), + Some(v) => return Err(format!("side is left or right, not `{v}`")), + }; + // A panel of each other column of that edge's dock, from the window edge inwards. + let others: Vec = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), edge) + .iter() + .filter(|c| !c.panels().any(|q| *q == panel)) + .filter_map(|c| c.panels().next().cloned()) + .collect(); + let order = match p.get("order") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64().and_then(|n| usize::try_from(n).ok()).filter(|&n| n <= others.len()) { + Some(n) => Some(n), + None => return Err(format!("order is a whole number from 0 to {}, not `{v}`", others.len())), + }, + }; + let here = docked_at(&app.ui, &panel).filter(|(e, _)| *e == edge).map(|(_, n)| n); + if here.is_none() { + // A new innermost column of that edge's dock; a hidden toolbar shows. + let hidden = !panel_docking::layout_of(&app.ui).contains(&panel); + app.run("window.panel.dock", json!({ "panel": panel, "side": if edge == DockEdge::End { "End" } else { "Start" } }))?; + shown_again(app, id, hidden); + } + let now = docked_at(&app.ui, &panel).map(|(_, n)| n); + if let Some(n) = order.filter(|n| Some(*n) != now) { + let to = match others.get(n) { + Some(anchor) => Target::at(anchor.clone(), DockPlacement::column(false)), + None => match others.last() { + Some(last) => Target::at(last.clone(), DockPlacement::column(true)), + None => return placement(app, &name), + }, + }; + let ctx = app.ui_ctx.clone(); + panel_docking::apply(app, ctx.as_ref(), vec![Action::move_panel(panel, to)])?; + } + // A toolbar where it was asked to go shows too, which ends a Tab hide. + panel_docking::show_panels(app); + placement(app, &name) +} + +/// `window.toolbar.float`: floats the toolbar named `name` with its top-left corner at `x`, `y` in +/// window points (both or neither; neither: where the dock floats a panel, and a floating toolbar +/// stays where it is). +fn float(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?; + let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone()); + let coord = |k: &str| match p.get(k) { + None | Some(Value::Null) => Some(None), + Some(v) => v.as_f64().filter(|f| f.abs() <= 1e6).map(|f| Some(f as f32)), + }; + let at = match (coord("x"), coord("y")) { + (Some(Some(x)), Some(Some(y))) => Some(pos2(x, y)), + (Some(None), Some(None)) => None, + _ => return Err("x and y must both be numbers from -1000000 to 1000000".into()), + }; + let window = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| w.rect); + let hidden = !panel_docking::layout_of(&app.ui).contains(&panel); + match (at, window) { + (Some(at), _) => panel_docking::place_floating(app, &panel, at, window.map_or(0.0, |r| r.width()))?, + (None, None) => { + app.run("window.panel.float", json!({ "panel": panel }))?; + } + (None, Some(_)) => {} + } + shown_again(app, id, hidden); + // A toolbar floating already shows too, which ends a Tab hide. + panel_docking::show_panels(app); + placement(app, &name) +} + +/// After a command showed toolbar `id`, which was `hidden`, the groups torn off it show again, as +/// Show Toolbar brings them back. +fn shown_again(app: &mut VectorcraftApp, id: u32, hidden: bool) { + if hidden && panel_docking::layout_of(&app.ui).contains(&panel_id(id)) { + crate::toolbar::strips_follow(app, &Owner::Toolbar(id), true); + } +} + /// Opens New Toolbar: a name box whose OK is held while the name is refused, the refusal shown under /// the row. fn open_new(app: &mut VectorcraftApp) -> Result<(), String> { @@ -464,6 +591,8 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option dock(app, p), + "window.toolbar.float" => float(app, p), "window.toolbar.list" => { let layout = panel_docking::layout_of(&app.ui); Ok(json!( @@ -474,7 +603,6 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option>().len(), MAX, "every toolbar has an id of its own"); } + + /// A hidden toolbar that `window.toolbar.dock` or `window.toolbar.float` shows brings back the + /// group torn off it, as Show Toolbar does. + #[test] + fn docking_or_floating_a_hidden_toolbar_brings_back_its_torn_off_group() { + let mut app = app(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "curvature", "toolbar": "Mine", "slot": 0, "place": "group"})).unwrap(); + app.run("window.floatTools", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + let id = find(&app.ui, "Mine").unwrap().id; + let strip = strip_id(&Owner::Toolbar(id), "pen"); + let on = |app: &VectorcraftApp| panel_docking::layout_of(&app.ui).contains(&strip); + assert!(on(&app)); + for (command, params) in [ + ("window.toolbar.dock", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine", "x": 40, "y": 50})), + ] { + app.run("window.toolbar.custom", json!({"name": "Mine", "show": false})).unwrap(); + assert!(!on(&app), "the strip hides with its toolbar"); + app.run(command, params.clone()).unwrap(); + assert!(panel_docking::layout_of(&app.ui).contains(&panel_id(id)), "{command} {params} shows the toolbar"); + assert!(on(&app), "{command} {params} brings the strip back"); + } + } + + /// The dock layout, to compare. + fn layout(app: &VectorcraftApp) -> Value { + serde_json::to_value(panel_docking::layout_of(&app.ui)).unwrap() + } + + /// Where the toolbar named `name` docks: its edge and column from that edge (none: floating). + fn dock_place(app: &VectorcraftApp, name: &str) -> Option<(DockEdge, usize)> { + docked_at(&app.ui, &panel_id(find(&app.ui, name).unwrap().id)) + } + + /// `window.toolbar.dock` docks a toolbar at an edge, innermost or at the column asked for, and + /// `window.toolbar.float` floats it, at x, y when given; bad params and a toolbar already where + /// it is asked to go change nothing, and `window.toolbar.list` reports the same places. + #[test] + fn toolbars_dock_and_float_by_their_commands() { + let mut app = app(); + for name in ["A", "B", "C"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + assert_eq!(dock_place(&app, "A"), None, "New Toolbar floats"); + let undo = app.session.doc().map_or(0, |d| d.history.undo.len()); + let r = app.run("window.toolbar.dock", json!({"name": "a"})).unwrap(); + assert_eq!((&r["toolbar"], &r["floating"], &r["side"], &r["pos"]), (&json!("A"), &json!(false), &json!("left"), &Value::Null)); + let (edge, a) = dock_place(&app, "A").unwrap(); + assert_eq!(edge, DockEdge::Start); + assert_eq!(r["order"], json!(a)); + // Each one docked after it goes inside it; one asked to go at A's column goes outside it. + app.run("window.toolbar.dock", json!({"name": "B", "side": "left"})).unwrap(); + let b = dock_place(&app, "B").unwrap().1; + assert!(b > dock_place(&app, "A").unwrap().1, "B docks inside A"); + let at_a = dock_place(&app, "A").unwrap().1; + app.run("window.toolbar.dock", json!({"name": "C", "side": "start", "order": at_a})).unwrap(); + let [c, a, b] = ["C", "A", "B"].map(|n| dock_place(&app, n).unwrap().1); + assert!(c < a && a < b, "C goes outside A: {c} {a} {b}"); + // Docked again at the edge it docks at, with no column asked for, nothing changes. + let before = layout(&app); + app.run("window.toolbar.dock", json!({"name": "A"})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "A", "side": "left", "order": a})).unwrap(); + assert_eq!(layout(&app), before); + // Bad params are errors and change nothing. + let columns = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), DockEdge::Start).len(); + for p in [ + json!({"name": "A", "side": "top"}), + json!({"name": "A", "side": 1}), + json!({"name": "A", "order": columns}), + json!({"name": "A", "order": -1}), + json!({"name": "A", "order": 0.5}), + json!({"name": "A", "order": "1"}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.dock", p.clone()).is_err(), "{p}"); + } + for p in [ + json!({"name": "A", "x": 10}), + json!({"name": "A", "x": 1e7, "y": 0}), + json!({"name": "A", "x": "1", "y": 2}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.float", p.clone()).is_err(), "{p}"); + } + assert_eq!(layout(&app), before); + // The innermost column asked for: A moves inside B. + app.run("window.toolbar.dock", json!({"name": "A", "order": columns - 1})).unwrap(); + assert!(dock_place(&app, "A").unwrap().1 > dock_place(&app, "B").unwrap().1); + // At the right edge. + let r = app.run("window.toolbar.dock", json!({"name": "A", "side": "RIGHT"})).unwrap(); + assert_eq!(r["side"], json!("right")); + assert_eq!(dock_place(&app, "A").map(|(e, _)| e), Some(DockEdge::End)); + // Floated, it remembers the right edge, and docks there again. + let r = app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!((&r["floating"], &r["side"], &r["order"]), (&json!(true), &json!("right"), &Value::Null)); + assert!(r["pos"].is_array()); + let listed = app.run("window.toolbar.list", json!({})).unwrap(); + let a_row = listed.as_array().unwrap().iter().find(|t| t["name"] == "A").unwrap().clone(); + assert_eq!((&a_row["floating"], &a_row["side"]), (&json!(true), &json!("right"))); + // Floating already, with no x, y: it stays where it is. + let before = layout(&app); + app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!(layout(&app), before); + let r = app.run("window.toolbar.float", json!({"name": "A", "x": 300, "y": 200})).unwrap(); + assert_eq!(r["pos"], json!([300.0, 200.0])); + assert_eq!(app.run("window.toolbar.dock", json!({"name": "A"})).unwrap()["side"], json!("right")); + // A hidden toolbar shows where it is docked or floated to. + app.run("window.toolbar.custom", json!({"name": "B", "show": false})).unwrap(); + app.run("window.toolbar.float", json!({"name": "B", "x": 50, "y": 60})).unwrap(); + assert!(panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel_id(find(&app.ui, "B").unwrap().id)).is_some()); + // Neither command records an undo step. + assert_eq!(app.session.doc().map_or(0, |d| d.history.undo.len()), undo); + } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 940a195e4b..39d57f3165 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -659,19 +659,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.dock", "Dock Toolbar", "", - "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}", + "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` as a column of the dock along the window's left or right edge (omitted: the edge it docks at, else the edge it docked at last, the left at first), as dragging its title bar to that edge does; a hidden toolbar shows; `order` is its column's place in that edge's dock, 0 at the window's edge (omitted: the innermost, or where it is when it docks at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}, `pos` its top-left corner while it floats (else null)", ), ( "window.toolbar.float", "Float Toolbar", "", - "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}", + "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in window points (both or neither, each from -1000000 to 1000000; omitted: where the dock floats a panel, and a floating toolbar stays where it is), as dragging its title bar out of the dock does; a hidden toolbar shows; returns {toolbar, floating, side, order, pos}", ), ( "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index dce3c4aa7b..d0a7a9322f 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -267,7 +267,7 @@ fn dock_columns(layout: &Layout) -> Vec<&Column> { } /// The columns of the dock on `edge`, from the window edge inwards; none when that edge has no dock. -fn edge_columns(layout: &Layout, edge: DockEdge) -> &[Column] { +pub(crate) fn edge_columns(layout: &Layout, edge: DockEdge) -> &[Column] { let dock = layout.dock_path(edge).and_then(|path| node_at(layout.root.as_ref()?, &path)); match dock { Some(Node::Dock { columns, .. }) => columns, @@ -1113,14 +1113,18 @@ pub(crate) fn place_floating(app: &mut VectorcraftApp, panel: &str, pos: egui::P } // A rail's window is a stepped column, which the dock fits to the rail's grid; it keeps the steps it had. let steps = is_rail(&id).then(|| column_of(layout, &id).and_then(|(_, column)| column.steps).unwrap_or(1)); - actions.push(match floating_window(layout, &id) { - Some(window) if window.panels().count() == 1 => Action::move_floating(id.clone(), rect), - _ => Action::float(id.clone(), rect), - }); + let ctx = app.ui_ctx.clone(); + match floating_window(layout, &id) { + // An open OS window moves with its window: the dock keeps it where its record says. + Some(window) if window.panels().count() == 1 => { + actions.push(Action::move_floating(id.clone(), rect)); + actions.extend(native_moved(ctx.as_ref(), window, rect)); + } + _ => actions.push(Action::float(id.clone(), rect)), + } if let Some(steps) = steps { actions.push(Action::set_column_steps(id, steps)); } - let ctx = app.ui_ctx.clone(); apply(app, ctx.as_ref(), actions).map(drop) } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 996afc5964..543c06998e 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -242,6 +242,22 @@ fn an_explicit_float_command_updates_an_existing_native_windows_geometry() { } } +/// `window.toolbar.float` with x, y moves the OS window a toolbar made with New Toolbar already has. +#[test] +fn floating_a_toolbar_at_a_point_moves_its_native_window() { + let mut h = Harness::new(); + h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 240, "y": 160})).unwrap(); + h.frames(3); + let panel = crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&h.app.ui, "Mine").unwrap().id); + let viewport = h.viewport(&panel); + assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(240.0, 160.0)); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 300, "y": 220})).unwrap(); + h.frames(3); + assert_eq!(h.viewport(&panel), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(300.0, 220.0)); +} + #[test] fn keys_typed_in_a_native_window_run_the_main_windows_shortcuts() { let mut h = Harness::new(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 220bdf2e45..3db811e012 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -494,9 +494,8 @@ button (Add Tool…) opens a menu of every tool under the drawer's headings: a c there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). -`window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and -`window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its -lane does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in: +`window.toolbar.dock {name, side?, order?}` docks a toolbar as a column of the dock along the window's left or right +edge, and `window.toolbar.float {name, x?, y?}` floats it again; dragging its title bar does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them. diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..4b62e7065d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3912,36 +3912,23 @@ the window's edge. ## Docking toolbars made with New Toolbar -A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (Dock to Left and -Dock to Right in the context menu of the toolbar's title bar, remote mode, `invoke_menu`) docks it in a lane along the -window's left or right edge. On the left, the lane is right of the Tools panel when the Tools panel is docked at the -window's edge. With Keep Tools Beside the Canvas on and the Tools panel docked on the left, the lane is right of the -Tools panel beside the canvas, and dropping a title bar on the Tools panel or on the lane docks the toolbar there. `side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it -docked at last, or at the left the first time. Toolbars docked at one edge stack from the top. `order` is the -toolbar's place in that stack, 0 at the top, from 0 to the number of other toolbars docked there; without it, the -toolbar goes at the end, or stays where it is when it is already docked at that edge. Each toolbar takes an equal -share of the lane's height and its tools scroll in it, and the lane is as wide as its widest toolbar. When the lane -is too short to give each toolbar 88 points of height, the stack wraps into more columns, left to right, and the lane -widens, so no toolbar covers another. A lane takes at most half the width the canvas and panels would have (beside -the canvas, it also leaves the canvas at least 200 points, and the canvas keeps room for one column); when that -many columns still give a toolbar less than 88 points, the toolbars in those columns show only their title bars, which -still float, dock and show the context menu. A column too short for all of its title bars shows as many as fit, and -the mouse wheel over the column scrolls through the others, one toolbar per notch. -`window.toolbar.float {name, x?, y?}` (Float Toolbar in the same menu) floats it with its top-left corner at `x`, `y` -in screen points, or where it floated last when both are omitted. Both commands answer -`{toolbar, floating, side, order, pos}`: `side` is the edge the toolbar docks at (while it floats, the edge it docked -at last), `order` its place in that edge's stack (null while it floats) and `pos` where it floats (while it is docked, -where it floated last). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole -number in range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`, -`side` and `order` for each toolbar. +A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (remote mode, +`invoke_menu`) docks it as a column of the dock along the window's left or right edge, and a hidden toolbar shows. +`side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it docks at +now, else at the edge of the docked panel it left when it floated or was hidden, else at the left. `order` is the +place of the toolbar's column in that edge's dock, 0 at the window's edge, from 0 to the number of the dock's other +columns; without it, the toolbar docks as the innermost column, or stays where it is when it already docks at that +edge. `window.toolbar.float {name, x?, y?}` floats it with its top-left corner at `x`, `y` in window points, each +from -1000000 to 1000000. When both are omitted, the dock floats it as it floats a panel, and a toolbar that floats +already stays where it is. Both commands answer `{toolbar, floating, side, order, pos}`: `side` is the edge the +toolbar docks at (while it floats or is hidden, the edge `window.toolbar.dock` uses without `side`), `order` its +column's place in that edge's dock (null while it floats) and `pos` its top-left corner while it floats (null while it +is docked). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole number in +range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`, `side` +and `order` for each toolbar. -With the pointer, dropping a floating toolbar's title bar on the window's left or right edge, or on that edge's lane, -docks it at the end of that edge's stack; the target lights up while the title bar is dragged over it. Dragging a -docked toolbar's title bar out of its lane floats it under the pointer. Escape, or the window losing focus, during -the drag puts the toolbar back where it was. Hiding a docked toolbar keeps its place, renaming it keeps its place, a -copy made with Manage Toolbars' + floats, and deleting one closes up the stack. Placement is kept with the workspace. -Toolbars saved before docking existed load floating. The lanes, the edge targets and the stacking are VectorCraft's -own layout rules. +Dragging the toolbar's title bar also docks and floats it. Placement is kept with the +workspace. These are VectorCraft's own layout rules. ```json {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} From df3d7ab275829dd0c506d66ad6780faa6f579837 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:49:57 -0800 Subject: [PATCH 094/107] Scripts: stale page item lists throw from toString; unavailable members stop hasOwnProperty - `toString()` on a page item list from a closed or replaced document throws "Stale document", as its other members do. - A member a host class declares unavailable is not reported by `hasOwnProperty` or `propertyIsEnumerable` even when a parent class has it. - Assigning a name an object of a host class inherits from a prototype no longer calls the class's indexer, so a non-strict assignment is ignored instead of throwing. - Assigning a selection checks repeated objects with a set instead of scanning the list for each object. - The script report test throws a text that names `Window` for the case of an error the script wrote itself. --- crates/engine/src/script/dom.rs | 10 ++++-- crates/engine/src/tests/script_dom.rs | 10 ++++-- crates/engine/src/tests/script_run.rs | 2 +- crates/js/src/host_classes.rs | 15 +++++++-- crates/js/src/host_tests.rs | 47 +++++++++++++++++++++++++++ crates/js/src/interp.rs | 10 +++--- 6 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 39c740cb2e..a51fa67acd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1303,6 +1303,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); let locks = d.locked_artboards(); @@ -1317,7 +1318,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { Ok(text("PageItems")) } +fn items_to_string(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("[PageItems]")) +} + fn items_parent(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) @@ -2148,7 +2154,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("index", method(l, items_index)), ("getByName", method(l, items_by_name)), ("removeAll", method(l, items_remove_all)), - ("toString", class_text("PageItems")), + ("toString", method(l, items_to_string)), ]), Some(function(l, items_at)), )); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..636402a015 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -680,9 +680,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); - for (member, message) in - [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] - { + for (member, message) in [ + ("d.typename", "Stale document"), + ("d.parent", "Stale document"), + ("p.typename", "Stale document"), + ("p.toString()", "Stale document"), + ("l.typename", "Stale"), + ] { let e = failure(&mut s, &format!("#targetengine keep\n{member};")); assert!(e.contains(message), "{member}: {e}"); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0d766e238a..c12653602f 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..d2994fb80b 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -91,6 +91,8 @@ pub(crate) struct Entry { parent: Option, /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. own: Rc>, + /// The names of the members this class declares as unavailable. + unavailable: Rc>, } impl Entry { @@ -143,7 +145,9 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { impl Interp { /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host - /// class, and `k` names an available member of that class or of a class it descends from. + /// class, and `k` names an available member of that class or of a class it descends from. The + /// nearest class that declares `k` decides, so a member a class declares unavailable is not + /// reported even when a class it descends from has it. pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult { let Class::Host(h) = &self.object(id)?.class else { return Ok(false) }; let mut class = Some(h.class); @@ -152,6 +156,9 @@ impl Interp { if e.own.contains(k) { return Ok(true); } + if e.unavailable.contains(k) { + return Ok(false); + } class = e.parent; } Ok(false) @@ -307,7 +314,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + let (unavailable, members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_))); + let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::>(); i.host_classes.push(Entry { name: class.name.as_str().into(), proto, @@ -315,7 +323,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { index: class.index, family, parent: parent_class, - own: Rc::new(members), + own: Rc::new(names(members)), + unavailable: Rc::new(names(unavailable)), }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 8213e989ae..25265086e5 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -756,6 +756,53 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() { ); } +#[test] +fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let base = HostClass { + name: "Base".into(), + parent: None, + members: vec![("size".to_string(), HostMember::Get(value.clone())), ("grow".to_string(), HostMember::Method(value))], + index: None, + construct: None, + }; + let leaf = HostClass { + name: "Leaf".into(), + parent: Some("Base".into()), + members: vec![("size".to_string(), HostMember::Unavailable(missing))], + index: None, + construct: None, + }; + r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap(); + r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), it.hasOwnProperty('grow')].join()").unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into())); +} + +#[test] +fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() { + let mut r = realm(1_000_000); + let calls: Rc> = Rc::default(); + let seen = calls.clone(); + let index: HostFunction = Rc::new(move |a| { + seen.set(seen.get() + 1); + match a.get(1) { + Some(Data::Number(_)) => Ok(Data::Undefined), + _ => Err(HostError::Error("no such member".into())), + } + }); + let class = HostClass { name: "List".into(), parent: None, members: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("List", &[1.0]))]).unwrap(); + r.start("Object.prototype.extra = 1; it.extra = 2; it.extra").unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::Number(1.0)); + assert_eq!(calls.get(), 0); + // A name nothing has still goes to the indexer, which throws. + r.start("it.nope = 2").unwrap(); + assert!(finish(&mut r, 1_000_000).0.is_err()); + assert_eq!(calls.get(), 1); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 9edea621c5..95032e3d3c 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1904,16 +1904,18 @@ impl Interp { None => {} } let proto = self.object(id)?.proto; - match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { + let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten(); + match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), _ => {} } if !self.object(id)?.extensible { - // A name that an object of a host class with an indexer lacks is read with the indexer - // first, so assigning it throws what reading it throws. - if array_index(&k).is_none() + // A name that an object of a host class with an indexer lacks, and its prototypes lack + // too, is read with the indexer first, so assigning it throws what reading it throws. + if inherited.is_none() + && array_index(&k).is_none() && let Some(f) = self.host_indexer(id)? { self.host_index(&f, id, Self::indexer_key(&k), false)?; From 9c34c3a2fab70858ebb8e3464f9df3eb0ec899f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:51:20 -0800 Subject: [PATCH 095/107] Guides: a transform's reply lists the guide paths it makes of ruler guides A selected ruler guide that a transform turns to an angle becomes a selected guide path, but the reply's ids left it out: object.rotate with copy on a lone guide returned {"ids": []}. transform_ruler_guides now returns the ids of the paths it adds, and the transform commands add them after the transformed objects, on the direct-selected anchor route too. --- crates/doc/src/document_guides.rs | 8 +++-- crates/engine/src/cmd/object/transform.rs | 9 +++-- crates/engine/src/cmd/path.rs | 9 ++--- crates/engine/src/tests/menucmds.rs | 41 +++++++++++++++++++++++ docs/mcp.md | 3 +- 5 files changed, 58 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 909fedd04d..b5c993a865 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -406,8 +406,10 @@ impl Document { /// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A /// line at any other angle becomes a guide path with that line, on the guide's layer, named /// as the guide was; `sel` then holds the path as a selected object instead of the guide. - /// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. - pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) { + /// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. Returns the ids + /// of the guide paths it adds, in the order it adds them. + pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) -> Vec { + let mut paths = vec![]; for id in sel.guides.clone() { let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue }; let (a, b) = match self.transformed_guide(&g, xf) { @@ -431,7 +433,9 @@ impl Document { } self.retain_guides(sel, |g| g.id != Some(id)); sel.objects.push(path); + paths.push(path); } + paths } /// The ruler guide node `g` names, if this document has it. diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 68c681b0a5..527957f234 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -172,8 +172,9 @@ fn apply_transform_moving_guides( if c[..4] == [1.0, 0.0, 0.0, 1.0] { interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?); } + let mut ids = ids; if xf != Affine::IDENTITY { - crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?; + ids.extend(crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?); } ids } else if none || (!copy && xf == Affine::IDENTITY) { @@ -181,7 +182,7 @@ fn apply_transform_moving_guides( } else { let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None }; s.edit(label, |d, sel| { - let targets = match &kept { + let mut targets = match &kept { // The document becomes the snapshot with the kept copies, untransformed, and the // loop below transforms only the copies. Some(k) => { @@ -231,7 +232,9 @@ fn apply_transform_moving_guides( d.edit_ruler_guide(i, |g| *g = g.moved(delta)); } } else if with_guides && !is_translation { - d.transform_ruler_guides(sel, xf); + // The guide paths are made already transformed, so they join the reply after the + // loop above. + targets.extend(d.transform_ruler_guides(sel, xf)); } Ok(targets) })? diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 2859ecf1c0..525cef316a 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -330,18 +330,15 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res /// [`transform_selected`] on the active document's selection, as one undo step `label`. A /// transform other than a move also transforms the selected ruler guides -/// ([`Document::transform_ruler_guides`]). -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { +/// ([`Document::transform_ruler_guides`]). Returns the ids of the guide paths that adds. +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result> { let sel = s.doc()?.selection.clone(); // As [`transform_selected`] tells a move apart, which moves the guides itself. let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; s.edit(label, |doc, live| { transform_selected(doc, &sel, xf, sc, interpolate)?; - if !is_translation { - doc.transform_ruler_guides(live, xf); - } - Ok(()) + Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) }) }) } diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index d922be19dd..6f7fe9c581 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4644,6 +4644,47 @@ fn a_ruler_guide_rotates_with_the_selected_art() { assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s)); } +/// The reply to a transform lists the guide paths it makes of ruler guides: for a guide alone, +/// with a copy, beside selected art and beside direct-selected anchors. +#[test] +fn a_transform_replies_with_the_guide_paths_it_makes() { + fn reply_ids(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() + } + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + // A copy keeps the ruler guide and adds a guide path, the only new object. + let r = s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap(); + let [copy] = selected(&s)[..] else { panic!("the copy is selected") }; + assert_eq!(reply_ids(&r), vec![copy]); + // Without a copy the guide becomes a guide path. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let [path] = selected(&s)[..] else { panic!("one guide path selected") }; + assert_ne!(path, copy); + assert_eq!(reply_ids(&r), vec![path]); + // With art selected, the reply lists the art and then the guide path. + let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + let r = s.execute("object.rotate", &json!({"angle": 20})).unwrap(); + let paths: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [mixed] = paths[..] else { panic!("the guide path is selected with the art") }; + assert_eq!(reply_ids(&r), vec![a, mixed]); + // With direct-selected anchors, the guide path joins the reply too. + s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.is_empty()); + let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let anchored: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [made] = anchored[..] else { panic!("the guide path is selected with the path") }; + assert!(line_ends(&s, made).1, "it is a guide path"); + assert!(reply_ids(&r).contains(&made), "{r}"); +} + #[test] fn ruler_guides_and_lock() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..0762915c9d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4134,7 +4134,8 @@ Copy) and `object.transformAgain`, also when no object is selected, in one undo guide transforms as the line `view.guides.release` makes of it, and the default origin is the center of the selected objects' box and those lines together. A guide that ends up vertical or horizontal stays a ruler guide at its new place: a turn of 180° keeps it, and a turn of 90° makes a horizontal guide vertical. A guide at any other angle -becomes a guide path along its line, on the guide's layer, and is selected as one. Locked or hidden guides do not +becomes a guide path along its line, on the guide's layer, and is selected as one; the reply's `ids` list it after +the transformed objects. Locked or hidden guides do not transform, nor do guides when `ids` is given or `objects` is false. `object.rotate` with `absolute` and only ruler guides selected is an error, as guides have no bounding box angle. From 6a72901192b4c64594dd563636e9a9cb41f711fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:58:54 -0800 Subject: [PATCH 096/107] Scripts: adding Promise to a realm leaves the language it reads as it was Realm::add_es2015 no longer turns on Options::es2015, which now also selects the ECMAScript 2015 syntax. A realm made without the option gets Promise and still reads ES5.1 until set_es2015 changes it; the engine calls set_es2015 for each run before it adds Promise. --- crates/js/src/builtins/promise.rs | 10 +++++----- crates/js/src/promise_tests.rs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 655dcde430..f131e11a93 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -276,12 +276,12 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { Ok(()) } -/// Turns on [`crate::Options::es2015`] in a realm made without it and creates `Promise` there, -/// replacing a global `Promise` an earlier script defined. A realm that has the built-in `Promise` -/// already keeps it. When `Promise` cannot be created, every later run of the realm ends with an -/// internal error, as for a realm whose built-ins could not be installed. +/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global +/// `Promise` an earlier script defined, and leaves the language the realm's runs read as it is. A +/// realm that has the built-in `Promise` already keeps it. When `Promise` cannot be created, every +/// later run of the realm ends with an internal error, as for a realm whose built-ins could not be +/// installed. pub(crate) fn add_to(interp: &mut Interp) { - interp.options.es2015 = true; if interp.promises.ctor.is_some() || interp.install_error.is_some() { return; } diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 358a97a434..d65205d794 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -38,6 +38,25 @@ fn an_extendscript_realm_has_no_promise() { assert_eq!(string("typeof Promise"), "function"); } +#[test] +fn adding_promise_leaves_the_language_and_the_other_built_ins_as_they_were() { + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("typeof Promise").unwrap(), JsValue::String("function".into())); + assert_eq!(r.run("typeof Symbol").unwrap(), JsValue::String("undefined".into())); + assert!(matches!(r.run("let a = 1;"), Err(RunError { kind: RunErrorKind::Syntax, .. }))); + r.set_es2015(true); + assert_eq!(r.run("let b = 2; b").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn promise_prototype_cannot_be_replaced() { + let src = "var before = Promise.prototype; Promise.prototype = {}; \ + var p = new Promise(function () {}); \ + [Promise.prototype === before, Object.getPrototypeOf(p) === before, p instanceof Promise].join()"; + assert_eq!(string(src), "true,true,true"); +} + #[test] fn then_callbacks_run_after_the_scripts_code_in_order() { let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ From 7b9726c71eb5d73ccc9573fc2fc2e7270e584308 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:12:51 -0800 Subject: [PATCH 097/107] Scripts: Promise statics refuse arrow functions and methods as this The statics' constructor check now treats an arrow function, a method and a function bound to one as non-constructors, as new does, so Promise.resolve.call(() => {}, 1) throws a TypeError. The test262 line in docs/target-app-parity.md now gives the count on current main: 440 of 538 runs. --- crates/js/src/builtins/promise.rs | 6 +++--- crates/js/src/promise_tests.rs | 3 +++ docs/target-app-parity.md | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index f131e11a93..276acf7e96 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -911,8 +911,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -921,7 +921,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { .. } => return Ok(true), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index d65205d794..915427de89 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -182,6 +182,9 @@ fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { "Promise.prototype.then.call({}, null)", "Promise.resolve.call(1, 2)", "Promise.all.call(Math.max, [])", + "Promise.resolve.call(() => {}, 1)", + "Promise.reject.call({ m() {} }.m, 1)", + "Promise.race.call((() => {}).bind(null), [])", ] { match r.run(src) { Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e39d701ba5..a121b2716a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1101,7 +1101,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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 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: 402 of 538 runs pass, where none ran before. The 136 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and a `name` on built-in functions. `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. `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 b5d62ade367572cb40ad334035e866dc8c25bf19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:19:27 -0800 Subject: [PATCH 098/107] Selection: a turned or skewed symbol instance is outlined along its frame The selection outline and the hover highlight drew a symbol instance as the box square to the page around it, so a turned, skewed or perspective instance showed a box larger than its frame. Type in perspective had the same box. Node::drawn_corners gives the four corners of an instance's art box placed by its transform, and of type's flat bounds, both through the projection of an object in perspective. node_outline joins them, as it already does for a placed document's corners. --- crates/doc/src/perspective.rs | 32 +++++++++- crates/ui-egui/src/canvas/outline.rs | 28 ++++++--- crates/ui-egui/src/canvas/tests.rs | 88 ++++++++++++++++++++++++++++ 3 files changed, 139 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index ab347529e6..d1322de74f 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -5,9 +5,10 @@ //! stay attached and deleted objects leave nothing stale behind. use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Homography, Rect}; +use vectorcraft_geom::{Homography, Point, Rect}; -use crate::{Node, NodeKind}; +use crate::symbols::SYMBOL_SQUARE; +use crate::{Node, NodeKind, SymbolBoxes}; /// The plane an object in perspective lies on. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -58,6 +59,33 @@ impl Node { } } + /// The corners of the box a symbol instance or type is drawn in, on the page (top left, top + /// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or + /// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both + /// through the projection of type or an instance in perspective. Joined by straight lines, + /// they outline the box as drawn. When the projection sends a corner to infinity the corners + /// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other + /// objects and for type without bounds. + pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> { + let flat = match &self.kind { + NodeKind::SymbolInstance { symbol, xf } => { + let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric); + [(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y)) + } + NodeKind::Text(t) => { + let b = t.bounds()?; + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y)) + } + _ => return None, + }; + let Some(h) = self.projection() else { return Some(flat) }; + let [a, b, c, d] = flat.map(|p| h.apply(p)); + Some(match (a, b, c, d) { + (Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d], + _ => flat, + }) + } + /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An /// invertible `a` that the projection cannot follow removes it, and the art is drawn flat. pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) { diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 7a80d814d6..50ab4ed40a 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,9 +8,9 @@ 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 -/// group's clipping path only, as [`walk_drawn`] visits it). +/// Outline of a node for highlighting (paths, compound children, area type frames, image bounds, +/// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures +/// ([`Node::drawn_corners`]); 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(); walk_drawn(n, &mut |c| match &c.kind { @@ -27,13 +27,19 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp.line_to(t.xf * b); } } - } else if let Some(b) = c.geometric_bounds_with(symbols) { + } else if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); + } + } + NodeKind::Image(_) => { + if let Some(b) = c.geometric_bounds_with(symbols) { bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { - if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + // A symbol instance shows its art's box, turned, skewed or in perspective with it. + NodeKind::SymbolInstance { .. } => { + if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } // A placed document shows its box, turned with it. @@ -56,6 +62,14 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Adds the closed outline through the four corners `q` to `bp`. +fn corners(bp: &mut BezPath, q: [Point; 4]) { + let [a, b, c, d] = q; + bp.move_to(a); + [b, c, d].into_iter().for_each(|p| bp.line_to(p)); + bp.close_path(); +} + /// The most points ([`overlay_points`]) the selection's outlines and anchors, and the hover /// highlight, are drawn for: an Image Trace of a photo selects hundreds of thousands of paths at /// once, and selecting all of an opened PDF can select as many type objects, images and gradient diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..24ec91b2ca 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -53,6 +53,94 @@ fn a_symbol_instance_is_outlined_around_its_art() { assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); } +/// The points of `bp`'s move and line elements, in order. +fn outline_points(bp: &vectorcraft_geom::BezPath) -> Vec { + use vectorcraft_geom::kurbo::PathEl; + bp.elements() + .iter() + .filter_map(|el| match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p), + _ => None, + }) + .collect() +} + +/// Whether `got` are the points `want`, each within 1e-9, a last point of `got` that repeats its +/// first left out. +fn same_points(got: &[Point], want: &[Point]) -> bool { + let near = |a: &Point, b: &Point| a.distance(*b) < 1e-9; + let got = match got { + [first, rest @ .., last] if !rest.is_empty() && near(first, last) => &got[..got.len() - 1], + _ => got, + }; + got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(a, b)) +} + +/// Puts `n` in perspective, drawn through `h`. +fn in_perspective(n: &mut Node, h: vectorcraft_geom::Homography) { + let at = vectorcraft_doc::PerspectiveAttachment { projection: Some(h.to_array()), ..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0) }; + n.extras_mut().perspective = Some(Box::new(at)); +} + +#[test] +fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() { + // The 20 × 20 square symbol of the test above, its instance at (20, 30). + let svg = r##""##; + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "star.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let st = s.active().unwrap(); + let mut inst = None; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + inst = Some(n.clone()); + } + }); + let inst = inst.unwrap(); + let symbols = st.doc.symbol_boxes(); + let square = [(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)].map(|(x, y)| Point::new(x, y)); + let placed = |a: Affine| { + let mut n = inst.clone(); + let NodeKind::SymbolInstance { xf, .. } = &mut n.kind else { panic!("an instance") }; + *xf = a * *xf; + let xf = *xf; + (n, square.map(|p| xf * p)) + }; + for (case, a) in [ + ("unturned", Affine::IDENTITY), + ("turned 30 degrees", Affine::rotate_about(30f64.to_radians(), Point::new(30.0, 40.0))), + ("skewed", Affine::skew(0.5, 0.0)), + ] { + let (n, frame) = placed(a); + let got = outline_points(&node_outline(&n, &symbols)); + assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}"); + } + // In perspective, the frame's corners go through the projection. + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.004, 0.0, 1.0]]); + let mut n = inst.clone(); + in_perspective(&mut n, h); + let (_, flat) = placed(Affine::IDENTITY); + let drawn = flat.map(|p| h.apply(p).unwrap()); + let got = outline_points(&node_outline(&n, &symbols)); + assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}"); +} + +#[test] +fn type_in_perspective_is_outlined_by_its_projected_box() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "Hello world", "size": 24})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + let st = s.active().unwrap(); + let mut n = st.doc.node(id).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + let b = t.bounds().unwrap(); + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]); + in_perspective(&mut n, h); + let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap()); + let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes())); + assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}"); +} + /// One headless canvas frame on an 800 × 600 window. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; From 1fed7a4e6fa73d7c5d3ba9c428692221e38166ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:10:55 -0800 Subject: [PATCH 099/107] Cursors: a Caps Lock command before the first frame stays in place The first host Caps Lock reading is now only a baseline when view.capsLock already set the session state, so the command no longer resets on the first canvas pass. --- crates/ui-egui/src/app/view.rs | 5 +++++ crates/ui-egui/src/canvas/tool_adapter/tests.rs | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index fa5eaf858d..1dbe830af4 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -423,7 +423,12 @@ impl VectorcraftApp { if self.canvas.host_caps_lock == Some(on) { return; } + let first_reading = self.canvas.host_caps_lock.is_none(); self.canvas.host_caps_lock = Some(on); + // A `view.capsLock` call that ran before the first reading stays in place; that reading is only the baseline. + if first_reading && self.session.caps_lock { + return; + } if self.session.caps_lock != on && let Err(err) = self.run("view.capsLock", serde_json::json!({ "on": on })) { diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index be5c619a2e..1ff48b983a 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -136,3 +136,19 @@ fn the_caps_lock_command_gives_the_brushes_the_crosshair() { assert!(shows_tip(&mut app)); assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); } + +/// A `view.capsLock` call that runs before the first canvas pass stays in place when the host's Caps Lock is off. +#[test] +fn the_caps_lock_command_before_the_first_frame_stays_in_place() { + use craft::ui::runtime::windows::WindowHost; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock, "the first host reading is only the baseline"); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock); +} From ca4fa0171bf7db0d4519f72f97bc71fdd5d14bfc Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Thu, 26 Nov 2026 12:41:14 +0500 Subject: [PATCH 100/107] Stroke panel: cap icon test also checks the three strokes differ (#9229) --- crates/ui-egui/src/icons.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index fc362bce98..30b6edfb49 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -231,6 +231,13 @@ mod tests { assert_eq!(end_line(icon), butt_end, "the {name} cap icon marks the end of the path where the butt cap icon does"); assert!(stroke_opacity(icon) < 1.0, "the {name} cap icon's stroke is lighter than its end-of-path line"); } + // The stroke bar, everything before the end-of-path line, shows each cap differently. + let bar = |icon: &str| -> String { icon.rsplit_once(" Date: Wed, 25 Nov 2026 21:46:03 -0800 Subject: [PATCH 101/107] Document Info: copy the value the click was released on The click copies the value under the release event's position, and a Shift-click copies nothing even when the key release arrives in the same frame. --- crates/ui-egui/src/panels/doc_info.rs | 21 +++++++++----- crates/ui-egui/src/tests/selectall.rs | 42 +++++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 7f85921deb..87eb9f9880 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -40,14 +40,21 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool { // The value can be selected and copied, and a click copies all of it (#8432). A drag selects // and a Shift-click extends the selection, so neither copies. let shown = SelectableText::new(label.to_string(), value).show(ui); - clicked = shown.contains_pointer() - && ui.input(|i| { - let primary = egui::PointerButton::Primary; - i.pointer.button_clicked(primary) - && !i.pointer.button_double_clicked(primary) - && !i.pointer.button_triple_clicked(primary) - && i.modifiers.is_none() + // The click's own position and keys: a move or a key change after the release in the same + // frame leaves the pointer and the held keys elsewhere. A frame with more than one release + // copies nothing, since the click flags below do not say which release they describe. + let area = shown.interact_rect.intersect(ui.clip_rect()); + let primary = egui::PointerButton::Primary; + let release = ui.input(|i| { + let mut releases = i.events.iter().filter_map(|e| match e { + egui::Event::PointerButton { pos, button, pressed: false, modifiers } if *button == primary => Some((*pos, *modifiers)), + _ => None, }); + let release = releases.next().filter(|_| releases.next().is_none()); + let single = i.pointer.button_clicked(primary) && !i.pointer.button_double_clicked(primary) && !i.pointer.button_triple_clicked(primary); + release.filter(|_| single) + }); + clicked = release.is_some_and(|(pos, keys)| keys.is_none() && area.contains(pos) && ui.ctx().layer_id_at(pos) == Some(ui.layer_id())); }); clicked } diff --git a/crates/ui-egui/src/tests/selectall.rs b/crates/ui-egui/src/tests/selectall.rs index 386fe9d14b..ed97ffcdb7 100644 --- a/crates/ui-egui/src/tests/selectall.rs +++ b/crates/ui-egui/src/tests/selectall.rs @@ -382,7 +382,8 @@ fn copy_and_cut_copy_the_text_selected_in_a_panel_label() { /// #8432: a click on a Document Info value copies the whole value and says so in the status bar, and /// leaves the art. A double click copies it once, and a drag across the value or a Shift-click on -/// it copies nothing. +/// it copies nothing. The click's own position and keys count, not where the pointer and the keys +/// are at the end of its frame. #[test] fn a_click_on_a_document_info_value_copies_it() { let mut a = App::new(); @@ -408,11 +409,48 @@ fn a_click_on_a_document_info_value_copies_it() { assert!(copies(&mut a, drag).is_empty(), "a drag selects and copies nothing"); a.time += 1.0; let shift = Event::ModifiersChanged(Modifiers::SHIFT); + let shift_click = + |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }; let extended = copies( &mut a, - vec![vec![shift, Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false)], vec![Event::ModifiersChanged(Modifiers::NONE)]], + vec![ + vec![shift.clone(), Event::PointerMoved(at)], + vec![shift_click(at, true)], + vec![shift_click(at, false)], + vec![Event::ModifiersChanged(Modifiers::NONE)], + ], ); assert!(extended.is_empty(), "a Shift-click copies nothing"); + a.time += 1.0; + // Shift let go in the frame of the release: the click was still a Shift-click. + let let_go = copies( + &mut a, + vec![ + vec![shift, Event::PointerMoved(at)], + vec![shift_click(at, true)], + vec![shift_click(at, false), Event::ModifiersChanged(Modifiers::NONE)], + vec![], + ], + ); + assert!(let_go.is_empty(), "a Shift-click copies nothing when Shift is let go in the same frame"); + a.time += 1.0; + // Released on the length, then moved onto the Paths count in the same frame. + let there = text_rect(&out, "2").center(); + let moved = + copies(&mut a, vec![vec![Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false), Event::PointerMoved(there)], vec![]]); + assert_eq!(moved, [length], "a click copies the value it was released on, not the one the pointer moved to"); + a.time += 1.0; + // A click on the Paths count, then a drag across the length, in one frame. + let (from, to) = (text_rect(&out, length).left_center() + vec2(1.0, 0.0), text_rect(&out, length).right_center() - vec2(1.0, 0.0)); + let both = copies( + &mut a, + vec![ + vec![Event::PointerMoved(there)], + vec![click(there, true), click(there, false), Event::PointerMoved(from), click(from, true), Event::PointerMoved(to), click(to, false)], + vec![], + ], + ); + assert!(!both.iter().any(|t| t == length), "a drag after a click in the same frame does not copy the dragged value"); } /// Drag across a label in a window of its own (a floating panel's), selecting its text there. The From a26d5981bd9def33d08e562f8ce6666e642516a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:21:12 -0800 Subject: [PATCH 102/107] Path Precision Tools: a Tangent Circle press with Shift keeps the radius it started with A radius written with tool.setOption during a press changed the circle only when Shift was released and pressed again before the drag started. The press now keeps the radius from its button press for every Shift change until the release. --- crates/tools/src/addons/tangent_circle.rs | 25 +++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index 9ae74c0936..c04ce6b22c 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -90,6 +90,9 @@ struct Press { at: Point, /// Whether Shift was held when the click's circle was last looked for. shift: bool, + /// The tool's `radius` when the button went down: Shift uses it for the whole press, whatever + /// `tool.setOption` writes meanwhile. + shift_radius: f64, /// How far the pointer was from the press last time, and the radius the drag set (none until /// the pointer moves far enough). reach: f64, @@ -338,8 +341,8 @@ impl TangentCircleTool { // A change without an undo step since the press: a changed first segment is forgotten (the // press then draws nothing), and the circle follows the segments it may touch as they are now. self.forget_if_changed(cx); - let radius = self.radius; let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return }; + let radius = press.shift_radius; // A pressed segment that is gone leaves nothing to touch. let second = if segment_now(cx, &press.pick).is_some() { second_set(cx, first, &press.pick) } else { vec![] }; let moved = second != press.second; @@ -410,7 +413,7 @@ impl Tool for TangentCircleTool { self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX)); self.looked = true; self.hover = None; - self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None }); + self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, shift_radius: self.radius, reach: 0.0, radius: None }); vec![] } PointerKind::Drag => { @@ -707,6 +710,24 @@ mod tests { assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); } + #[test] + fn a_press_keeps_the_radius_it_started_with() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("radius", &json!(20)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0)); + // A radius written during the press does not reach the circle, however Shift changes. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &ev(PointerKind::Drag, 200.0, 139.0)); + t.pointer(&cx, &shifted(PointerKind::Drag, 200.0, 139.0)); + let released = up(&mut t, &cx, &shifted(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (180.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + #[test] fn the_preview_options_set_its_cross_radii_and_color() { let d = doc(); From 0ae1949e684a4243e154edfe7eb1a4683264969d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:32:00 -0800 Subject: [PATCH 103/107] Shapes: document that a given center moves the shape in addon.pathtools.shape.set The params text and docs/mcp.md said the center stays when no reference point applies. With a center, the shape's center moves to the given point; the docs now name that case. --- crates/engine/src/cmd/addons/pathtools/shape.rs | 2 +- docs/mcp.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 6c16893aba..135c9d964e 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Edit Parametric Shape", [], None, - "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", + "{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}", has_doc, set ), diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..bb46c73861 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15471,7 +15471,7 @@ Commands: - `addon.pathtools.shape.set {id, …}` changes a parametric shape's numbers (the same keys; a new `kind` takes its own defaults for the values not given) and redraws it in place. With `reference` (0 to 8 on the 9-point grid of the bounding box as `object.setBounds` measures it, rotated with rotated objects) and no `center`, that point of the box - keeps its place, as with the Transform panel's W and H; otherwise the shape's center stays. Snapping to the pixel + keeps its place, as with the Transform panel's W and H; with `center`, the shape's center moves to it; otherwise the shape's center stays. Snapping to the pixel grid and an attachment to a path apply after that, as they do for the Transform panel's W and H, and can move the point. A `reference` outside 0 to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; `null` when snapping to the pixel grid left a plain path). From 318770ea623871a6d03dc3422bfcd19ad343e2d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:37:50 -0800 Subject: [PATCH 104/107] File open: apply the profile answer with the settings snapshot its question was built from apply_answer read the working settings once for the reply's profileChoice and again inside apply_open_policies_choosing. A Color Settings change between the two reads could report an answer that the policies did not apply. apply_open_policies_choosing now takes the snapshot, and apply_answer passes the one it built the question from. --- crates/engine/src/cmd/colormgmt.rs | 33 +++++++++++++++++++++++----- crates/engine/src/cmd/fileio/load.rs | 6 +++-- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 54e7a3bbf4..42ee145c94 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -704,7 +704,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co /// from. → a note for each profile, and whether `d` changed. pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec, bool) { // Without a choice nothing can fail. - apply_open_policies_choosing(d, None).unwrap_or_default() + apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default() } /// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening @@ -879,10 +879,14 @@ impl ProfileQuestion { /// mismatch choice takes the place of the policy of the document's color mode, and a missing /// choice tags the document after the policies ran. A choice for the other kind of question, or /// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile -/// to assign is not a profile of that model. -pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec, bool)> { - let working = cms::working_settings(); - let question = ProfileQuestion::of(d, &working); +/// to assign is not a profile of that model. `working` is the settings snapshot the question is +/// built from and the policies are read from. +pub(crate) fn apply_open_policies_choosing( + d: &mut vectorcraft_doc::Document, + choice: Option<&ProfileChoice>, + working: &ColorSettings, +) -> Result<(Vec, bool)> { + let question = ProfileQuestion::of(d, working); let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue())); // A mismatch answer stands in for the policy of the document's color mode. let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) { @@ -1596,3 +1600,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result { } Ok(json!({"name": name, "spot": spot})) } + +#[cfg(test)] +mod tests { + use super::*; + + /// The policies come from the settings snapshot the question was built from, not from the + /// working settings as they are when the policies run. + #[test] + fn open_policies_use_the_snapshot_they_are_given() { + let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string()); + let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() }; + let mut d = vectorcraft_doc::Document::new(100.0, 100.0); + tagged(&mut d); + let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap(); + assert!(changed, "the Off policy of the snapshot takes the profile off"); + assert_eq!(d.color_profiles.rgb, None); + assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}"); + } +} diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 250fc98f9b..2b3613984a 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -884,14 +884,16 @@ impl ReadFile { if self.rest.is_none() { return Ok(()); } + // One snapshot of the working settings serves the reply and the policies. + let working = vectorcraft_color::cms::working_settings(); // The question the answer was given to, for the reply's `profileChoice`. - let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &working); let answered = match (&self.choice, &question) { (Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })), _ => None, }; // A failure leaves the file waiting, unchanged. - let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?; + let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref(), &working)?; let Some(rest) = self.rest.take() else { return Ok(()) }; self.answered = answered; self.loaded.warnings.extend(notes); From d13acd32ddd4f6cb96682d31aaa89736c4e9aa9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:44:19 -0800 Subject: [PATCH 105/107] Tools: a shared option set through another tool during a held press stays after the press is dropped Setting a Liquify brush size through another Liquify tool while a press is held was lost when the press was dropped and the value matched the size the drag had made current. The set now names the keys of the stores it shares with the pressed tool, so the dropped press keeps them. --- crates/engine/src/tests/toolsettings.rs | 19 +++++++++++++++++++ crates/engine/src/tooling.rs | 10 +++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 933ed15874..7a28a84ec7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -267,6 +267,25 @@ fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() { assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); } +/// A shared Liquify brush size set through another Liquify tool during a held press survives the +/// dropped press, also when the set value equals the size the press's drag has made current. +#[test] +fn a_shared_option_set_through_another_tool_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "warp"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + let before = s.tool_options()["width"].as_f64().unwrap(); + // The press's own change to the shared size, not stored. + s.tool.set_option("width", &json!(before + 40.0)); + let current = s.tool_options()["width"].clone(); + s.set_tool_option_cmd(&json!({"tool": "pucker", "key": "width", "value": before + 40.0})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["width"], current, "the tool keeps the size set through the other tool"); + assert_eq!(s.prefs.tool_settings["liquify"]["width"], current, "and stores it"); +} + /// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with /// the next click. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 222657ac1c..965abf399c 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1582,7 +1582,15 @@ impl Session { let set = other.id(); Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } - self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed); + // Another tool's set also names the keys of the stores it shares with the pressed tool. + let shared: Vec<&str> = match (self.pressed_tool().map(|t| t.id()), id) { + (Some(pressed), Some(set)) if pressed != set => settings::stores(pressed) + .filter(|(store, _)| settings::stores(set).any(|(s, _)| s == *store)) + .flat_map(|(_, keys)| keys.iter().copied()) + .collect(), + _ => Vec::new(), + }; + self.keep_press_set(before_press, |k| values.contains_key(k) && (sets_pressed || shared.contains(&k)), sets_pressed); // The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one. if (active || lender) && values.contains_key("stop") { let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper"; From 2f529c52a0a7b09b446e08661be047dc9bc8c52f Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 26 Nov 2026 17:34:12 +0700 Subject: [PATCH 106/107] Keyboard Shortcuts: the dialog commands a key can run are grouped under their panel or menu --- crates/ui-egui/src/shortcut_editor.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 6dfcfd0a7d..42f01d739b 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -458,33 +458,46 @@ const GROUPS: &[(&str, &str)] = &[ ("ui.actionSet.", "Window › Actions"), ("ui.blendOptions", "Window › Properties"), ("ui.brushObjectOptions", "Window › Brushes"), + ("ui.brushOptions", "Window › Brushes"), + ("ui.bulletsAndNumbering", "Window › Paragraph"), + ("ui.colorGroupOptions", "Window › Swatches"), ("ui.colorGuideOptions", "Window › Color Guide"), ("ui.colorPicker", "Color"), ("ui.colorRgbPercent", "Window › Color"), + ("ui.corners", "Window › Transform"), ("ui.dialogReset", "Dialogs"), ("ui.dxfOptionsDialog", "File"), ("ui.epsOptionsDialog", "File"), ("ui.fileInfoDialog", "File"), ("ui.findAndReplace", "Window › Properties"), + ("ui.findFontsInFolder", "Type"), ("ui.hpglOptionsDialog", "File"), ("ui.hyphenation", "Window › Paragraph"), ("ui.javascriptFilesDialog", "Window › SVG Interactivity"), ("ui.justification", "Window › Paragraph"), + ("ui.layerOptions", "Window › Layers"), ("ui.layersPanelOptions", "Window › Layers"), ("ui.loadAllStyles", "Window › Character Styles"), ("ui.loadCharStyles", "Window › Character Styles"), ("ui.loadParaStyles", "Window › Paragraph Styles"), + ("ui.missingFontsDialog", "Type"), ("ui.newArtboard", "Window › Artboards"), + ("ui.newBrush", "Window › Brushes"), ("ui.newCharStyle", "Window › Character Styles"), + ("ui.newColorGroup", "Window › Swatches"), ("ui.newLayer", "Window › Layers"), ("ui.newParaStyle", "Window › Paragraph Styles"), + ("ui.newSwatch", "Window › Swatches"), ("ui.pdfSummary.", "File"), + ("ui.perspectivePlane", "View › Perspective Grid"), ("ui.perspectiveUserPreset1.", "View › Perspective Grid › One Point Perspective"), ("ui.perspectiveUserPreset2.", "View › Perspective Grid › Two Point Perspective"), ("ui.perspectiveUserPreset3.", "View › Perspective Grid › Three Point Perspective"), + ("ui.placementOptionsDialog", "Window › Links"), ("ui.rasterEffectsSettingsDialog", "Effect"), ("ui.recolorRedo", "Edit › Edit Colors › Recolor Artwork"), ("ui.recolorUndo", "Edit › Edit Colors › Recolor Artwork"), + ("ui.relinkDialog", "Window › Links"), ("ui.rename", "Window › Layers"), ("ui.retype", "Window › Properties"), ("ui.runInstalledScript", "File › Scripts"), 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 107/107] 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