From 03b5c9ce9247d8d2093e70f4abdc56d210cf731e Mon Sep 17 00:00:00 2001 From: Alex Date: Sat, 7 Nov 2026 17:44:19 +0300 Subject: [PATCH 01/20] Panels: the Artboards list fills the panel, so the panel resizes (#6085) The Artboards panel gave its list a fixed height: `ui.set_min_height(110.0)` and `ScrollArea::max_height(220.0)`. The panel therefore kept that content size whatever the window or the floating window's height, a long list scrolled inside a small clipped area, and the buttons sat part way down with empty space below them. The list now takes the panel's height less the bottom bar, as the Layers panel's list does: `list_height()` gives `available - 46.0`, but never less than one 24-point row, with `ScrollArea::auto_shrink([false, false])` and `min_scrolled_height(0.0)`. The 46 points hold the bar's divider, the spacing around it and its 24-point buttons, as the test measures them on the screen-reader tree; at the dock's minimum height one whole row stays in view and the dock panel scrolls to the bottom bar. The list grows and shrinks with the panel, and long lists scroll in it. Tests: the panel has 36 artboards, so the list overflows a 300-point panel. panels::artboards::tests::the_list_fills_the_panel_and_the_bottom_bar_follows_its_height renders the panel 300 and 700 points tall and checks the bottom bar's divider sits at the bottom of each, the New Artboard button's bounds end inside the panel at 300, 700 and 80 points, the bar moves with the height, and the 36th row lies below the bar's divider (the list scrolls instead of pushing the bar out); it fails with the old fixed list. panels::artboards::tests::a_panel_at_the_docks_minimum_height_shows_a_whole_row checks the list keeps one whole row at the minimum height and takes the rest otherwise. The panel's `show` has a docstring. Docs: roadmap, target-app-parity (revision row, status line, evidence bullet and the UI chrome area row) and ui-parity (revision row and an Artboards checklist row), all dated 2026-11-07. --- crates/ui-egui/src/panels/artboards.rs | 21 +++- crates/ui-egui/src/panels/artboards/tests.rs | 102 +++++++++++++++++++ docs/roadmap.md | 3 +- docs/target-app-parity.md | 6 +- docs/ui-parity.md | 4 +- 5 files changed, 130 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index d02f5f0280..6150ccd9f3 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -500,6 +500,20 @@ fn select_copies(app: &mut VectorcraftApp, all: &[usize], r: &Value) { } } +/// The height of one artboard row, its name and number drawn inside it. +const ROW_H: f32 = 24.0; + +/// The list's height in a panel whose body has `available` points: the panel less the bottom bar's +/// 46 points (its divider, the spacing around it and its 24-point buttons, which the test measures), +/// but never below one row, so a panel at the dock's minimum height still shows a whole row and the +/// dock panel scrolls to the bottom bar below it. +fn list_height(available: f32) -> f32 { + (available - 46.0).max(ROW_H) +} + +/// The Artboards panel: the artboard rows with their selection, rename, lock, reorder and double-click +/// rules, the list filling the panel above the bottom bar, and the panel's buttons (`Rearrange All +/// Artboards`, `Move Up`/`Move Down`, `New Artboard`, `Delete Artboard`) in that bar. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let abs: Vec = app.session.active().map(|d| d.doc.artboards.iter().map(|a| a.name.clone()).collect()).unwrap_or_default(); @@ -514,10 +528,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut row_clicked = false; // A row dropped on another row: (from, to), the index it lands at. let mut dropped = None; + // The list grows and shrinks with the panel, taking the height the bottom bar leaves, as the + // Layers panel's list does (#6085). + let list_h = list_height(ui.available_height()); let list_rect = widgets::list_box(ui, |ui| { - ui.set_min_height(110.0); ui.spacing_mut().item_spacing.y = 0.0; - let scrolled = egui::ScrollArea::vertical().id_salt("ab-scroll").max_height(220.0).show(ui, |ui| { + let list = egui::ScrollArea::vertical().id_salt("ab-scroll").max_height(list_h).min_scrolled_height(0.0); + let scrolled = list.auto_shrink([false, false]).show(ui, |ui| { for (i, name) in abs.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click_and_drag()); if resp.drag_started() { diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index c01d82eb13..1a6b72c453 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -2,6 +2,108 @@ use super::*; use crate::widgets::accessibility_tests::{named, tree}; use vectorcraft_engine::Session; +/// The list fills the panel's height less the bottom bar, so the bar sits at the bottom of the +/// panel and follows the window's height, as the Layers panel's does (#6085). With 36 rows the +/// list overflows a short panel and scrolls instead of pushing the bar out. +#[test] +fn the_list_fills_the_panel_and_the_bottom_bar_follows_its_height() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 150, "artboards": 36})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let divider = crate::theme::Tokens::get(&ctx).divider; + // The bottom bar's divider across the panel, at the height of a panel `h` tall. + let bar_y = |app: &mut VectorcraftApp, h: f32| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.rect.height() == 1.0 && r.fill == divider => Some(r.rect.top()), + _ => None, + }) + .expect("the bottom bar draws its divider") + }; + // The bottom bar's buttons through the screen-reader tree, at the height of a panel `h` tall. + let buttons_end = |app: &mut VectorcraftApp, h: f32| { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut end = None; + for time in [0.0, 0.1] { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let nodes: Vec = + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default(); + if let Some(b) = nodes.iter().find(|n| n.label() == Some("New Artboard")).and_then(|n| n.bounds()) { + end = Some((b.y1 as f32, h)); + } + } + end.expect("the bottom bar's New Artboard button is named") + }; + // The 36th row's name: in a 300-point panel it lies below the bar's divider, so the list + // scrolls inside the panel and does not move the bar down. + let last_row = |app: &mut VectorcraftApp, h: f32| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text() == "Artboard 36" => Some(t.visual_bounding_rect()), + _ => None, + }) + .expect("the 36th row is laid out") + }; + let (short_buttons, _) = buttons_end(&mut app, 300.0); + let short = bar_y(&mut app, 300.0); + let last = last_row(&mut app, 300.0); + assert!(last.top() > short, "the 36 rows overflow a 300 px panel: row 36 at {last:?}, the bar at {short}"); + let (tall_buttons, _) = buttons_end(&mut app, 700.0); + let tall = bar_y(&mut app, 700.0); + assert!(short_buttons <= 300.0 - 1.0, "the bar's buttons end inside a 300 px panel, not below it: {short_buttons}"); + assert!(tall_buttons <= 700.0 - 1.0, "and inside a 700 px one: {tall_buttons}"); + // A panel as short as the dock allows (80 points) still keeps its buttons inside. + let (tiny_buttons, _) = buttons_end(&mut app, 80.0); + assert!(tiny_buttons <= 80.0 - 1.0, "and inside an 80 px one: {tiny_buttons}"); + assert!(short > 300.0 - 40.0, "the bar sits at the bottom of a 300 px panel: {short}"); + assert!(tall - short > 350.0, "the bar follows the panel's height: {short} -> {tall}"); +} +/// A panel at the dock's minimum height keeps one whole 24-point row in view, with the dock panel +/// scrolling to the bottom bar below it; a roomier panel gives the list the rest of its height (#6085). +#[test] +fn a_panel_at_the_docks_minimum_height_shows_a_whole_row() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 150, "artboards": 36})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let border = crate::theme::Tokens::get(&ctx).input_border; + // The list box frame drawn by a panel `h` points tall. + let list = |app: &mut VectorcraftApp, h: f32| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, h)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.stroke.width == 1.0 && r.stroke.color == border && r.rect.width() > 200.0 => Some(r.rect), + _ => None, + }) + .expect("the list box's frame") + }; + assert_eq!(list_height(0.0), ROW_H, "never below one row"); + assert_eq!(list_height(60.0), ROW_H, "at the dock's minimum height one row still fits"); + assert_eq!(list_height(200.0), 154.0, "and otherwise the bottom bar's 46 points are left"); + assert!(list(&mut app, 60.0).height() >= ROW_H, "one whole row at the dock's minimum height"); + let roomy = list(&mut app, 300.0); + assert!(roomy.height() >= 200.0 && roomy.height() < 300.0, "a roomier panel gives the list its height: {roomy:?}"); +} /// Clicking a row makes its artboard the active one (the navigator's, Fit Artboard in Window's). #[test] fn clicking_a_row_makes_its_artboard_active() { diff --git a/docs/roadmap.md b/docs/roadmap.md index c4246c7114..2e1de3e722 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Panels: the Artboards panel's list fills the panel, so it resizes with the window as the Layers panel does, #6085; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -36,6 +36,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Panels: the Artboards panel's list fills the panel and the buttons stay at its bottom, so the panel resizes with the window like the Layers panel (#6085); scores and estimates unchanged. | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | | 2026-11-05 | minor | Effect dialogs: a colour swatch beside a hex colour field follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills the field (#5365); scores and estimates unchanged. | | 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0af2f06708..0c171eb047 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-07 · **Change:** minor (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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Panels: the Artboards panel's list fills the panel, so it resizes with the window as the Layers panel does, #6085; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -31,6 +31,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Panels: the Artboards panel's list fills the panel's height and the buttons stay at its bottom, so the panel resizes with the window like the Layers panel (#6085); scores and estimates unchanged. | | 2026-11-07 | minor | The canvas keeps selection outlines, anchors and handles between frames, so an idle frame with a large selection redraws them as one mesh; scores and estimates unchanged | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | | 2026-11-06 | minor | Stroke gradients: an arrowhead whose tip sits on the end of a long straight leg is painted by the gradient to the corners of its base. The slices that reach across a head now run to the end of its reach instead of narrowing towards the next corner (#5964). Test: `stroke::tests_gradient::slices_cover_an_arrowhead_on_a_long_straight_leg`. Scores and estimates unchanged. | @@ -211,7 +212,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -555,6 +556,7 @@ since 2026-10-01. - **Effects in the art's bounds:** Export with Use Artboards off, Fit to Artwork Bounds, and the other exports of the whole art (EPS without artboards, Export for Screens' Full Document, Save for Web (Legacy) with Clip to Artboard off) measure each visible object as the export crops above do. The drop shadows and other effects of groups, layers, type and images are inside the image or the artboard. A Shaper group without effects of its own is measured by the art it shows, and the hidden members of a group with a drop shadow, a glow or another raster effect do not count unless it is a Shaper group or also has a geometry, Pathfinder, Crop Marks or 3D effect or a visible effect on its own fill or stroke. The SVG of an artboard keeps an object whose effects alone reach the artboard. Tests measure a group, type and an image with a drop shadow, export a group and type with Use Artboards off and fit an artboard to them. +- **The Artboards panel resizes with the window (#6085):** its list takes the panel's height less the bottom bar, as the Layers panel's list does, so a long artboard list scrolls in a panel that grows and shrinks with the window and the buttons stay at its bottom (`panels::artboards` test `the_list_fills_the_panel_and_the_bottom_bar_follows_its_height`, which fails with the old fixed 110/220 px list). - **Selected artboard deletion:** the Artboards panel menu, panel trash button and Properties use the same selected set; selecting all retains artboard 1. Pointer-event tests cover nonadjacent and single selections, the original first-board survivor, ordinary artwork, Undo/Redo and the single-board guard. Public reference: [Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). - **Delete Empty Artboards:** the Artboards panel menu item ([Delete artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html)) runs `artboard.deleteEmpty`: every unlocked artboard with no artwork goes with its guides in one undo step, artboard 1 stays when every artboard is empty and none is locked, and the panel makes an artboard that is left active; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule). Engine tests in `tests/panelcmds.rs` (`delete_empty_artboards_*`) and the panel test `delete_empty_artboards_deletes_the_empty_ones_and_selects_one_left`. The menu item's enabled check measures nothing in a document with one artboard, and Save Gradient Preset's check reads the proxy's paint without measuring the object; both give the same answer as before. An artboard that no path's control points, grown by the farthest its strokes reach, can meet is found empty without measuring the path. With an open path of 200,000 anchors selected, the checks take under 0.01 ms instead of 21.9 ms and 17.2 ms in a release build; with a second, empty artboard, Delete Empty Artboards' check takes 0.85 ms instead of 42.1 ms. Tests `delete_empty_artboards_is_enabled_exactly_when_it_deletes_something`, `delete_empty_artboards_enabled_state_matches_the_command_on_varied_documents`, `empty_artboard_checks_match_the_visual_bounds_on_varied_strokes`, `the_empty_artboard_check_matches_measuring_every_artboard`, `the_save_check_matches_saving_with_and_without_a_gradient`, `the_unmeasured_proxy_paint_is_the_measured_one` and `the_unmeasured_proxy_paint_is_the_measured_one_on_varied_objects`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4efbee4aa2..961cb7fef3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Panels: the Artboards panel's list fills the panel, so it resizes with the window as the Layers panel does, #6085; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence @@ -39,6 +39,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Panels: the Artboards panel's list fills the panel and the buttons stay at its bottom, so the panel resizes with the window (#6085); scores and estimates unchanged | | 2026-10-30 | minor | Home screen: welcome, New / Open and Community are centred and the large Discord button uses the theme accent, part of #4684; scores and estimates unchanged (estimated) | | 2026-11-06 | minor | Snap to Grid: a straight segment dragged with Direct Selection lands its anchors on the grid, not the pressed point (#3835); scores and estimates unchanged | | 2026-11-06 | minor | Drop Shadow: a swatch beside Color follows the hex and a double-click opens the Color Picker over the dialog, whose OK fills Color (#5364); scores and estimates unchanged | @@ -291,6 +292,7 @@ tools, never checked side by side) isn't captured row by row. | Selection tool: selected area type and type on a path show an in port and an out port (empty, an arrow where threaded, the red "+" of overflow); a click on either loads the text cursor; a click on a closed path, on empty canvas or a drag threads the text there, after the clicked frame from its out port, before it from its in port; Escape or another tool drops it; a double-click on a threaded port breaks the thread there | partial | #2572 (`text.thread.add`, `before` for the in port); the out port sits on the frame's right side above the bottom-right corner handle and the in port on its left side below the top-left one, so the handles can still be grabbed; a double-click on a threaded port breaks the thread (`text.thread.break`, [archived help](https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html)); the loaded cursor borrows the I-beam | | Shift-click selects several artboards (Artboard tool, Artboards panel); they move, Alt-copy and delete together | done | `artboard.move`/`artboard.delete` `indices` (#1139); in the panel, Shift- and Ctrl/Cmd-click work with any tool by switching to the Artboard tool (#5698); panel menu, trash and Properties share selected-set deletion; all-selected retains artboard 1 and a single board cannot be deleted, with pointer-event and Undo/Redo coverage | | Artboards panel: drag a row above or below another to reorder the artboards (as Move Up / Move Down do) | done | #4687; a line shows where the row lands, `artboard.reorder` in one undo step, the moved artboard becomes active; public forum answers describe the drag | +| Artboards panel: the list fills the panel's height and the buttons stay at its bottom, so the panel resizes with the window like the Layers panel (#6085) | done | the list takes ui.available_height() less the bottom bar with ScrollArea::auto_shrink([false, false]); panels::artboards test he_list_fills_the_panel_and_the_bottom_bar_follows_its_height | | Artboards panel › Delete Empty Artboards | done | `artboard.deleteEmpty`; one undo step, guides go too, locked artboards stay, and artboard 1 when every artboard is empty and none is locked; an artboard is empty when no object (hidden, locked and template art included; guides not) has visual bounds that meet or touch it, a group counting by its members and a clip group or clipping layer by its members inside the clip (our reading of "no artwork"; the pages give no finer rule); [spec](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html) | | Artboard Delete/Backspace delete selected boards while protecting artwork, the last board and active drags | done | Headless shortcut regressions in `tests/distortkeys.rs` cover retaining the original first board when all are selected, single-board protection, artwork, saved state and Undo/Redo; the navigator follows the tool’s surviving board through repeated deletion and history changes. | | Artboard navigator synchronizes the active tool selection before deletion | done | Actual status-bar Next → Delete/Backspace and Next → Properties Delete regressions in `chrome.rs` cover surviving board records, preserved artwork and Undo/Redo; other tools keep object selection and history. **Tab-switch follow-up:** document-tab changes align the Artboard tool with the displayed board. Actual A → B → A tab clicks followed by Properties Delete and controls for same-tab multiselection, Move/Scale Artwork options and other tools passed, along with historical full CI on `a0671777`. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). **Clean-tab close:** with the Artboard tool active, closing a clean active tab restores the surviving document's displayed board before Properties Delete. | From 33c58357220851e207a58b093cbffdeaf02add93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:33:53 -0800 Subject: [PATCH 02/20] Plug-ins: a command's manifest can list it in the canvas and Layers panel context menus At plug-in API level 2 a command's `menu` may give `context`: a list of `{"menu": "canvas" | "layers", "when"?: condition}`, with or without a `path`. The canvas context menu lists the command while objects are selected, and the menu of a Layers panel layer, group or object row lists it too, in a Plug-ins submenu that holds a submenu named after each plug-in. `when` is one of selection, oneObject, typeObject and layerRow (Layers panel only); while it fails the item is dimmed. Choosing the item runs `plugin..` with the selection, or with the clicked or highlighted rows whatever is selected, as `ids`, as one undo step. A command with parameters opens its dialog for those objects first, and its preview and OK run on them. A `context` that is not a list, an entry of the wrong shape, an unknown menu or condition, layerRow for the canvas, a menu named twice and more than 8 commands of one plug-in in one context menu are refused when the module is installed, and the error names the command and the key. `plugin.list` gives the command's `menu.context`. The three new messages have an `@msg` row in each complete-message catalog. --- crates/engine/src/cmd/plugin.rs | 5 +- crates/engine/tests/plugin_fuzz.rs | 19 +- crates/plugins/src/lib.rs | 2 +- crates/plugins/src/manifest.rs | 224 ++++++++++++++++++++++- crates/ui-egui/src/dialogs/plugin.rs | 97 +++++++++- crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tests.rs | 26 ++- crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/menus/context.rs | 8 +- crates/ui-egui/src/menus/invoke.rs | 5 +- crates/ui-egui/src/menus/state.rs | 4 +- crates/ui-egui/src/panels/layers.rs | 7 +- crates/ui-egui/src/panels/layers/rows.rs | 21 ++- crates/ui-egui/src/tests/plugins.rs | 98 ++++++++++ docs/mcp.md | 7 +- docs/plugins.md | 39 +++- docs/target-app-parity.md | 1 + 40 files changed, 597 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index cef2b14775..aa08715bd7 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -126,6 +126,9 @@ pub fn describe(p: &Plugin) -> Value { } entry["menu"] = menu; } + if !c.context.is_empty() { + entry["menu"]["context"] = json!(c.context); + } entry }) .collect(); @@ -1548,7 +1551,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, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (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), 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, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (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 ), diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 158a4d6798..41ca3446f1 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -707,10 +707,11 @@ proptest! { } /// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with - /// control and bidirectional override characters, a `menu` of any shape naming any menu, junk - /// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no - /// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest - /// may name, with the plug-in's name; installing one and running each of its commands ends as an + /// control and bidirectional override characters, a `menu` of any shape naming any menu or + /// context menu, junk parameters) at API level 1 or 2 parse to an error or to commands whose + /// menu labels show no hidden character and that sit under Plug-ins, or at level 2 in one of the + /// menus a manifest may name, with the plug-in's name, and in at most the capped number of + /// context menu items; installing one and running each of its commands ends as an /// error or an edit, never a panic, and the document then renders and exports. #[test] fn hostile_manifest_commands_never_crash( @@ -733,6 +734,11 @@ proptest! { Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})), arb_junk().prop_map(|j| json!({"path": j})), arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})), + Just(json!({"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers", "when": "layerRow"}]})), + Just(json!({"context": [{"menu": "canvas", "when": "layerRow"}]})), + arb_junk().prop_map(|j| json!({"context": j})), + arb_junk().prop_map(|j| json!({"context": [{"menu": "layers", "when": j}]})), + arb_junk().prop_map(|j| json!({"path": ["Select"], "context": [j]})), arb_junk(), ], prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()], @@ -774,6 +780,11 @@ proptest! { prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place); prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed); } + prop_assert!(api >= 2 || c.context.is_empty(), "level 1 lists no context menu: {:?}", c.context); + prop_assert!(c.context.iter().all(|p| p.menu == vectorcraft_plugins::ContextMenu::Layers || p.when != Some(vectorcraft_plugins::ContextWhen::LayerRow))); + } + for menu in [vectorcraft_plugins::ContextMenu::Canvas, vectorcraft_plugins::ContextMenu::Layers] { + prop_assert!(man.context_commands(menu).count() <= vectorcraft_plugins::manifest::MAX_CONTEXT_COMMANDS); } } let mut s = rich_session(); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index dada995bb3..200b8575cb 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -52,7 +52,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; +pub use manifest::{Budget, Command, ContextMenu, ContextPlace, ContextWhen, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b96ae96bde..600df2da34 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -51,6 +51,9 @@ pub const MENU_PLACES: &[&[&str]] = &[ &["View"], ]; +/// Most commands of one plug-in that one context menu lists (`menu.context`). +pub const MAX_CONTEXT_COMMANDS: usize = 8; + /// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the /// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when /// `after` is left out or names no built-in item there. @@ -61,9 +64,119 @@ pub struct MenuPlace { pub after: Option, } +/// A context menu a command's `menu.context` lists it in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ContextMenu { + /// The canvas context menu, while objects are selected. + Canvas, + /// The menu of a layer, group or object row of the Layers panel. + Layers, +} + +impl ContextMenu { + /// Its name in a manifest. + pub fn name(self) -> &'static str { + match self { + ContextMenu::Canvas => "canvas", + ContextMenu::Layers => "layers", + } + } +} + +/// When a context menu item can be chosen (`when`); without one it always can. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ContextWhen { + /// One or more objects are selected (in the Layers panel: one or more rows are clicked). + Selection, + /// Exactly one object, which is not a layer, is selected or clicked. + OneObject, + /// One of the objects selected or clicked is a type object. + TypeObject, + /// Every row clicked in the Layers panel is a layer or sublayer (Layers panel only). + LayerRow, +} + +impl ContextWhen { + const ALL: [(&'static str, ContextWhen); 4] = [ + ("selection", ContextWhen::Selection), + ("oneObject", ContextWhen::OneObject), + ("typeObject", ContextWhen::TypeObject), + ("layerRow", ContextWhen::LayerRow), + ]; + + /// The conditions context menu `menu` takes: every one in the Layers panel, all but + /// `layerRow` on the canvas. + fn allowed(menu: ContextMenu) -> impl Iterator { + Self::ALL.into_iter().filter(move |(_, w)| menu == ContextMenu::Layers || *w != ContextWhen::LayerRow) + } +} + +/// One entry of a command's `menu.context`: the context menu that lists it and when its item can +/// be chosen. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct ContextPlace { + pub menu: ContextMenu, + #[serde(skip_serializing_if = "Option::is_none")] + pub when: Option, +} + +impl ContextPlace { + /// Reads `menu.context`: a list of `{"menu": "canvas" | "layers", "when"?: condition}`, each + /// menu at most once. + fn read_list(v: &Value) -> std::result::Result, String> { + let Some(list) = v.as_array() else { + let key = "menu.context"; + return Err(format!("`{key}` must be a list")); + }; + let mut out: Vec = Vec::with_capacity(list.len().min(2)); + for (i, entry) in list.iter().enumerate() { + let Some(o) = entry.as_object() else { + let key = format!("menu.context[{i}]"); + return Err(format!("`{key}` must be an object")); + }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "menu" | "when")) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(format!("unknown key `{k}`; the keys here are {}", "menu, when")); + } + let menu = match o.get("menu").and_then(Value::as_str) { + Some("canvas") => ContextMenu::Canvas, + Some("layers") => ContextMenu::Layers, + _ => { + let k = format!("menu.context[{i}].menu"); + return Err(format!("`{k}` must be one of {}", "\"canvas\", \"layers\"")); + } + }; + let when = match o.get("when") { + None => None, + Some(w) => { + let found = w.as_str().and_then(|w| ContextWhen::allowed(menu).find(|(name, _)| *name == w)); + match found { + Some((_, when)) => Some(when), + None => { + let k = format!("menu.context[{i}].when"); + let names: Vec = ContextWhen::allowed(menu).map(|(name, _)| format!("{name:?}")).collect(); + return Err(format!("`{k}` must be one of {}", names.join(", "))); + } + } + } + }; + if out.iter().any(|p| p.menu == menu) { + let (key, name) = ("menu.context", menu.name()); + return Err(format!("`{key}` names \"{name}\" twice")); + } + out.push(ContextPlace { menu, when }); + } + Ok(out) + } +} + impl MenuPlace { - /// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`. - fn read(v: &Value) -> std::result::Result { + /// Reads a command's `menu` value: `{"path"?: [label, …], "after"?: label, "context"?: [...]}` + /// ([`ContextPlace::read_list`]). `path` may be left out only when `context` is given, and + /// `after` only goes with `path`. + fn read(v: &Value) -> std::result::Result<(Option, Vec), String> { let wrong_path = || { let k = "menu.path"; let places: Vec = @@ -74,9 +187,16 @@ impl MenuPlace { let key = "menu"; return Err(format!("`{key}` must be an object")); }; - if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) { + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after" | "context")) { let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); - return Err(format!("unknown key `{k}`; the keys here are {}", "path, after")); + return Err(format!("unknown key `{k}`; the keys here are {}", "path, after, context")); + } + let context = match o.get("context") { + Some(c) => ContextPlace::read_list(c)?, + None => Vec::new(), + }; + if o.get("context").is_some() && !o.contains_key("path") && !o.contains_key("after") { + return Ok((None, context)); } let path: Vec<&str> = match o.get("path").and_then(Value::as_array) { Some(path) => path.iter().map(Value::as_str).collect::>().ok_or_else(wrong_path)?, @@ -95,7 +215,7 @@ impl MenuPlace { } Some(_) => return Err(format!("`{key}` must be a string")), }; - Ok(MenuPlace { path, after }) + Ok((Some(MenuPlace { path, after }), context)) } } @@ -305,6 +425,10 @@ pub struct Command { /// [`crate::permissions::MENU_API`] and later). #[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")] pub place: Option, + /// The context menus that also list it (`menu.context`, read at + /// [`crate::permissions::MENU_API`] and later), at most one entry per menu. + #[serde(skip)] + pub context: Vec, /// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them. #[serde(skip)] pub(crate) declared_menu: Vec, @@ -497,7 +621,7 @@ impl Manifest { continue; } let name = command_name(i, &c.id); - let place = match menus.as_slice() { + let read = match menus.as_slice() { [] => continue, [menu] => MenuPlace::read(menu), _ => { @@ -505,11 +629,27 @@ impl Manifest { Err(format!("duplicate field `{key}`")) } }; - c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?); + (c.place, c.context) = read.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?; + } + // Each context menu lists at most MAX_CONTEXT_COMMANDS of the plug-in's commands; the + // error names the first command past that. + for menu in [ContextMenu::Canvas, ContextMenu::Layers] { + let mut listed = self.commands.iter().enumerate().filter(|(_, c)| c.context.iter().any(|p| p.menu == menu)); + if let Some((i, c)) = listed.nth(MAX_CONTEXT_COMMANDS) { + let (name, key) = (command_name(i, &c.id), "menu.context"); + let e = format!("`{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu"); + return Err(Error::Manifest(format!("command {name}: {e}"))); + } } Ok(()) } + /// The commands context menu `menu` lists (`menu.context`), in manifest order, each with when + /// its item can be chosen. + pub fn context_commands(&self, menu: ContextMenu) -> impl Iterator)> { + self.commands.iter().filter_map(move |c| c.context.iter().find(|p| p.menu == menu).map(|p| (c, p.when))) + } + /// Checks what the module declared: its id, name and text lengths, its extensions, a budget its /// kind may have (only a filter may be heavy), and each parameter and its dialog layout. fn validate(&self) -> Result<()> { @@ -958,7 +1098,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu let Some(label) = label else { return Err(named(&Some(id), &"missing field `label`")); }; - Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu }) + Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, context: Vec::new(), declared_menu: menu }) } } @@ -1356,7 +1496,9 @@ mod tests { assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none()); let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap(); assert_eq!(effect.commands.len(), 1); - let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label(); + let label = |l: &str| { + Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, context: Vec::new(), declared_menu: Vec::new() }.shown_label() + }; assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe"); let many: Vec = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect(); @@ -1468,6 +1610,70 @@ mod tests { assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`")); } + /// At API level 2 a command's `menu.context` lists it in the canvas and Layers panel context + /// menus, each with an optional `when` from a fixed list, with or without a `path`. A context + /// entry of the wrong shape, an unknown menu or condition, `layerRow` on the canvas, a menu + /// named twice and more than [`MAX_CONTEXT_COMMANDS`] commands in one menu are refused, and the + /// error names the command and the key. At level 1 the key is ignored. + #[test] + fn a_command_menu_context_lists_it_in_context_menus() { + let with = |api: u32, menu: &str| { + format!(r#"{{"id":"org.example.t","name":"Tidy","api":{api},"kind":"filter","commands":[{{"id":"tidy","label":"Tidy","menu":{menu}}}]}}"#) + }; + let m = Manifest::parse(with(2, r#"{"context":[{"menu":"canvas","when":"typeObject"},{"menu":"layers"}]}"#).as_bytes()).unwrap(); + let c = &m.commands[0]; + assert_eq!(c.place, None, "no other menu: it stays in its plug-in's submenu"); + assert_eq!( + c.context, + vec![ + ContextPlace { menu: ContextMenu::Canvas, when: Some(ContextWhen::TypeObject) }, + ContextPlace { menu: ContextMenu::Layers, when: None } + ] + ); + assert_eq!(c.menu_label(&m.name), "Tidy", "a context item is not renamed"); + assert_eq!(m.context_commands(ContextMenu::Layers).map(|(c, w)| (c.id.as_str(), w)).collect::>(), [("tidy", None)]); + let both = Manifest::parse(with(2, r#"{"path":["Select"],"context":[{"menu":"layers","when":"layerRow"}]}"#).as_bytes()).unwrap(); + assert_eq!(both.commands[0].place, Some(MenuPlace { path: &["Select"], after: None })); + assert_eq!(both.commands[0].context, vec![ContextPlace { menu: ContextMenu::Layers, when: Some(ContextWhen::LayerRow) }]); + assert!(Manifest::parse(with(2, r#"{"context":[]}"#).as_bytes()).unwrap().commands[0].context.is_empty()); + assert!(Manifest::parse(with(1, r#"{"context":[{"menu":"sky"}]}"#).as_bytes()).unwrap().commands[0].context.is_empty(), "ignored at level 1"); + + for (menu, says) in [ + (r#"{"context":"canvas"}"#, "`menu.context` must be a list"), + (r#"{"context":["canvas"]}"#, "`menu.context[0]` must be an object"), + (r#"{"context":[{"menu":"canvas","if":"selection"}]}"#, "unknown key `if`"), + (r#"{"context":[{"menu":"Canvas"}]}"#, "`menu.context[0].menu` must be one of \"canvas\", \"layers\""), + (r#"{"context":[{}]}"#, "`menu.context[0].menu` must be one of"), + (r#"{"context":[{"menu":"layers"},{"menu":"canvas","when":"always"}]}"#, "`menu.context[1].when` must be one of"), + ( + r#"{"context":[{"menu":"canvas","when":"layerRow"}]}"#, + "`menu.context[0].when` must be one of \"selection\", \"oneObject\", \"typeObject\"", + ), + (r#"{"context":[{"menu":"canvas","when":1}]}"#, "`menu.context[0].when` must be one of"), + (r#"{"context":[{"menu":"canvas"},{"menu":"canvas"}]}"#, "`menu.context` names \"canvas\" twice"), + (r#"{"after":"Inverse","context":[{"menu":"canvas"}]}"#, "`menu.path` must be one of"), + (r#"{"path":["File"],"context":[{"menu":"canvas"}]}"#, "`menu.path` must be one of"), + ] { + let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string(); + assert!(e.contains("command `tidy`") && e.contains(says), "{menu}: {e}"); + } + + let listed = |n: usize, menu: &str| { + let commands: Vec = + (0..n).map(|i| format!(r#"{{"id":"c{i}","label":"C{i}","menu":{{"context":[{{"menu":"{menu}"}}]}}}}"#)).collect(); + format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{}]}}"#, commands.join(",")) + }; + for menu in ["canvas", "layers"] { + assert_eq!( + Manifest::parse(listed(MAX_CONTEXT_COMMANDS, menu).as_bytes()).unwrap().context_commands(ContextMenu::Canvas).count(), + if menu == "canvas" { MAX_CONTEXT_COMMANDS } else { 0 } + ); + let e = Manifest::parse(listed(MAX_CONTEXT_COMMANDS + 1, menu).as_bytes()).unwrap_err().to_string(); + let past = format!("command `c{MAX_CONTEXT_COMMANDS}`"); + assert!(e.contains(&past) && e.contains("`menu.context`: a plug-in may put at most 8 commands in each context menu"), "{e}"); + } + } + #[test] fn strings_and_number_lists_resolve_like_the_other_types() { let m = Manifest::parse( diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 14573a611d..d41036d131 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -28,7 +28,7 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::plugin::InstallApproval; -use vectorcraft_plugins::{Budget, Kind, Manifest, Plugin, permissions, registry}; +use vectorcraft_plugins::{Budget, ContextMenu, ContextWhen, Kind, Manifest, Plugin, permissions, registry}; use super::{DialogAction, DialogSpec, form}; use crate::VectorcraftApp; @@ -182,6 +182,75 @@ fn leave_out(items: &mut [Item], placed: &std::collections::HashSet<&str>) { } } +/// Does condition `when` of a context menu item hold for objects `ids` of `doc` (the selection on +/// the canvas, the clicked rows in the Layers panel)? `selection`: one or more; `oneObject`: one, +/// which is not a layer; `typeObject`: one of them is a type object; `layerRow`: each is a layer or +/// sublayer. Without a condition the item can always be chosen. +pub fn context_holds(doc: &vectorcraft_doc::Document, ids: &[u64], when: Option) -> bool { + let nodes = || ids.iter().filter_map(|id| doc.node(vectorcraft_doc::NodeId(*id))); + match when { + None => true, + Some(ContextWhen::Selection) => !ids.is_empty(), + Some(ContextWhen::OneObject) => ids.len() == 1 && nodes().count() == 1 && nodes().all(|n| !n.is_layer()), + Some(ContextWhen::TypeObject) => nodes().any(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Text(_))), + Some(ContextWhen::LayerRow) => !ids.is_empty() && nodes().count() == ids.len() && nodes().all(|n| n.is_layer()), + } +} + +/// One plug-in command of a context menu: its label (with an ellipsis when it has parameters), its +/// command id and whether its condition holds. +#[derive(Clone, Debug, PartialEq)] +pub struct ContextCommand { + pub label: &'static str, + pub command: &'static str, + pub enabled: bool, +} + +/// The plug-in commands context menu `menu` lists for objects `ids` of `doc` +/// ([`vectorcraft_plugins::Command::context`]): for each filter or live effect, in plug-in id +/// order, its name as it is and its commands in manifest order, each enabled only while its `when` +/// holds ([`context_holds`]). +pub fn context_commands(menu: ContextMenu, doc: &vectorcraft_doc::Document, ids: &[u64]) -> Vec<(&'static str, Vec)> { + registry::list() + .iter() + .filter(|p| matches!(p.manifest().kind, Kind::Filter | Kind::Effect)) + .filter_map(|p| { + let m = p.manifest(); + let commands: Vec = m + .context_commands(menu) + .map(|(c, when)| ContextCommand { + label: label(&c.shown_label(), !c.params.is_empty()), + command: registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)), + enabled: context_holds(doc, ids, when), + }) + .collect(); + let name = registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)); + (!commands.is_empty()).then_some((name, commands)) + }) + .collect() +} + +/// The canvas context menu's Plug-ins submenu for the selection `ids`: a submenu per plug-in that +/// lists commands there, named after it, each item running its command on `ids`. `None` when no +/// installed plug-in lists a command there. +pub fn canvas_submenu(doc: &vectorcraft_doc::Document, ids: &[u64]) -> Option { + let groups: Vec = context_commands(ContextMenu::Canvas, doc, ids) + .into_iter() + .map(|(name, commands)| Item::Sub(name, commands.into_iter().map(|c| Item::Cmd(c.label, c.command, json!({ "ids": ids }))).collect())) + .collect(); + (!groups.is_empty()).then_some(Item::Sub("Plug-ins", groups)) +} + +/// Can the canvas context menu's item for plug-in command `id` with `p` be chosen? Only an item +/// that carries `ids` ([`canvas_submenu`]) has a condition; every other item can. +pub fn canvas_item_enabled(app: &VectorcraftApp, id: &str, p: &Value) -> bool { + let Some(ids) = p.get("ids").and_then(Value::as_array) else { return true }; + let Some((_, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return true }; + let Some(place) = c.context.iter().find(|p| p.menu == ContextMenu::Canvas) else { return true }; + let ids: Vec = ids.iter().filter_map(Value::as_u64).collect(); + app.session.active().is_some_and(|st| context_holds(&st.doc, &ids, place.when)) +} + /// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then /// Install Plug-in… and Reload Plug-ins. pub fn object_menu() -> Vec { @@ -277,17 +346,25 @@ fn described(ui: &mut egui::Ui, d: &Dialog) -> Option> { Some(plugin) } -/// Opens the dialog of plug-in command `id` (`plugin..`), given no params, -/// when it has parameters and a document is open: its fields at their defaults (`__command` is the -/// command id) with a live Preview, and OK keeps the run as one undo step. False for any other -/// command, which then runs as it was given. -pub fn open_command(app: &mut VectorcraftApp, id: &str) -> bool { +/// Opens the dialog of plug-in command `id` (`plugin..`), given no params +/// or only `ids` (a context menu's objects), when it has parameters and a document is open: its +/// fields at their defaults (`__command` is the command id, `__ids` the objects given) with a live +/// Preview, and OK keeps the run on those objects as one undo step. False for any other command or +/// params, which then run as they were given. +pub fn open_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { + let only_ids = p.as_object().is_none_or(|o| o.keys().all(|k| k == "ids")) && p.get("ids").is_none_or(Value::is_array); + if !only_ids { + return false; + } let Some((plugin, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return false }; if c.params.is_empty() || app.session.active().is_none() { return false; } let mut fields = fields_for(&plugin.manifest().for_command(&c)); fields.insert("__command".into(), json!(id)); + if let Some(ids) = p.get("ids") { + fields.insert("__ids".into(), ids.clone()); + } fields.insert("__label".into(), json!(c.shown_label())); fields.insert("preview".into(), json!(true)); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); @@ -309,11 +386,15 @@ fn command(d: &Dialog) -> String { } } -/// The params of the command dialog `d` runs ([`command`]). +/// The params of the command dialog `d` runs ([`command`]): a command opened from a context menu +/// runs on the objects it was opened for (`__ids`). fn params(d: &Dialog) -> Value { match d.str("__command").is_empty() { true => json!({"id": d.str("__plugin"), "params": form::params(d)}), - false => json!({"params": form::params(d)}), + false => match d.fields.get("__ids") { + Some(ids) => json!({"ids": ids, "params": form::params(d)}), + None => json!({"params": form::params(d)}), + }, } } diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 94332b3e72..7f5b941b26 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7692,6 +7692,9 @@ variable-list-end {0}, {1} {0} i {1} # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` ha de tenir 1-64 caràcters imprimibles @msg `{key}` must be 1-64 printable characters `{key}` ha de tenir 1-64 caràcters imprimibles +@msg `{key}` must be a list `{key}` ha de ser una llista +@msg `{key}` names "{name}" twice `{key}` esmenta "{name}" dues vegades +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: un complement pot posar com a màxim {MAX_CONTEXT_COMMANDS} ordres a cada menú contextual @msg `version`, `description` or `author` is too long `version`, `description` o `author` és massa llarg @msg `warnings` must be a list of strings `warnings` ha de ser una llista de cadenes @msg `{k}` must be one of {_1} `{k}` ha de ser un de {_1} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 27d1e9175a..a3dc77e93b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7303,6 +7303,9 @@ axis Y Axis osa Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` musí mít 1-64 tisknutelných znaků @msg `{key}` must be 1-64 printable characters `{key}` musí mít 1-64 tisknutelných znaků +@msg `{key}` must be a list `{key}` musí být seznam +@msg `{key}` names "{name}" twice `{key}` uvádí "{name}" dvakrát +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: zásuvný modul může do každé místní nabídky přidat nejvýše {MAX_CONTEXT_COMMANDS} příkazů @msg `version`, `description` or `author` is too long `version`, `description` nebo `author` je příliš dlouhé @msg `warnings` must be a list of strings `warnings` musí být seznam řetězců @msg `{k}` must be one of {_1} `{k}` musí být jedno z {_1} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8f7631cf9a..7e3eb12519 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -533,6 +533,9 @@ liquify-list-end {0}, {1} {0} og {1} @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants »{_1}« beder om et tungt budget (hver kørsel op til {minutes} minutter og {times} gange de sædvanlige instruktioner): en person skal godkende det i skrivebordsappen, eller send `allowHeavy: true` i en session startet med --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` skal være 1-64 tegn, der kan udskrives @msg `{key}` must be 1-64 printable characters `{key}` skal være 1-64 tegn, der kan udskrives +@msg `{key}` must be a list `{key}` skal være en liste +@msg `{key}` names "{name}" twice `{key}` nævner "{name}" to gange +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: et plug-in må højst sætte {MAX_CONTEXT_COMMANDS} kommandoer i hver genvejsmenu @msg `version`, `description` or `author` is too long `version`, `description` eller `author` er for lang @msg `warnings` must be a list of strings `warnings` skal være en liste med strenge @msg `{k}` must be one of {_1} `{k}` skal være en af {_1} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4ebb7c9220..f4c547779b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6886,6 +6886,9 @@ axis Y Axis Y-Achse # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` muss 1-64 druckbare Zeichen haben @msg `{key}` must be 1-64 printable characters `{key}` muss 1-64 druckbare Zeichen haben +@msg `{key}` must be a list `{key}` muss eine Liste sein +@msg `{key}` names "{name}" twice `{key}` nennt "{name}" doppelt +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: Ein Plug-in darf höchstens {MAX_CONTEXT_COMMANDS} Befehle in jedes Kontextmenü setzen @msg `version`, `description` or `author` is too long `version`, `description` oder `author` ist zu lang @msg `warnings` must be a list of strings `warnings` muss eine Liste von Zeichenketten sein @msg `{k}` must be one of {_1} `{k}` muss einer der folgenden Werte sein: {_1} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d75cd4c4fb..26baf18dc3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7292,6 +7292,9 @@ axis Y Axis Άξονας Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters το `name` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες @msg `{key}` must be 1-64 printable characters το `{key}` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες +@msg `{key}` must be a list το `{key}` πρέπει να είναι λίστα +@msg `{key}` names "{name}" twice το `{key}` αναφέρει το "{name}" δύο φορές +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: ένα πρόσθετο μπορεί να βάλει το πολύ {MAX_CONTEXT_COMMANDS} εντολές σε κάθε μενού περιβάλλοντος @msg `version`, `description` or `author` is too long το `version`, το `description` ή το `author` είναι πολύ μεγάλο @msg `warnings` must be a list of strings το `warnings` πρέπει να είναι λίστα συμβολοσειρών @msg `{k}` must be one of {_1} το `{k}` πρέπει να είναι ένα από τα {_1} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5a2b8f9857..86cf8aa3bd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7278,6 +7278,9 @@ axis Y Axis Eje Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` debe tener 1-64 caracteres imprimibles @msg `{key}` must be 1-64 printable characters `{key}` debe tener 1-64 caracteres imprimibles +@msg `{key}` must be a list `{key}` debe ser una lista +@msg `{key}` names "{name}" twice `{key}` nombra "{name}" dos veces +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: un plugin puede poner como máximo {MAX_CONTEXT_COMMANDS} comandos en cada menú contextual @msg `version`, `description` or `author` is too long `version`, `description` o `author` es demasiado largo @msg `warnings` must be a list of strings `warnings` debe ser una lista de cadenas @msg `{k}` must be one of {_1} `{k}` debe ser uno de estos: {_1} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 57f87528a4..ce19334c25 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7369,6 +7369,9 @@ axis Y Axis Y-akseli # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name`-kentässä on oltava 1-64 tulostettavaa merkkiä @msg `{key}` must be 1-64 printable characters `{key}`-kentässä on oltava 1-64 tulostettavaa merkkiä +@msg `{key}` must be a list `{key}` on oltava luettelo +@msg `{key}` names "{name}" twice `{key}` mainitsee "{name}" kahdesti +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: laajennus voi lisätä enintään {MAX_CONTEXT_COMMANDS} komentoa kuhunkin pikavalikkoon @msg `version`, `description` or `author` is too long `version`, `description` tai `author` on liian pitkä @msg `warnings` must be a list of strings `warnings` on oltava merkkijonojen luettelo @msg `{k}` must be one of {_1} `{k}` on oltava jokin seuraavista: {_1} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 56ea0bac94..3ee7afbe5d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7299,6 +7299,9 @@ axis Y Axis Axe Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` doit compter 1-64 caractères imprimables @msg `{key}` must be 1-64 printable characters `{key}` doit compter 1-64 caractères imprimables +@msg `{key}` must be a list `{key}` doit être une liste +@msg `{key}` names "{name}" twice `{key}` cite "{name}" deux fois +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu pour `{key}`, un module externe peut placer au plus {MAX_CONTEXT_COMMANDS} commandes dans chaque menu contextuel @msg `version`, `description` or `author` is too long `version`, `description` ou `author` est trop long @msg `warnings` must be a list of strings `warnings` doit être une liste de chaînes @msg `{k}` must be one of {_1} `{k}` doit valoir l’une de ces valeurs : {_1} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 54817a47c7..cf61af52bf 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7115,6 +7115,9 @@ arrowhead Feather पंख @msg `name` is empty `name` खाली है @msg `name` must be 1-64 printable characters `name` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए @msg `{key}` must be 1-64 printable characters `{key}` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए +@msg `{key}` must be a list `{key}` एक सूची होना चाहिए +@msg `{key}` names "{name}" twice `{key}` में "{name}" दो बार है +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: एक प्लग-इन हर संदर्भ मेनू में अधिकतम {MAX_CONTEXT_COMMANDS} कमांड रख सकता है @msg `names` is a list of preset names `names` प्रीसेट नामों की सूची है @msg `names` lists preset names `names` प्रीसेट नामों की सूची देता है @msg `names` must be a list of names `names` को नामों की सूची होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8b6374bd63..7b62a39be7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7288,6 +7288,9 @@ axis Y Axis Y tengely # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters a `name` 1-64 nyomtatható karakter legyen @msg `{key}` must be 1-64 printable characters a `{key}` 1-64 nyomtatható karakter legyen +@msg `{key}` must be a list a `{key}` lista legyen +@msg `{key}` names "{name}" twice a `{key}` kétszer nevezi meg ezt: "{name}" +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: egy bővítmény legfeljebb {MAX_CONTEXT_COMMANDS} parancsot tehet az egyes helyi menükbe @msg `version`, `description` or `author` is too long a `version`, a `description` vagy az `author` túl hosszú @msg `warnings` must be a list of strings a `warnings` karakterláncok listája legyen @msg `{k}` must be one of {_1} `{k}`: ezek egyike kell: {_1} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4ca1800dc3..0d03780e73 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -416,6 +416,9 @@ @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” meminta anggaran berat (setiap proses hingga {minutes} menit dan {times} kali instruksi biasa): seseorang harus menyetujuinya di aplikasi desktop, atau berikan `allowHeavy: true` dalam sesi yang dimulai dengan --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` harus berupa 1-64 karakter yang dapat dicetak @msg `{key}` must be 1-64 printable characters `{key}` harus berupa 1-64 karakter yang dapat dicetak +@msg `{key}` must be a list `{key}` harus berupa daftar +@msg `{key}` names "{name}" twice `{key}` menyebut "{name}" dua kali +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: plug-in dapat menaruh paling banyak {MAX_CONTEXT_COMMANDS} perintah di setiap menu konteks @msg `version`, `description` or `author` is too long `version`, `description` atau `author` terlalu panjang @msg `warnings` must be a list of strings `warnings` harus berupa daftar string @msg `{k}` must be one of {_1} `{k}` harus salah satu dari {_1} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 3a8c3a60d1..78eb3b3ddd 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6925,6 +6925,9 @@ axis Y Axis Asse Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` deve avere 1-64 caratteri stampabili @msg `{key}` must be 1-64 printable characters `{key}` deve avere 1-64 caratteri stampabili +@msg `{key}` must be a list `{key}` deve essere un elenco +@msg `{key}` names "{name}" twice `{key}` nomina "{name}" due volte +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: un plug-in può inserire al massimo {MAX_CONTEXT_COMMANDS} comandi in ogni menu contestuale @msg `version`, `description` or `author` is too long `version`, `description` o `author` è troppo lungo @msg `warnings` must be a list of strings `warnings` deve essere un elenco di stringhe @msg `{k}` must be one of {_1} `{k}` deve essere uno dei seguenti: {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f261704aae..5d2e850c20 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7000,6 +7000,9 @@ axis Y Axis Y 軸 # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` は印刷可能な 1-64 文字にしてください @msg `{key}` must be 1-64 printable characters `{key}` は印刷可能な 1-64 文字にしてください +@msg `{key}` must be a list `{key}` はリストにしてください +@msg `{key}` names "{name}" twice `{key}` で "{name}" が 2 回指定されています +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: プラグインが各コンテキストメニューに追加できるコマンドは最大 {MAX_CONTEXT_COMMANDS} 個です @msg `version`, `description` or `author` is too long `version`、`description` または `author` が長すぎます @msg `warnings` must be a list of strings `warnings` は文字列のリストにしてください @msg `{k}` must be one of {_1} `{k}` は {_1} のいずれかにしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index ef9708d8a0..5384d3a428 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9405,6 +9405,9 @@ axis Y Axis Y ღერძი # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან @msg `{key}` must be 1-64 printable characters `{key}` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან +@msg `{key}` must be a list `{key}` უნდა იყოს სია +@msg `{key}` names "{name}" twice `{key}` ორჯერ ასახელებს "{name}"-ს +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: პლაგინს თითოეულ კონტექსტურ მენიუში მაქსიმუმ {MAX_CONTEXT_COMMANDS} ბრძანების ჩასმა შეუძლია @msg `version`, `description` or `author` is too long `version`, `description` ან `author` ზედმეტად გრძელია @msg `warnings` must be a list of strings `warnings` უნდა იყოს სტრიქონების სია @msg `{k}` must be one of {_1} `{k}` უნდა იყოს ერთ-ერთი: {_1} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c28c2e1ca0..e7c8140520 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6897,6 +6897,9 @@ axis Y Axis Y축 # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name`은(는) 인쇄 가능한 문자 1-64자여야 합니다 @msg `{key}` must be 1-64 printable characters `{key}`은(는) 인쇄 가능한 문자 1-64자여야 합니다 +@msg `{key}` must be a list `{key}`은(는) 목록이어야 합니다 +@msg `{key}` names "{name}" twice `{key}`에 "{name}"이(가) 두 번 지정되었습니다 +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: 플러그인은 각 상황에 맞는 메뉴에 명령을 최대 {MAX_CONTEXT_COMMANDS}개까지 넣을 수 있습니다 @msg `version`, `description` or `author` is too long `version`, `description` 또는 `author`가 너무 깁니다 @msg `warnings` must be a list of strings `warnings`는 문자열 목록이어야 합니다 @msg `{k}` must be one of {_1} `{k}`은(는) {_1} 중 하나여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c612a8a9fd..3e0095a952 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -380,6 +380,9 @@ liquify-list-end {0}, {1} {0} en {1} @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” vraagt om een groot rekenbudget (elke uitvoering tot {minutes} minuten en {times} keer het gebruikelijke aantal instructies): een persoon moet dit goedkeuren in de desktop-app, of geef `allowHeavy: true` door in een sessie die is gestart met --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` moet uit 1-64 afdrukbare tekens bestaan @msg `{key}` must be 1-64 printable characters `{key}` moet uit 1-64 afdrukbare tekens bestaan +@msg `{key}` must be a list `{key}` moet een lijst zijn +@msg `{key}` names "{name}" twice `{key}` noemt "{name}" twee keer +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: een plug-in mag in elk contextmenu hoogstens {MAX_CONTEXT_COMMANDS} opdrachten plaatsen @msg `version`, `description` or `author` is too long `version`, `description` of `author` is te lang @msg `warnings` must be a list of strings `warnings` moet een lijst met strings zijn @msg `{k}` must be one of {_1} `{k}` moet een van {_1} zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index b5239d8a39..d5cf5faea0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7158,6 +7158,9 @@ axis Y Axis Oś Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` musi mieć 1-64 drukowalnych znaków @msg `{key}` must be 1-64 printable characters `{key}` musi mieć 1-64 drukowalnych znaków +@msg `{key}` must be a list `{key}` musi być listą +@msg `{key}` names "{name}" twice `{key}` wymienia "{name}" dwa razy +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: wtyczka może umieścić w każdym menu kontekstowym najwyżej {MAX_CONTEXT_COMMANDS} poleceń @msg `version`, `description` or `author` is too long `version`, `description` lub `author` jest za długie @msg `warnings` must be a list of strings `warnings` musi być listą ciągów znaków @msg `{k}` must be one of {_1} `{k}` musi mieć jedną z wartości: {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2bb3e74c81..33fbb68f55 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7202,6 +7202,9 @@ axis Y Axis Eixo Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` deve ter 1-64 caracteres imprimíveis @msg `{key}` must be 1-64 printable characters `{key}` deve ter 1-64 caracteres imprimíveis +@msg `{key}` must be a list `{key}` deve ser uma lista +@msg `{key}` names "{name}" twice `{key}` cita "{name}" duas vezes +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: um plug-in pode colocar no máximo {MAX_CONTEXT_COMMANDS} comandos em cada menu de contexto @msg `version`, `description` or `author` is too long `version`, `description` ou `author` é longo demais @msg `warnings` must be a list of strings `warnings` deve ser uma lista de strings @msg `{k}` must be one of {_1} `{k}` deve ser um de {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 4f1bff082f..09eac9e1fb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6924,6 +6924,9 @@ axis Y Axis Ось Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` должен содержать 1-64 печатаемых символа @msg `{key}` must be 1-64 printable characters `{key}` должен содержать 1-64 печатаемых символа +@msg `{key}` must be a list `{key}` должен быть списком +@msg `{key}` names "{name}" twice `{key}` называет "{name}" дважды +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: модуль может добавить в каждое контекстное меню не более {MAX_CONTEXT_COMMANDS} команд @msg `version`, `description` or `author` is too long `version`, `description` или `author` слишком длинное @msg `warnings` must be a list of strings `warnings` должно быть списком строк @msg `{k}` must be one of {_1} `{k}` должно быть одним из: {_1} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ed74b506a9..9e9f65cc92 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8934,6 +8934,9 @@ digits Hindi Hindi @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` måste vara "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" eller "lineEndHalf" @msg `name` must be 1-64 printable characters `name` måste vara 1-64 utskrivbara tecken @msg `{key}` must be 1-64 printable characters `{key}` måste vara 1-64 utskrivbara tecken +@msg `{key}` must be a list `{key}` måste vara en lista +@msg `{key}` names "{name}" twice `{key}` nämner "{name}" två gånger +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: ett plugin får placera högst {MAX_CONTEXT_COMMANDS} kommandon i varje snabbmeny @msg `names` is a list of preset names `names` är en lista med namn på förinställningar @msg `names` lists preset names `names` listar namn på förinställningar @msg `names` must be a list of names `names` måste vara en lista med namn diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 9009698065..53e9ff503a 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5427,7 +5427,7 @@ fn script_interpreter_core_errors_are_translated() { /// A manifest whose `commands` value, or a command's `menu`, has the wrong shape is refused with an error that every /// language of [`COMPLETE_MESSAGES`] translates whole, the command's name and the place in the -/// manifest included. +/// manifest included, and so is one that puts too many commands in a context menu. #[test] fn wrongly_shaped_plugin_commands_errors_are_translated() { let many: Vec = (0..=32).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect(); @@ -5458,18 +5458,34 @@ fn wrongly_shaped_plugin_commands_errors_are_translated() { "unknown", "printable", "characters", + "names", + "twice", + "most", ]; - // A `menu` of the wrong shape (read at API level 2). + // A `menu` of the wrong shape (read at API level 2), its `context` included. let menus = [ r#"{"path":["File"]}"#, r#"{"path":["Select"],"before":"Inverse"}"#, r#"{"path":["Select"],"after":3}"#, r#"{"path":["Select"],"after":" "}"#, r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, + r#"{"context":"canvas"}"#, + r#"{"context":[{"menu":"canvas","when":"layerRow"}]}"#, + r#"{"context":[{"menu":"canvas"},{"menu":"canvas"}]}"#, ]; - let manifests = commands.iter().map(|value| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":{value}}}"#)).chain( - menus.iter().map(|menu| format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{{"id":"x","label":"A","menu":{menu}}}]}}"#)), - ); + // More commands in one context menu than a plug-in may put there. + let crowded: Vec = (0..=vectorcraft_plugins::manifest::MAX_CONTEXT_COMMANDS) + .map(|i| format!(r#"{{"id":"c{i}","label":"C{i}","menu":{{"context":[{{"menu":"layers"}}]}}}}"#)) + .collect(); + let manifests = commands + .iter() + .map(|value| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":{value}}}"#)) + .chain( + menus + .iter() + .map(|menu| format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{{"id":"x","label":"A","menu":{menu}}}]}}"#)), + ) + .chain([format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{}]}}"#, crowded.join(","))]); for manifest in manifests { let e = vectorcraft_plugins::manifest::Manifest::parse(manifest.as_bytes()).unwrap_err().to_string(); let numbers: Vec<&str> = e.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6663b1385e..dd735857c0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7375,6 +7375,9 @@ axis Y Axis Y ekseni # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 1-64 yazdırılabilir karakter olmalıdır @msg `{key}` must be 1-64 printable characters `{key}` 1-64 yazdırılabilir karakter olmalıdır +@msg `{key}` must be a list `{key}` bir liste olmalıdır +@msg `{key}` names "{name}" twice `{key}`, "{name}" değerini iki kez belirtiyor +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: bir eklenti her bağlam menüsüne en fazla {MAX_CONTEXT_COMMANDS} komut koyabilir @msg `version`, `description` or `author` is too long `version`, `description` veya `author` çok uzun @msg `warnings` must be a list of strings `warnings` bir dize listesi olmalıdır @msg `{k}` must be one of {_1} `{k}` şunlardan biri olmalıdır: {_1} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2bf33a0d89..243501274e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6907,6 +6907,9 @@ axis Y Axis Вісь Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` має містити 1-64 друковані символи @msg `{key}` must be 1-64 printable characters `{key}` має містити 1-64 друковані символи +@msg `{key}` must be a list `{key}` має бути списком +@msg `{key}` names "{name}" twice `{key}` називає "{name}" двічі +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: модуль може додати до кожного контекстного меню щонайбільше {MAX_CONTEXT_COMMANDS} команд @msg `version`, `description` or `author` is too long `version`, `description` або `author` задовге @msg `warnings` must be a list of strings `warnings` має бути списком рядків @msg `{k}` must be one of {_1} `{k}` має бути одним з: {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 73c4984e17..19a7dab3eb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6953,6 +6953,9 @@ axis Y Axis Trục Y # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` phải có 1-64 ký tự in được @msg `{key}` must be 1-64 printable characters `{key}` phải có 1-64 ký tự in được +@msg `{key}` must be a list `{key}` phải là một danh sách +@msg `{key}` names "{name}" twice `{key}` nêu "{name}" hai lần +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`: một plug-in có thể đặt tối đa {MAX_CONTEXT_COMMANDS} lệnh vào mỗi menu ngữ cảnh @msg `version`, `description` or `author` is too long `version`, `description` hoặc `author` quá dài @msg `warnings` must be a list of strings `warnings` phải là một danh sách chuỗi @msg `{k}` must be one of {_1} `{k}` phải là một trong {_1} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2a0fbcd5a4..27ae630951 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7135,6 +7135,9 @@ axis Y Axis Y 轴 # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 必须是 1-64 个可打印字符 @msg `{key}` must be 1-64 printable characters `{key}` 必须是 1-64 个可打印字符 +@msg `{key}` must be a list `{key}` 必须是列表 +@msg `{key}` names "{name}" twice `{key}` 两次列出了 "{name}" +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`:每个增效工具在每个上下文菜单中最多可放入 {MAX_CONTEXT_COMMANDS} 个命令 @msg `version`, `description` or `author` is too long `version`、`description` 或 `author` 太长 @msg `warnings` must be a list of strings `warnings` 必须是字符串列表 @msg `{k}` must be one of {_1} `{k}` 必须是 {_1} 之一 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5a3d90d647..ca5f85f3b9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6956,6 +6956,9 @@ axis Y Axis Y 軸 # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 必須是 1-64 個可列印字元 @msg `{key}` must be 1-64 printable characters `{key}` 必須是 1-64 個可列印字元 +@msg `{key}` must be a list `{key}` 必須是清單 +@msg `{key}` names "{name}" twice `{key}` 列出了兩次 "{name}" +@msg `{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu `{key}`:每個增效模組在每個內容選單中最多可放入 {MAX_CONTEXT_COMMANDS} 個指令 @msg `version`, `description` or `author` is too long `version`、`description` 或 `author` 太長 @msg `warnings` must be a list of strings `warnings` 必須是字串清單 @msg `{k}` must be one of {_1} `{k}` 必須是 {_1} 其中之一 diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index d80b69038b..e2cc3acfee 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -4,7 +4,8 @@ use super::tree::{arrange_items, transform_items}; use super::{Item, Sep, Value, VectorcraftApp, c, cp, json, sub, widgets}; /// The canvas context menu (right-click): what applies to the selection, or to the view when -/// nothing is selected. Commands that can't run now are left out rather than greyed out. +/// nothing is selected. Commands that can't run now are left out rather than greyed out; a plug-in +/// command whose `when` fails for the selection is greyed out in the Plug-ins submenu. pub fn context_items(app: &VectorcraftApp) -> Vec { use vectorcraft_doc::NodeKind; let Some(st) = app.session.active() else { return vec![] }; @@ -127,6 +128,11 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { Sep, c("Export Selection…", "file.exportSelection"), ]); + // The commands plug-in manifests list here (`menu.context`), each run on the selection. + let ids: Vec = st.selection.objects.iter().map(|id| id.0).collect(); + if let Some(plugins) = crate::dialogs::plugin::canvas_submenu(&st.doc, &ids) { + v.extend([Sep, plugins]); + } } prune(app, v) } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 7186f0707d..a5023e26a8 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -193,8 +193,9 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { app.ui.dialog = Some(crate::state::Dialog::new(kind, fields)); return; } - // A plug-in command with parameters asks for them, from its menu item or its shortcut. - if p.as_object().is_none_or(|o| o.is_empty()) && crate::dialogs::plugin::open_command(app, id) { + // A plug-in command with parameters asks for them, from its menu item, its shortcut or a + // context menu (which gives only `ids`). + if crate::dialogs::plugin::open_command(app, id, &p) { return; } if open_view_dialog(app, id, &p) || open_object_dialog(app, id, &p) { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 5533352c18..b1541d14f9 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -172,7 +172,9 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool { /// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden /// ([`east_asian_hidden`]). pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option)> { - let en = enabled(app, id) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)); + let en = enabled(app, id) + && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)) + && (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p)); if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) { return None; } diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 93aa99e6da..771611eb3d 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -471,7 +471,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } bottom_bar(app, ui, &view, &doc, &mut out.actions); for (c, p) in out.actions { - app.run(&c, p).ok(); + // A plug-in command from a row's menu asks for its parameters first, as its menu item does. + if vectorcraft_engine::cmd::plugin::is_command_id(&c) { + crate::menus::invoke(app, &c, p); + } else { + app.run(&c, p).ok(); + } } // A deletion that took the last highlighted row leaves the panel nothing to delete. Release the // keys now, not at the next draw, so the very next frame's Delete reaches Edit › Clear. diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index c945537326..5f28a89092 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -696,9 +696,28 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out ui.separator(); // Collect for Export let ids: Vec = collect_ids.to_vec(); + let actions = &mut out.actions; collect_for_export_menu(ui, true, move |multiple| { - out.actions.push(("assets.add".into(), json!({ "ids": ids.clone(), "multiple": multiple }))); + actions.push(("assets.add".into(), json!({ "ids": ids.clone(), "multiple": multiple }))); }); + // The commands plug-in manifests list in this menu (`menu.context`): a submenu per plug-in, + // each item running its command on these rows' objects. + let plugins = crate::dialogs::plugin::context_commands(vectorcraft_plugins::ContextMenu::Layers, view.doc, collect_ids); + if !plugins.is_empty() { + ui.separator(); + ui.menu_button(tl!("Plug-ins"), |ui| { + for (name, commands) in &plugins { + ui.menu_button(*name, |ui| { + for c in commands { + if widgets::menu_item_name(ui, c.label, c.enabled, false) { + out.actions.push((c.command.into(), json!({ "ids": collect_ids }))); + ui.close(); + } + } + }); + } + }); + } } /// Context menu Others action for `ids`: Lock Others / Unlock All Layers or Hide Others / Show All Layers. diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index a8cf4ccb5e..1c092fbd2f 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -855,6 +855,104 @@ fn desktop_items_of_placeable_menus_are_known_to_the_engine() { assert!(missing.is_empty(), "missing from DESKTOP_MENU_ITEMS:\n{}", rows.join("\n")); } +/// A filter at API level 2 named Ctx whose commands are `commands` (a JSON list): each adds a +/// triangle when it is given an object named Target, and leaves its input as it is otherwise. +fn context_plugin(id: &str, commands: &str) -> String { + let manifest = format!(r#"{{"id":"{id}","name":"Ctx","api":2,"version":"1","kind":"filter","commands":{commands}}}"#); + let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#; + vectorcraft_format::base64_encode(&wat::parse_str(tpl::when_given(&manifest, tpl::Given::Input, r#""name":"Target""#, triangle)).unwrap()) +} + +/// The items of the canvas context menu's Plug-ins submenu: (plug-in, label, command, params). +fn canvas_plugin_items(app: &VectorcraftApp) -> Vec<(String, String, String, Value)> { + let items = menus::context_items(app); + let Some(menus::Item::Sub(_, plugins)) = items.iter().find(|it| matches!(it, menus::Item::Sub("Plug-ins", _))) else { return Vec::new() }; + let mut out = Vec::new(); + for p in plugins { + let menus::Item::Sub(name, commands) = p else { panic!("a plug-in's group is a submenu: {p:?}") }; + for c in commands { + let menus::Item::Cmd(label, id, params) = c else { panic!("a plug-in group holds commands only: {c:?}") }; + out.push((name.to_string(), label.to_string(), id.to_string(), params.clone())); + } + } + out +} + +/// A command whose manifest's `menu.context` names the canvas or the Layers panel is listed in that +/// context menu, in a Plug-ins submenu holding a submenu named after the plug-in; a command without +/// it is not. An item whose `when` fails is greyed out. Chosen, it runs its command on the +/// selection (canvas) or on the clicked rows (Layers panel, whatever the selection) as one undo +/// step named after the command; one with parameters opens its dialog first, and OK runs it on +/// those objects. Nothing is listed while nothing is selected, and nothing once the plug-in is +/// removed. +#[test] +fn plugin_commands_are_listed_in_the_canvas_and_layers_context_menus() { + use dialogs::plugin::{ContextCommand, context_commands}; + use vectorcraft_plugins::ContextMenu; + let mut app = app(); + let id = "test.ui.context"; + let command = |c: &str| vectorcraft_engine::cmd::plugin::command_id(id, c); + let commands = r#"[{"id":"tidy","label":"Tidy","menu":{"context":[{"menu":"canvas"},{"menu":"layers","when":"oneObject"}]}}, + {"id":"text","label":"Text Only","menu":{"context":[{"menu":"canvas","when":"typeObject"},{"menu":"layers","when":"layerRow"}]}}, + {"id":"size","label":"Size","menu":{"context":[{"menu":"layers"}]},"params":{"by":{"type":"number","min":0,"max":10,"default":2}}}, + {"id":"plain","label":"Plain"}]"#; + app.run("plugin.install", json!({"dataBase64": context_plugin(id, commands)})).unwrap(); + let target = red_rect(&mut app); + app.run("layer.setProps", json!({"ids": [target.0], "name": "Target"})).unwrap(); + let other = red_rect(&mut app); + let layer = app.session.doc().unwrap().doc.layers[0].id; + + app.run("select.none", json!({})).unwrap(); + assert!(canvas_plugin_items(&app).is_empty(), "nothing selected: no Plug-ins submenu"); + + app.run("select.set", json!({"ids": [target.0]})).unwrap(); + let ids = json!({"ids": [target.0]}); + let listed = canvas_plugin_items(&app); + let expected = [("Ctx", "Tidy", command("tidy")), ("Ctx", "Text Only", command("text"))]; + assert_eq!(listed.iter().map(|(p, l, c, _)| (p.as_str(), l.as_str(), c.clone())).collect::>(), expected); + assert!(listed.iter().all(|(.., p)| *p == ids), "{listed:?}"); + let shown = |app: &VectorcraftApp, c: &str| menus::shown_state(app, c, &ids).map(|(enabled, _)| enabled); + assert_eq!((shown(&app, &command("tidy")), shown(&app, &command("text"))), (Some(true), Some(false)), "no type object is selected"); + + let doc = app.session.doc().unwrap().doc.clone(); + let rows = |ids: &[u64]| context_commands(ContextMenu::Layers, &doc, ids); + let item = |label: &'static str, c: &str, enabled| ContextCommand { label, command: vectorcraft_plugins::registry::intern(&command(c)), enabled }; + assert_eq!(rows(&[target.0]), vec![("Ctx", vec![item("Tidy", "tidy", true), item("Text Only", "text", false), item("Size…", "size", true)])]); + assert_eq!(rows(&[layer.0])[0].1[..2], [item("Tidy", "tidy", false), item("Text Only", "text", true)], "a layer row"); + assert_eq!(rows(&[target.0, other.0])[0].1[0], item("Tidy", "tidy", false), "two rows are not one object"); + + // The canvas item runs on the selection as one undo step. + // The plug-in's output, a triangle in place of what it was given, replaces Target only when + // Target is what it was given. + let undo = app.session.doc().unwrap().history.undo.len(); + menus::invoke(&mut app, &command("tidy"), ids.clone()); + let st = app.session.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Tidy")); + assert!(st.doc.node(target).is_none() && st.doc.node(other).is_some(), "the plug-in was given Target alone"); + app.run("edit.undo", json!({})).unwrap(); + + // A row's item runs on that row's object, not on the selection; one with parameters asks first. + app.run("select.set", json!({"ids": [other.0]})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + menus::invoke(&mut app, &command("size"), ids.clone()); + let d = app.ui.dialog.as_ref().expect("Size opens its dialog"); + assert_eq!((d.str("__command"), d.fields.get("__ids")), (command("size"), Some(&json!([target.0])))); + frame(&mut app); + dialogs::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Size")); + assert!(st.doc.node(target).is_none() && st.doc.node(other).is_some(), "the plug-in was given the row's object, not the selection"); + + let list = app.run("plugin.list", json!({})).unwrap(); + let entry = list["plugins"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap().clone(); + assert_eq!(entry["commands"][0]["menu"], json!({"context": [{"menu": "canvas"}, {"menu": "layers", "when": "oneObject"}]})); + assert!(entry["commands"][3].get("menu").is_none(), "Plain lists no menu"); + + app.run("plugin.remove", json!({"id": id})).unwrap(); + assert!(canvas_plugin_items(&app).is_empty(), "removed: nothing listed"); + assert!(rows(&[other.0]).is_empty()); +} + /// A shortcut the user gives a plug-in command runs it. #[test] fn a_shortcut_runs_a_plugin_command() { diff --git a/docs/mcp.md b/docs/mcp.md index 914f26f211..c10452ef46 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13362,9 +13362,10 @@ changes nothing when a new `pluginsFolder` is missing, is not a folder or can't value or the folder the preference already holds, and the web build does not check folders. A filter or live effect may declare commands of its own ([plugins.md](plugins.md#commands)): each is the command `plugin..` while the plug-in is installed, listed by `command_list` and in its `plugin.list` entry -(`commands: [{id, command, label, params, paramsSchema, menu?}]`; `menu`, `{path, after?, placed?}`, is the menu its -manifest places it in, with `placed: false` when the command stays in its plug-in's submenu, see -[plugins.md](plugins.md#placing-a-command-in-another-menu)). Run it with `{ids?, params?}` (its parameters may also +(`commands: [{id, command, label, params, paramsSchema, menu?}]`; `menu`, `{path?, after?, placed?, context?}`, is the +menu its manifest places it in, with `placed: false` when the command stays in its plug-in's submenu, see +[plugins.md](plugins.md#placing-a-command-in-another-menu), and `context`, `[{menu, when?}]`, lists the context menus +that also list it, see [plugins.md](plugins.md#context-menus)). Run it with `{ids?, params?}` (its parameters may also be top-level keys): the parameters are checked before the plug-in runs, a run is one undo step named after the command, and a run that traps or runs out of its instruction budget returns an error that starts with the plug-in's name and the command's label and leaves the document and the undo history as they were. For `plugin.run` and plug-in diff --git a/docs/plugins.md b/docs/plugins.md index bd1a5b6073..fc4b5a7d1d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -89,7 +89,8 @@ replaced by a module without it. - **Menus.** A plug-in with commands is a submenu of **Object › Plug-ins** (a live effect: **Effect › Plug-ins**) named after the plug-in. The submenu holds the plug-in's own item, then its commands. A command with parameters has an ellipsis and opens a dialog for them, with a live preview, as a filter's own item does. A command whose manifest - gives a `menu` is listed in that menu instead ([below](#placing-a-command-in-another-menu)). + gives a `menu` is listed in that menu instead ([below](#placing-a-command-in-another-menu)), and one whose `menu` + gives a `context` is also listed in the canvas or Layers panel context menu ([Context menus](#context-menus)). - **Keyboard Shortcuts.** Edit › Keyboard Shortcuts lists each command under its menu, and the user can give it a shortcut. A manifest cannot give a command a shortcut. - **Actions and agents.** A command run is recorded in an action like any other command and plays back with its @@ -117,8 +118,9 @@ Inverse. `["Object", "Clipping Mask"]`, `["Type"]`, `["Select"]`, `["Select", "Same"]`, `["Select", "Object"]`, `["Effect"]` and `["View"]`. The File, Window and Help menus, the application menu, Edit › Preferences and the submenus that list files, fonts, panels or plug-ins cannot be named. Any other `path`, a `menu` that is not an object or is given twice, - a key other than `path` and `after`, and an `after` that is not 1–64 printable characters are refused when the - module is installed, and the error names the command. + a key other than `path`, `after` and `context`, and an `after` that is not 1–64 printable characters are refused when + the module is installed, and the error names the command. `path` may be left out only when `context` is given + ([Context menus](#context-menus)), and `after` needs `path`. - `after` is the English label of a built-in item or submenu of that menu, with or without its closing ellipsis (`"Inverse"`). The command is listed right after it. An item that switches between two labels is matched by either of them (`"Show Edges"` and `"Hide Edges"`, `"Start Global Edit"` and `"Stop Global Edit"`). Without `after`, or when no @@ -140,6 +142,34 @@ Inverse. the plug-in off (`plugin.setEnabled`) removes it at the next launch. - At `api` 1 a `menu` key, repeated or not, is ignored and the command stays in the plug-in's submenu. +#### Context menus + +At `api` 2 a command's `menu` may also list it in the canvas context menu and in the menu of a Layers panel row, with +`context`: a list of `{"menu": "canvas" | "layers", "when"?: condition}`. For example, +`"menu": {"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers"}]}`. The command stays where `path` +puts it (or in its plug-in's submenu) as well. + +- The canvas context menu lists the command while objects are selected, after Export Selection…, in a **Plug-ins** + submenu that holds a submenu named after each plug-in, in plug-in id order. Its items are the commands in manifest + order, under their own labels, with an ellipsis for a command with parameters. A row's menu in the Layers panel lists + the same way after Collect for Export. Guide rows and blend spine rows list no plug-in commands. With no command + listed there, the menu has no Plug-ins submenu. +- `when` is one of `"selection"` (one or more objects are selected, or rows clicked), `"oneObject"` (exactly one + object that is not a layer), `"typeObject"` (one of them is a type object) and `"layerRow"` (every clicked row is a + layer or sublayer; Layers panel only). Without `when` the item can always be chosen. While its condition fails, the + item is shown dimmed. +- Choosing the item runs `plugin..` as its other menu items do, with the same permissions, and one run is + one undo step. On the canvas it runs on the selection. In the Layers panel it runs on the clicked row, or on every + highlighted row when the clicked row is one of them, whatever is selected on the canvas; a layer or group row gives + the run the objects in it. Both pass the objects as `ids`, so an action records them. A command with parameters + opens its dialog first, and its preview and OK run on those objects. Nothing runs until an item is chosen. +- Each menu may be listed once in a command's `context`. A `context` that is not a list, an entry that is not an + object or has a key other than `menu` and `when`, an unknown `menu` or `when`, `"layerRow"` for the canvas and a + menu named twice are refused when the module is installed. A plug-in may list at most 8 commands in each context + menu; the module is refused otherwise. Each error names the command and the key. +- `plugin.list` gives the command's `menu` with its `context`. +- At `api` 1 the key is ignored, as the rest of `menu` is. + **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a @@ -604,7 +634,8 @@ the module's start function, in a run that isn't a filter's run on a document, o ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}, "menu"?: {…}}`. An `id` is 1–32 characters from `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` - are. `menu` (`api` 2 and later; ignored at `api` 1) places the command in [another menu](#placing-a-command-in-another-menu). + are. `menu` (`api` 2 and later; ignored at `api` 1) places the command in [another menu](#placing-a-command-in-another-menu) + and lists it in [context menus](#context-menus). A malformed entry is refused when the module is installed, and the error names the command by its id (or its place, `[0]`). - `commandAllowlist` (filters at `api` 2 with the usual budget, and only with the `commands` permission, which needs diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4179c3b5f4..322761c67b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2674,6 +2674,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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. - **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) unless its manifest places it in another menu, 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. - **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands at one spot keep plug-in id order and then manifest order; a filter whose commands are all placed elsewhere is a single item in Object › Plug-ins, and such a live effect is a single item in Effect › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `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. +- **Plug-in commands in context menus (G17):** at plug-in API level 2 a command's `menu.context` (`[{menu: "canvas" | "layers", when?}]`) also lists it in the canvas context menu while objects are selected and in the menu of a Layers panel layer, group or object row, in a Plug-ins submenu holding a submenu named after each plug-in. `when` is `selection`, `oneObject`, `typeObject` or `layerRow` (Layers panel only), and the item is dimmed while it fails. The item runs the command as one undo step on the selection, or on the clicked or highlighted rows whatever the selection, passing them as `ids`; a command with parameters opens its dialog for those objects first. A plug-in may list at most 8 commands in each context menu; any other `context` is refused by command and key when the module is installed. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`, `crates/ui-egui/src/i18n/tests.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. - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. From 6c37e6a071d745e996fbbd56d0190a8e3c2ae5ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:15:43 -0800 Subject: [PATCH 03/20] Plug-ins: plugin.info's manifest gives a command's context menus A command's `menu` in the manifest that `plugin.info` gives now carries its `context` list next to `path` and `after`, and is present for a command listed only in context menus, as `plugin.list` already reports it. --- crates/engine/src/tests/plugins.rs | 21 ++++++++++++++++ crates/plugins/src/manifest.rs | 40 ++++++++++++++++++++++++++++-- docs/plugins.md | 2 +- 3 files changed, 60 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index f2d84f00c9..b2e546b3ce 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4647,6 +4647,27 @@ fn placed_plugin_commands_are_listed_in_their_menu() { assert!(listed(&s, &low(bee)).is_none()); } +/// `plugin.info`'s `manifest` gives each command's context menus in its `menu`, for a command +/// placed in another menu and for one listed only in context menus. +#[test] +fn plugin_info_gives_a_command_s_context_menus() { + let mut s = session(); + let id = "test.engine.place.context"; + let commands = json!([ + {"id": "low", "label": "Low", "menu": {"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}}, + {"id": "tidy", "label": "Tidy", "menu": {"context": [{"menu": "layers", "when": "layerRow"}]}}, + {"id": "keep", "label": "Keep"} + ]); + let manifest = format!(r#"{{"id":"{id}","name":"Ctx","api":2,"version":"1","kind":"filter","commands":{commands}}}"#); + install_wat(&mut s, &tpl::returning(&manifest, r#"{"objects":[]}"#)); + let info = run(&mut s, "plugin.info", json!({"id": id})); + let shown = &info["manifest"]["commands"]; + assert_eq!(shown[0]["menu"], json!({"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}), "{info}"); + assert_eq!(shown[1]["menu"], json!({"context": [{"menu": "layers", "when": "layerRow"}]}), "{info}"); + assert!(shown[2].get("menu").is_none(), "{info}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A command run is journaled like any other, so an action records it with its parameters and /// plays it back. #[test] diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 600df2da34..38f1273c28 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -411,7 +411,7 @@ pub struct Param { /// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it /// as the command `plugin..`, and calls the plug-in's `vc_run` with /// `_context.command` set to `id` and the parameters it declares. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Deserialize)] pub struct Command { /// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest. pub id: String, @@ -423,7 +423,7 @@ pub struct Command { pub params: Vec<(String, Param)>, /// The menu it is listed in instead of the plug-in's submenu (`menu`, read at /// [`crate::permissions::MENU_API`] and later). - #[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")] + #[serde(skip)] pub place: Option, /// The context menus that also list it (`menu.context`, read at /// [`crate::permissions::MENU_API`] and later), at most one entry per menu. @@ -434,6 +434,34 @@ pub struct Command { pub(crate) declared_menu: Vec, } +/// A command as its manifest gives it: `id`, `label`, `params` and, when it has a place or context +/// menus, `menu` with its `path`, `after` and `context`. +impl Serialize for Command { + fn serialize(&self, s: S) -> std::result::Result { + fn params(p: &&[(String, Param)], s: S) -> std::result::Result { + params_as_object(p, s) + } + #[derive(Serialize)] + struct Menu<'a> { + #[serde(flatten)] + place: Option<&'a MenuPlace>, + #[serde(skip_serializing_if = "<[_]>::is_empty")] + context: &'a [ContextPlace], + } + #[derive(Serialize)] + struct Shown<'a> { + id: &'a str, + label: &'a str, + #[serde(serialize_with = "params")] + params: &'a [(String, Param)], + #[serde(skip_serializing_if = "Option::is_none")] + menu: Option>, + } + let menu = (self.place.is_some() || !self.context.is_empty()).then_some(Menu { place: self.place.as_ref(), context: &self.context }); + Shown { id: &self.id, label: &self.label, params: &self.params, menu }.serialize(s) + } +} + impl Command { /// The label as menus and errors show it: control and bidirectional characters escaped, at /// most [`crate::permissions::MAX_SHOWN_NAME`] characters. @@ -1635,6 +1663,14 @@ mod tests { let both = Manifest::parse(with(2, r#"{"path":["Select"],"context":[{"menu":"layers","when":"layerRow"}]}"#).as_bytes()).unwrap(); assert_eq!(both.commands[0].place, Some(MenuPlace { path: &["Select"], after: None })); assert_eq!(both.commands[0].context, vec![ContextPlace { menu: ContextMenu::Layers, when: Some(ContextWhen::LayerRow) }]); + // The manifest a plug-in's info gives carries the context menus, with or without a place. + assert_eq!( + serde_json::to_value(&both.commands[0]).unwrap()["menu"], + json!({"path": ["Select"], "context": [{"menu": "layers", "when": "layerRow"}]}) + ); + assert_eq!(serde_json::to_value(c).unwrap()["menu"], json!({"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers"}]})); + let plain = Manifest::parse(with(2, r#"{"context":[]}"#).as_bytes()).unwrap(); + assert!(serde_json::to_value(&plain.commands[0]).unwrap().get("menu").is_none(), "no place and no context menu: no `menu`"); assert!(Manifest::parse(with(2, r#"{"context":[]}"#).as_bytes()).unwrap().commands[0].context.is_empty()); assert!(Manifest::parse(with(1, r#"{"context":[{"menu":"sky"}]}"#).as_bytes()).unwrap().commands[0].context.is_empty(), "ignored at level 1"); diff --git a/docs/plugins.md b/docs/plugins.md index fc4b5a7d1d..be7bfe58e6 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -167,7 +167,7 @@ puts it (or in its plug-in's submenu) as well. object or has a key other than `menu` and `when`, an unknown `menu` or `when`, `"layerRow"` for the canvas and a menu named twice are refused when the module is installed. A plug-in may list at most 8 commands in each context menu; the module is refused otherwise. Each error names the command and the key. -- `plugin.list` gives the command's `menu` with its `context`. +- `plugin.list` gives the command's `menu` with its `context`, and so does the `manifest` that `plugin.info` gives. - At `api` 1 the key is ignored, as the rest of `menu` is. **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every From abc0872cd0e209aa3b3dc74dab71bff362eff595 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:17:31 -0800 Subject: [PATCH 04/20] Plug-ins: a canvas context-menu command with parameters opens its own dialog Choosing a plug-in command that has parameters from the canvas context menu opened the generic parameter dialog, because its item carries the selection's ids and its label ends with an ellipsis. Menu clicks on a plug-in command now run the command, which opens the plug-in's dialog for those objects. --- crates/ui-egui/src/menus/invoke.rs | 3 ++- crates/ui-egui/src/tests/plugins.rs | 12 ++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index a5023e26a8..3b735e7fc7 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -4,10 +4,11 @@ use super::{Value, VectorcraftApp, json}; /// What a menu click runs: items whose label ends with "…" and that carry default params open a /// generic parameter dialog (fields = the defaults) instead of running immediately. A script of the /// Scripts folder runs, whatever its name ends with, and so does a proof setup saved in the Proof -/// Setups folder. +/// Setups folder. A plug-in command's item runs its command, which opens the plug-in's own dialog. pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { let dialog = label.ends_with('…') && p.as_object().is_some_and(|o| !o.is_empty()) + && !vectorcraft_engine::cmd::plugin::is_command_id(id) && !matches!( id, "effect.dialog" diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 1c092fbd2f..4bcbd0be2b 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -894,7 +894,7 @@ fn plugin_commands_are_listed_in_the_canvas_and_layers_context_menus() { let command = |c: &str| vectorcraft_engine::cmd::plugin::command_id(id, c); let commands = r#"[{"id":"tidy","label":"Tidy","menu":{"context":[{"menu":"canvas"},{"menu":"layers","when":"oneObject"}]}}, {"id":"text","label":"Text Only","menu":{"context":[{"menu":"canvas","when":"typeObject"},{"menu":"layers","when":"layerRow"}]}}, - {"id":"size","label":"Size","menu":{"context":[{"menu":"layers"}]},"params":{"by":{"type":"number","min":0,"max":10,"default":2}}}, + {"id":"size","label":"Size","menu":{"context":[{"menu":"canvas"},{"menu":"layers"}]},"params":{"by":{"type":"number","min":0,"max":10,"default":2}}}, {"id":"plain","label":"Plain"}]"#; app.run("plugin.install", json!({"dataBase64": context_plugin(id, commands)})).unwrap(); let target = red_rect(&mut app); @@ -908,7 +908,7 @@ fn plugin_commands_are_listed_in_the_canvas_and_layers_context_menus() { app.run("select.set", json!({"ids": [target.0]})).unwrap(); let ids = json!({"ids": [target.0]}); let listed = canvas_plugin_items(&app); - let expected = [("Ctx", "Tidy", command("tidy")), ("Ctx", "Text Only", command("text"))]; + let expected = [("Ctx", "Tidy", command("tidy")), ("Ctx", "Text Only", command("text")), ("Ctx", "Size…", command("size"))]; assert_eq!(listed.iter().map(|(p, l, c, _)| (p.as_str(), l.as_str(), c.clone())).collect::>(), expected); assert!(listed.iter().all(|(.., p)| *p == ids), "{listed:?}"); let shown = |app: &VectorcraftApp, c: &str| menus::shown_state(app, c, &ids).map(|(enabled, _)| enabled); @@ -931,6 +931,14 @@ fn plugin_commands_are_listed_in_the_canvas_and_layers_context_menus() { assert!(st.doc.node(target).is_none() && st.doc.node(other).is_some(), "the plug-in was given Target alone"); app.run("edit.undo", json!({})).unwrap(); + // Clicking the canvas item of a command with parameters opens the plug-in's own dialog for the + // selection, not the generic parameter dialog. + let (_, label, c, p) = listed.iter().find(|(_, l, ..)| l == "Size…").unwrap(); + let (cmd, p) = menus::click_target(label, c, p); + menus::invoke(&mut app, &cmd, p); + let d = app.ui.dialog.take().expect("Size opens its dialog from the canvas"); + assert_eq!((d.kind.as_str(), d.str("__command"), d.fields.get("__ids")), (dialogs::plugin::KIND, command("size"), Some(&json!([target.0])))); + // A row's item runs on that row's object, not on the selection; one with parameters asks first. app.run("select.set", json!({"ids": [other.0]})).unwrap(); let undo = app.session.doc().unwrap().history.undo.len(); From d14d2137c5aa91fd82a00da83d4d7e475f609580 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:54:57 -0800 Subject: [PATCH 05/20] Plug-ins: a command dialog runs only on the document it opened on A plug-in command's dialog now records the uid of the document it opened on (`__doc`). Object ids come from a per-document counter, so the ids in `__ids` can name a different object in another document. Once another document is the active one, the dialog closes when it is next drawn, and OK closes it without running the command. Closing it that way leaves the active document's interaction in progress. --- crates/ui-egui/src/dialogs.rs | 5 ++- crates/ui-egui/src/dialogs/plugin.rs | 32 ++++++++++++----- crates/ui-egui/src/tests/plugins.rs | 53 ++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..461b9b5e86 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -826,7 +826,10 @@ pub fn cancel(app: &mut VectorcraftApp) { // that was already active before opening them. The generic parameter dialog has a spec // without a preview, yet previews some commands (Grid Repeat Options) when asked to. let owns_preview = d.kind != flare_options::KIND || d.fields.contains_key(form::PREVIEWED); - if (spec(&d.kind).preview && owns_preview) || d.fields.contains_key(form::PREVIEWED) { + // A plug-in command's dialog previews on the document it opened on, so closing it while + // another document is active leaves that document's interaction alone. + let elsewhere = d.kind == plugin::KIND && !plugin::on_its_document(app, &d); + if !elsewhere && ((spec(&d.kind).preview && owns_preview) || d.fields.contains_key(form::PREVIEWED)) { let _ = app.session.cancel_interaction(); } app.ui.dialog = parent(&d); diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index d41036d131..2dd4a29bf5 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -346,22 +346,24 @@ fn described(ui: &mut egui::Ui, d: &Dialog) -> Option> { Some(plugin) } +/// The field of a plug-in command's dialog holding the uid of the document it opened on. +const DOC: &str = "__doc"; + /// Opens the dialog of plug-in command `id` (`plugin..`), given no params /// or only `ids` (a context menu's objects), when it has parameters and a document is open: its -/// fields at their defaults (`__command` is the command id, `__ids` the objects given) with a live -/// Preview, and OK keeps the run on those objects as one undo step. False for any other command or -/// params, which then run as they were given. +/// fields at their defaults (`__command` is the command id, `__ids` the objects given, `__doc` the +/// uid of the active document) with a live Preview, and OK keeps the run on those objects as one +/// undo step. False for any other command or params, which then run as they were given. pub fn open_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { let only_ids = p.as_object().is_none_or(|o| o.keys().all(|k| k == "ids")) && p.get("ids").is_none_or(Value::is_array); if !only_ids { return false; } let Some((plugin, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return false }; - if c.params.is_empty() || app.session.active().is_none() { - return false; - } + let Some(doc) = app.session.active().map(|st| st.uid).filter(|_| !c.params.is_empty()) else { return false }; let mut fields = fields_for(&plugin.manifest().for_command(&c)); fields.insert("__command".into(), json!(id)); + fields.insert(DOC.into(), json!(doc)); if let Some(ids) = p.get("ids") { fields.insert("__ids".into(), ids.clone()); } @@ -378,6 +380,12 @@ fn command_of(d: &Dialog) -> Option { Some(plugin.manifest().for_command(&c)) } +/// Whether dialog `d` may run on the active document: a plug-in command's dialog runs only on the +/// document it opened on, and a filter's dialog runs on any document. +pub(super) fn on_its_document(app: &VectorcraftApp, d: &Dialog) -> bool { + d.str("__command").is_empty() || app.session.active().is_some_and(|st| d.fields.get(DOC).and_then(Value::as_u64) == Some(st.uid)) +} + /// The command dialog `d` runs: its plug-in command, or `plugin.run`. fn command(d: &Dialog) -> String { match d.str("__command") { @@ -416,11 +424,12 @@ fn run(app: &mut VectorcraftApp, plugin: &Plugin, p: Value) -> Result bool { let Some(plugin) = described(ui, d) else { return true }; let run_with = command_of(d); - if run_with.is_none() && !d.str("__command").is_empty() { + if (run_with.is_none() && !d.str("__command").is_empty()) || !on_its_document(app, d) { return true; } form::schema_fields(app, ui, d, run_with.as_ref().unwrap_or(plugin.manifest())); @@ -442,8 +451,13 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// OK: a filter keeps its previewed run as one undo step; a heavy one, which has no preview, and a /// light one that runs in the background ([`in_background`]) with Preview off or a failed preview, /// start in the background ([`run`]) and the dialog closes. A preview still shown when Preview was -/// just turned off, or a preview that failed, is rolled back first. +/// just turned off, or a preview that failed, is rolled back first. Once another document is +/// the active one, a command dialog closes and changes no document. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if !on_its_document(app, d) { + app.ui.dialog = None; + return Ok(json!({})); + } let own_run = d.str("__command").is_empty(); let kept = |plugin: &Plugin| { plugin.manifest().budget == Budget::Light && d.bool("preview") && app.session.in_interaction() && !d.fields.contains_key(form::REFUSED) diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 4bcbd0be2b..4cb2ef5e37 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -961,6 +961,59 @@ fn plugin_commands_are_listed_in_the_canvas_and_layers_context_menus() { assert!(rows(&[other.0]).is_empty()); } +/// A command dialog opened for objects of one document changes no document once another document +/// is the active one, even one holding an object with the same id: drawn, the dialog closes and +/// leaves that document's edit in progress, and OK closes it. On its own document, OK runs the +/// command on those objects. +#[test] +fn a_plugin_command_dialog_stays_with_its_document() { + let mut app = app(); + let id = "test.ui.context.doc"; + let size = vectorcraft_engine::cmd::plugin::command_id(id, "size"); + let commands = r#"[{"id":"size","label":"Size","params":{"by":{"type":"number","min":0,"max":10,"default":2}}}]"#; + app.run("plugin.install", json!({"dataBase64": context_plugin(id, commands)})).unwrap(); + let target = red_rect(&mut app); + app.run("layer.setProps", json!({"ids": [target.0], "name": "Target"})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let twin = red_rect(&mut app); + app.run("layer.setProps", json!({"ids": [twin.0], "name": "Target"})).unwrap(); + assert_eq!(twin, target, "the second document's object has the first one's id"); + let ids = json!({"ids": [target.0]}); + let undos = |app: &VectorcraftApp| app.session.documents().iter().map(|st| st.history.undo.len()).collect::>(); + let kept = |app: &VectorcraftApp| app.session.documents().iter().map(|st| st.doc.node(target).is_some()).collect::>(); + + // Drawn while the other document is active, the dialog closes. + app.run("document.activate", json!({"index": 0})).unwrap(); + menus::invoke(&mut app, &size, ids.clone()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("__command")), Some(size.clone())); + let before = undos(&app); + frame(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.begin_interaction("Edit").unwrap(); + frame(&mut app); + assert!(app.ui.dialog.is_none(), "the dialog closes on another document"); + assert!(app.session.in_interaction(), "closing it leaves the other document's edit in progress"); + app.session.cancel_interaction().unwrap(); + assert_eq!((undos(&app), kept(&app)), (before.clone(), vec![true, true])); + + // OK while the other document is active closes the dialog and changes neither document. + app.run("document.activate", json!({"index": 0})).unwrap(); + menus::invoke(&mut app, &size, ids.clone()); + frame(&mut app); + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_eq!(dialogs::confirm(&mut app).unwrap(), json!({})); + assert!(app.ui.dialog.is_none()); + assert_eq!((undos(&app), kept(&app)), (before.clone(), vec![true, true])); + + // On its own document, OK runs the command on the objects it opened for. + app.run("document.activate", json!({"index": 0})).unwrap(); + menus::invoke(&mut app, &size, ids); + frame(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert_eq!((undos(&app), kept(&app)), (vec![before[0] + 1, before[1]], vec![false, true])); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + /// A shortcut the user gives a plug-in command runs it. #[test] fn a_shortcut_runs_a_plugin_command() { From bf3eeaccc00f1d8c9dec45d67f5c03d05607ace5 Mon Sep 17 00:00:00 2001 From: ViktorBystrov72 <18964918+ViktorBystrov72@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:53:09 +0500 Subject: [PATCH 06/20] Render: cover the effects on rotated radial repeat copies --- crates/render/src/fx/bounds.rs | 25 ++++++++++++++++--------- crates/render/src/tests/changed.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 2a554a3d92..0883efb68f 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -730,7 +730,13 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b NodeKind::Blend { .. } => { let b = n.reach_bounds_with(symbols)?; let a = live_content_reach(symbols, n); - vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n)) + vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_live_effect_bounds(symbols, n)) + } + // A radial repeat rotates each copy before applying the source's geometry effects. + NodeKind::Repeat(_) => { + let b = n.visual_bounds_with(symbols)?; + let a = live_content_reach(symbols, n); + vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_live_effect_bounds(symbols, n)) } _ => { let b = n.visual_bounds_with(symbols)?; @@ -815,7 +821,7 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> /// (Revolve builds no art from type). fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { let b = match &n.kind { - NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)), + NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_live_effect_bounds(symbols, n)), _ => n.visual_bounds_with(symbols), }?; Some(match &n.kind { @@ -824,13 +830,14 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { }) } -/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects -/// run on the placed shapes, so their reach on the original keys need not cover what they paint. -/// Effect-free blends keep the quick rail envelope without evaluating their steps. -fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { - let NodeKind::Blend { spec, .. } = &n.kind else { return None }; - if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath { - return None; +/// A radial repeat's copies or a spine-aligned blend's steps, measured after rotation. Geometry +/// effects run on the placed shapes, so their reach on the source need not cover what they paint. +/// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps. +fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + match &n.kind { + NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {} + NodeKind::Repeat(r) if matches!(r.kind, vectorcraft_doc::RepeatKind::Radial { .. }) => {} + _ => return None, } let mut has_effects = false; n.walk(&mut |c| { diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 07251df938..756dd18e5c 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -135,6 +135,34 @@ fn moving_a_shadowed_object_changes_where_its_shadow_falls() { assert!(a.x1 > 86.0 && a.y1 > 70.0, "the shadow, before and after: {a:?}"); } +#[test] +fn moving_a_radial_repeat_redraws_the_effects_on_its_rotated_copies() { + for effected in [false, true] { + let mut old = Document::new(110.0, 80.0); + let source_id = old.alloc_id(); + let mut source = Node::path( + source_id, + shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + if effected { + source.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}), + visible: true, + }); + } + let repeat = vectorcraft_doc::RepeatSpec::radial(vec![Arc::new(source)], 4, Some(12.0)); + let id = old.alloc_id(); + old.insert(Some(old.layers[0].id), 0, Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat))).unwrap(); + let mut moved = old.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false); + // A partial redraw must reproduce the whole frame, both on the move and on Undo. + area(redraw(&old, &moved)); + area(redraw(&moved, &old)); + } +} + #[test] fn adding_removing_and_restacking_change_those_objects() { let (old, [loose, _, _, _, other]) = document(); From e8dddd17d597790148783a8b747c13e47edaae11 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:49:29 -0800 Subject: [PATCH 07/20] Plug-ins: open_filter takes a command's objects and document with the command Main added a `values` argument to `open_filter`, which made it take eight arguments and fail clippy's `too_many_arguments`. A command's id, its context-menu objects and its document now go in one `CommandRun`. --- crates/ui-egui/src/dialogs/plugin.rs | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 00317a47db..ce4878e782 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -643,7 +643,7 @@ pub fn open_last(app: &mut VectorcraftApp) -> Result { return run(app, &plugin, json!({"id": plugin.id(), "params": params})); } let m = plugin.manifest(); - open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), params, None, None)?; + open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), params)?; Ok(Value::Null) } @@ -665,23 +665,25 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { return run(app, &plugin, json!({"id": id, "params": given.cloned().unwrap_or(Value::Null)})); } let values = remembered(app, id).map(|(_, params)| params).unwrap_or_else(|| m.defaults()); - open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), values, None, None)?; + open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), values)?; Ok(Value::Null) } /// Opens the dialog of filter `plugin`, or of its command `command`, with `m` the manifest it runs /// with, headed `heading`: the rows at `values`, with a live Preview for a light filter. A -/// command's dialog runs on objects `ids` when given, and only on document `doc`. +/// command's dialog runs on its objects when given, and only on its document ([`CommandRun`]). fn open_filter( app: &mut VectorcraftApp, plugin: &Plugin, m: Manifest, - command: Option, + command: Option, heading: String, values: Map, - ids: Option, - doc: Option, ) -> Result<(), String> { + let (command, ids, doc) = match command { + Some(c) => (Some(c.id), c.ids, Some(c.doc)), + None => (None, None, None), + }; let own = plugin.manifest(); let light = own.budget == Budget::Light; let look = Look { title: heading.clone(), description: own.description.clone(), previews: light, note: !light, ok: None }; @@ -703,6 +705,14 @@ fn open_filter( Ok(()) } +/// The plug-in command a filter dialog runs: its id, the objects a context menu gave it, and the +/// uid of the document the dialog opened on, the only one it runs on. +struct CommandRun { + id: String, + ids: Option, + doc: u64, +} + /// Opens the dialog of plug-in command `id` (`plugin..`), given no params /// or only `ids` (a context menu's objects), when it has parameters and a document is open: its /// rows at their defaults with a live Preview, and OK keeps the run on those objects as one undo @@ -718,7 +728,8 @@ pub fn open_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { let ids = p.get("ids").cloned(); let m = plugin.manifest().for_command(&c); let defaults = m.defaults(); - if let Err(e) = open_filter(app, &plugin, m, Some(id.to_string()), c.shown_label().to_string(), defaults, ids, Some(doc)) { + let run = CommandRun { id: id.to_string(), ids, doc }; + if let Err(e) = open_filter(app, &plugin, m, Some(run), c.shown_label().to_string(), defaults) { app.status(e); } true From 7a5fa63be0a998e912542d08b2d6cf4db5f546f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:26:16 -0800 Subject: [PATCH 08/20] Plug-ins: a command's dialog opens only for no params or `ids` alone A plug-in command with parameters, invoked with a number, a string, a list or a non-list `ids`, opened its dialog at the defaults and dropped what it was given. Such params now go to the command as they were given. --- crates/ui-egui/src/dialogs/plugin.rs | 2 +- crates/ui-egui/src/tests/plugins.rs | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index ce4878e782..83ab829440 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -719,7 +719,7 @@ struct CommandRun { /// step. The dialog runs only on the document that was active when it opened. False for any other /// command or params, which then run as they were given. pub fn open_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool { - let only_ids = p.as_object().is_none_or(|o| o.keys().all(|k| k == "ids")) && p.get("ids").is_none_or(Value::is_array); + let only_ids = (p.is_null() || p.as_object().is_some_and(|o| o.keys().all(|k| k == "ids"))) && p.get("ids").is_none_or(Value::is_array); if !only_ids { return false; } diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 6275d3cf58..e4bb835de2 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -872,6 +872,27 @@ fn a_plugin_command_dialog_stays_with_its_document() { h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); } +/// A command with parameters given params that are neither nothing nor an object of `ids` alone +/// opens no dialog: they go to the command as they were given, and it changes nothing. +#[test] +fn a_plugin_command_given_other_params_opens_no_dialog() { + let mut h = window(app()); + let id = "test.ui.context.params"; + let size = vectorcraft_engine::cmd::plugin::command_id(id, "size"); + let commands = r#"[{"id":"size","label":"Size","params":{"by":{"type":"number","min":0,"max":10,"default":2}}}]"#; + let app = h.state_mut(); + app.run("plugin.install", json!({"dataBase64": context_plugin(id, commands)})).unwrap(); + let target = red_rect(app); + let undo = app.session.doc().unwrap().history.undo.len(); + for p in [json!(5), json!("by"), json!([target.0]), json!({"ids": target.0})] { + menus::invoke(h.state_mut(), &size, p.clone()); + step(&mut h); + assert!(h.state().plugin_dialog.is_none(), "{p} opens no dialog"); + assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo, "{p} changes nothing"); + } + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); +} + /// The `grant` and `allowHeavy` that `ui.installPlugin` is given approve nothing: it asks all the /// same, and what OK would approve comes from the manifest. A module with nothing to approve /// installs without either. From 46a2bc63517759fd0c642aaf30228e3c2bd0ebe2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:07:34 -0800 Subject: [PATCH 09/20] Honor plugin command conditions in canvas context menus --- crates/ui-egui/src/dialogs/plugin.rs | 5 ++++- crates/ui-egui/src/tests/plugins.rs | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 83ab829440..8890b9dd72 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -248,7 +248,10 @@ pub fn context_commands(menu: ContextMenu, doc: &vectorcraft_doc::Document, ids: pub fn canvas_submenu(doc: &vectorcraft_doc::Document, ids: &[u64]) -> Option { let groups: Vec = context_commands(ContextMenu::Canvas, doc, ids) .into_iter() - .map(|(name, commands)| sub(name, commands.into_iter().map(|command| cp(command.label, command.command, json!({ "ids": ids }))).collect())) + .map(|(name, commands)| { + let items = commands.into_iter().map(|command| cp(command.label, command.command, json!({ "ids": ids })).enabled(command.enabled)).collect(); + sub(name, items) + }) .collect(); (!groups.is_empty()).then_some(sub("Plug-ins", groups)) } diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index e4bb835de2..d9e0233302 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -766,6 +766,16 @@ fn plugin_commands_are_listed_in_the_canvas_and_layers_context_menus() { assert!(listed.iter().all(|(.., p)| *p == ids), "{listed:?}"); let shown = |app: &VectorcraftApp, c: &str| menus::shown_state(app, c, &ids).map(|(enabled, _)| enabled); assert_eq!((shown(app, &command("tidy")), shown(app, &command("text"))), (Some(true), Some(false)), "no type object is selected"); + fn rendered_enabled(nodes: &[menus::Node], command: &str) -> Option { + nodes.iter().find_map(|node| match node { + menus::Node::Item(item) if item.command.id == command => Some(item.enabled), + menus::Node::Submenu { children, .. } => rendered_enabled(children, command), + _ => None, + }) + } + let rendered = menus::context_items(app); + assert_eq!(rendered_enabled(&rendered, &command("tidy")), Some(true)); + assert_eq!(rendered_enabled(&rendered, &command("text")), Some(false)); let doc = app.session.doc().unwrap().doc.clone(); let rows = |ids: &[u64]| context_commands(ContextMenu::Layers, &doc, ids); From 0639f6f2f7e23d514277d290d3aa3f138ca0fbe7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:22:02 -0800 Subject: [PATCH 10/20] Format plugin context menu item construction --- crates/ui-egui/src/dialogs/plugin.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 8890b9dd72..5762a69ba9 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -249,7 +249,8 @@ pub fn canvas_submenu(doc: &vectorcraft_doc::Document, ids: &[u64]) -> Option = context_commands(ContextMenu::Canvas, doc, ids) .into_iter() .map(|(name, commands)| { - let items = commands.into_iter().map(|command| cp(command.label, command.command, json!({ "ids": ids })).enabled(command.enabled)).collect(); + let items = + commands.into_iter().map(|command| cp(command.label, command.command, json!({ "ids": ids })).enabled(command.enabled)).collect(); sub(name, items) }) .collect(); From 75d328e005c2109e89270471b9d86513592b47c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:05:34 -0800 Subject: [PATCH 11/20] Home: margin and gaps follow the framework's spacing tokens The app's size sets gave Home's page margin and its title, action, section, heading and link gaps fixed point values (60, 9, 27, 14, 33, 15, 5). They are dropped, so Home uses the framework's page tokens, which follow its spacing scale (space.gap.*), and the gaps between Home's sections, headings and cards share one rhythm. --- crates/ui-egui/src/theme.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 016e665e88..1aa688ceb9 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -146,10 +146,10 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { } /// The app's sizes over the framework's size sets (`sizes.json`): push buttons have the app's 4-point corners -/// where the sets give pills, the Home title is 26-point under 60 points of page margin with a 36-point call to -/// action, Home keeps production's rhythm (its item spacing of 5 plus the room it added: 9 from title to subtitle, 27 -/// to New and Open, 28-point New and Open with 16 points beside their labels and 14 between them, 33 between sections, -/// 15 under a heading, 24-point link rows 5 apart), and the compact set takes the reference app's metrics: +/// where the sets give pills, the Home title is 26-point with a 36-point call to action, 28-point New and Open with 16 +/// points beside their labels and 24-point link rows. Home's margin and the gaps between its title, actions, sections, +/// headings and links are the framework's page tokens, which follow its spacing scale (`space.gap.*`). The compact set +/// takes the reference app's metrics: /// 26-point fields and spinners, 24-point push buttons, 10 points inside panels, 5 between rows, 16-point glyphs in /// icon buttons, 5-point control corners, 8-point menus and 10-point windows, 33-point panel tabs, 310-point dock /// columns with 14-point column bars and 38-point icon columns, 29-point menu rows, and dialogs 22 points inside their @@ -161,16 +161,9 @@ const SIZES: &[u8] = br#"{ "radius.button": 4, "typography.display.size": 26, "typography.display.line_height": 32, - "size.page.margin": 60, "size.page.action": 36, "size.page.button": 28, "size.page.button_side": 16, - "size.page.gap.title": 9, - "size.page.gap.lead": 27, - "size.page.gap.actions": 14, - "size.page.gap.section": 33, - "size.page.gap.heading": 15, - "size.page.gap.link": 5, "size.page.link": 24 }, "compact": { @@ -235,4 +228,17 @@ mod tests { fn the_app_sizes_are_read_whole() { assert!(AppSizes::parse(SIZES).is_ok_and(|sizes| !sizes.is_empty())); } + + /// Home's margin and gaps are the framework's page tokens: no size set gives them points of its own, so they follow + /// the framework's spacing scale. + #[test] + fn home_spacing_follows_the_framework_tokens() { + let sets: serde_json::Map = serde_json::from_slice(SIZES).unwrap(); + for (set, sizes) in &sets { + let keys = sizes.as_object().map(|o| o.keys().collect::>()).unwrap_or_default(); + for key in keys { + assert!(!key.starts_with("size.page.gap.") && key != "size.page.margin", "{set} sets {key}"); + } + } + } } From fdffa121a9a7613ee78f8a7ec4d649795a3fb02a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:05:59 -0800 Subject: [PATCH 12/20] Render: cover the effects on reflected mirror repeat copies A Mirror Repeat on a slanted axis reflects its copy before the source's geometry effects run, so a Transform effect on the copy painted outside the move and Undo damage region, the same fault #9169 fixes for Radial Repeat. Mirror repeats now take the same measured bounds, with a test that fails without the change. --- crates/render/src/fx/bounds.rs | 10 ++++++---- crates/render/src/tests/changed.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index eefe3de3e7..2e05fca92b 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -758,7 +758,8 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b let a = live_content_reach(symbols, n); vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_live_effect_bounds(symbols, n)) } - // A radial repeat rotates each copy before applying the source's geometry effects. + // A radial or mirror repeat rotates or reflects each copy before applying the source's + // geometry effects. NodeKind::Repeat(_) => { let b = n.visual_bounds_with(symbols)?; let a = live_content_reach(symbols, n); @@ -856,13 +857,14 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { }) } -/// A radial repeat's copies or a spine-aligned blend's steps, measured after rotation. Geometry -/// effects run on the placed shapes, so their reach on the source need not cover what they paint. +/// A radial or mirror repeat's copies or a spine-aligned blend's steps, measured after they are +/// rotated or reflected. Geometry effects run on the placed shapes, so their reach on the source +/// need not cover what they paint. /// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps. fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { match &n.kind { NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {} - NodeKind::Repeat(r) if matches!(r.kind, vectorcraft_doc::RepeatKind::Radial { .. }) => {} + NodeKind::Repeat(r) if matches!(r.kind, vectorcraft_doc::RepeatKind::Radial { .. } | vectorcraft_doc::RepeatKind::Mirror { .. }) => {} _ => return None, } let mut has_effects = false; diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 7ccb472fda..4440c06baf 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -199,6 +199,34 @@ fn moving_a_radial_repeat_redraws_the_effects_on_its_rotated_copies() { } } +#[test] +fn moving_a_slanted_mirror_repeat_redraws_the_effects_on_its_reflected_copy() { + for effected in [false, true] { + let mut old = Document::new(110.0, 80.0); + let source_id = old.alloc_id(); + let mut source = Node::path( + source_id, + shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + if effected { + source.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}), + visible: true, + }); + } + let repeat = vectorcraft_doc::RepeatSpec::mirror(vec![Arc::new(source)], 45.0, 6.0); + let id = old.alloc_id(); + old.insert(Some(old.layers[0].id), 0, Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat))).unwrap(); + let mut moved = old.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false); + // A partial redraw must reproduce the whole frame, both on the move and on Undo. + area(redraw(&old, &moved)); + area(redraw(&moved, &old)); + } +} + #[test] fn adding_removing_and_restacking_change_those_objects() { let (old, [loose, _, _, _, other]) = document(); From 8af6814eb1eb200329295a1a606c365f292b40b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:08:16 -0800 Subject: [PATCH 13/20] Canvas: art lands on whole device pixels, so strokes stay sharp The canvas drew its rendered frame from wherever its corner fell, often between device pixels on a HiDPI or scaled display. Each frame pixel was then spread over two device pixels, so lines, arcs and shape edges looked soft and jagged with a doubled gray edge. The main canvas and the split view panes now place the frame on whole device pixels at its own pixel size. --- crates/ui-egui/src/canvas/panes.rs | 10 ++++++-- crates/ui-egui/src/canvas/raster.rs | 15 ++++++++++- crates/ui-egui/src/canvas/tests.rs | 39 +++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 9e25bcbf93..2fff6194da 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -19,7 +19,7 @@ use serde_json::json; use vectorcraft_geom::{Affine, Point}; use super::BodyKind; -use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key}; +use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key, snapped_rect}; use crate::doc_windows::Win; use crate::state::View; use crate::{CacheKey, VectorcraftApp}; @@ -141,6 +141,7 @@ impl PaneSource { pub(super) fn new(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, cv: &CanvasView) -> Option { let env = Env::of_root(ctx); let ppp = ctx.pixels_per_point(); + let device_ppp = ppp; let space = cv.rect; let v = crate::doc_windows::view(app, w).copied()?; let st = app.session.documents().get(w.0)?; @@ -165,7 +166,12 @@ impl PaneSource { Some([x0, y0, x1, y1]) => { egui::Rect::from_two_pos(cv.to_screen(Point::new(x0 as f64, y0 as f64)), cv.to_screen(Point::new(x1 as f64, y1 as f64))) } - None => space, + // The frame's own pixel size, centered on the pane and on whole device pixels, so each + // of its pixels covers one device pixel. + None => { + let size = egui::vec2(pw as f32 / ppp, ph as f32 / ppp); + snapped_rect(space.center() - size / 2.0, size, device_ppp) + } }; let frame = PaneFrame { key: PaneKey { slot: (st.uid, w.1) }, diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 9d1cdcb417..48f036012e 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -313,6 +313,18 @@ pub(super) fn frame_ppp(size: egui::Vec2, ppp: f32, max_side: usize) -> f32 { if longest.round() <= max { ppp } else { ppp * (max / longest) } } +/// Where a frame drawn `size` points across from `min` goes on a display of `device_ppp` pixels a +/// point: `min` moved to the nearest device pixel, the size unchanged. A canvas whose corner falls +/// between device pixels would otherwise draw every pixel of the frame across two device pixels, +/// and each edge in the art would show as a soft double line. +pub(super) fn snapped_rect(min: egui::Pos2, size: egui::Vec2, device_ppp: f32) -> egui::Rect { + if !(device_ppp.is_finite() && device_ppp > 0.0) { + return egui::Rect::from_min_size(min, size); + } + let snap = |c: f32| (c * device_ppp).round() / device_ppp; + egui::Rect::from_min_size(pos2(snap(min.x), snap(min.y)), size) +} + /// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view /// included. None when the view is degenerate, or when a side of the region is more than /// `max_side` pixels, the largest texture side the display supports. @@ -975,7 +987,8 @@ fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, view: &CanvasV let old = CanvasView::new(old_rect, Point::new(k.cx, k.cy), k.zoom).rotation(rotation); let a = view.to_screen(old.to_doc(old_rect.min)); let b = view.to_screen(old.to_doc(old_rect.max)); - painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + let placed = snapped_rect(a, b - a, painter.pixels_per_point()); + painter.image(tex.id(), placed, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } // The view turned after the last frame was rendered, and the worker renders the frame at // the new angle. Until it arrives, the last frame is drawn turned into this view: each diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4857c67064..3f1eddb392 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1191,6 +1191,45 @@ fn the_art_renders_within_the_largest_texture_side() { assert_eq!(pixel_region(&view, 1024), None, "more than the display's largest texture"); } +/// On a display of 2 pixels a point, a canvas whose corner falls between device pixels still draws +/// its art's frame on whole device pixels at its own size, so each frame pixel covers one device +/// pixel and a stroke's edges stay sharp instead of spreading over two device pixels. +#[test] +fn the_art_lands_on_whole_device_pixels() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":400,"height":300})).unwrap(); + app.canvas.worker_started = true; // every frame on this thread + let ctx = crate::testing::ui_context(); + ctx.set_pixels_per_point(2.0); + let mut shapes = vec![]; + // The first frame sets the pixels a point, the second draws at them. + for _ in 0..2 { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(pos2(31.3, 19.7), vec2(800.3, 600.35))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + shapes = flat_shapes(out.shapes); + } + let ppp = ctx.pixels_per_point(); + assert_eq!(ppp, 2.0); + let rect = app.canvas_view().unwrap().rect; + let off_grid = |c: f32| ((c * ppp) - (c * ppp).round()).abs() > 0.01; + assert!(off_grid(rect.min.x) || off_grid(rect.min.y), "the canvas {rect:?} starts between device pixels"); + let tex = app.canvas.texture.as_ref().expect("a rendered frame"); + let (tid, size) = (tex.id(), tex.size()); + let drawn = shapes + .iter() + .find_map(|s| match s { + Shape::Mesh(m) if m.texture_id == tid => Some(m.calc_bounds()), + _ => None, + }) + .expect("the frame is drawn"); + for (c, what) in [(drawn.min.x, "left"), (drawn.min.y, "top")] { + assert!(!off_grid(c), "the frame's {what} edge {c} is not on a device pixel"); + } + assert!((drawn.width() * ppp - size[0] as f32).abs() < 0.01, "{} device pixels across for {} frame pixels", drawn.width() * ppp, size[0]); + assert!((drawn.height() * ppp - size[1] as f32).abs() < 0.01, "{} device pixels down for {} frame pixels", drawn.height() * ppp, size[1]); +} + /// `rgb` as the display transform `t` shows it. fn convert8(t: &craft::color_ui::display::DisplayTransform, rgb: [u8; 3]) -> [u8; 3] { let mut px = [rgb[0], rgb[1], rgb[2], 255]; From 71b31572509f51ed910a3e488d0293e61c1c520b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:20:43 -0800 Subject: [PATCH 14/20] =?UTF-8?q?Relink:=20OK=20after=20File=20=E2=80=BA?= =?UTF-8?q?=20Revert=20relinks=20nothing=20and=20asks=20to=20reopen=20the?= =?UTF-8?q?=20dialog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Relink dialog kept only the opening document's uid, so after File › Revert replaced that document's content, OK relinked the restored objects that have the same ids. The dialog now keeps the document's revert count as well, and OK in a reverted document relinks nothing, records no undo step and shows "The document was reverted. Reopen this dialog to continue." in the status line, as Transform and the style dialogs do. --- crates/ui-egui/src/dialogs/relink.rs | 100 ++++++++++++++++++++++++--- docs/mcp.md | 4 +- 2 files changed, 94 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index 7220750be8..2ee70056be 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -46,7 +46,8 @@ fn scope_label(scope: &str) -> Label { /// Open the dialog on the images and placed documents `ids` (default: the selected ones). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let st = app.session.active().ok_or("no document open")?; + let document = (st.uid, st.reverts); let ids = match p.get("ids").filter(|v| !v.is_null()) { Some(v) => v.as_array().cloned().ok_or_else(|| format!("`ids` must be an array of object ids, not {v}"))?, None => crate::panels::links::selected_ids(app).into_iter().map(Value::from).collect(), @@ -86,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns. -fn relink(app: &mut VectorcraftApp, (document, params): &(u64, Value)) -> Result<(), String> { - if app.session.active().is_none_or(|st| st.uid != *document) { - let reason = tl!("Relink can only change links in the document where it was opened."); +/// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns. OK is refused in +/// another document, and in the opening document after File > Revert has replaced its content. +fn relink(app: &mut VectorcraftApp, ((document, reverts), params): &((u64, u64), Value)) -> Result<(), String> { + let refusal = match app.session.active() { + Some(st) if st.uid == *document && st.reverts == *reverts => None, + Some(st) if st.uid == *document => Some(tl!("The document was reverted. Reopen this dialog to continue.")), + _ => Some(tl!("Relink can only change links in the document where it was opened.")), + }; + if let Some(reason) = refusal { app.status(reason); return Err(reason.to_owned()); } @@ -122,8 +128,8 @@ impl ItemSource for Names<'_> {} /// app (`HoldsOk`); with Each Link Separately it stays open until every link has a file. pub(crate) struct RelinkDialog { id: DialogId, - /// The document that owns the link IDs. - document: u64, + /// The document that owns the link IDs: its uid and revert count. + document: (u64, u64), ids: Vec, links: Vec, scope: String, @@ -135,7 +141,7 @@ pub(crate) struct RelinkDialog { } impl RelinkDialog { - fn new(document: u64, ids: Vec, links: Vec) -> Self { + fn new(document: (u64, u64), ids: Vec, links: Vec) -> Self { RelinkDialog { id: dialog_id(KEY), document, @@ -194,7 +200,7 @@ impl RelinkDialog { } impl HoldsOk for RelinkDialog { - type Answer = (u64, Value); + type Answer = ((u64, u64), Value); fn held_ok(self) -> Self { self @@ -451,6 +457,82 @@ mod tests { check_relink_stays_in_opening_drawing(true); } + /// Opens Relink on a saved document's linked image and chooses a replacement (in `path`, or from the file picker + /// with `native_picker`) around File > Revert, then presses OK: the restored image keeps its link, no undo step is + /// recorded and the status line reports the revert. Reopened on the restored document, Relink relinks again. + fn check_relink_refused_after_file_revert(native_picker: bool) { + use crate::tests::panel_harness::Panel; + + let (mut app, dir) = setup(if native_picker { "revert-picker" } else { "revert-path" }, &["photo.png"]); + let picker = scripted(&mut app); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let original = dir.join("photo.png").to_string_lossy().into_owned(); + let id = place(&mut app, &dir.join("photo.png")); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let chosen = new_file(&dir, "replacement.png"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(900.0, 700.0)); + panel.app().run("ui.relinkDialog", json!({"ids": [id]})).unwrap(); + panel.frame(); + if native_picker { + panel.click("Relink…"); + assert_eq!(picker.requests().len(), 1); + } else { + let dialog = relink_dialog(&panel.app()).id; + answer_dialog(&mut panel.app(), dialog, &[("path", json!(chosen))], false); + } + panel.app().run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + assert_eq!(link_path(&panel.app(), id), original, "the same id names the restored image"); + let undo = panel.app().session.active().unwrap().history.undo.len(); + if native_picker { + picker.answer(&[&chosen]); + panel.frame(); + panel.frame(); + } else { + panel.click("Relink…"); + panel.frame(); + } + { + let app = panel.app(); + assert_eq!(link_path(&app, id), original, "OK leaves the restored image's link unchanged"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); + let dialog = relink_dialog(&app).id; + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + } + + let ctx = ctx(&panel.app()); + let dialogs = panel.app().dialogs().expect("a window"); + let dialog = relink_dialog(&panel.app()).id; + dialogs.with(|host| host.cancel_by_id(&ctx, dialog)); + panel.frame(); + assert!(open_dialogs(&panel.app()).is_empty()); + panel.app().run("ui.relinkDialog", json!({"ids": [id]})).unwrap(); + panel.frame(); + let dialog = relink_dialog(&panel.app()).id; + answer_dialog(&mut panel.app(), dialog, &[("path", json!(chosen))], false); + panel.click("Relink…"); + panel.frame(); + let app = panel.app(); + assert!(open_dialogs(&app).is_empty()); + assert_eq!(link_path(&app, id), chosen, "reopened, Relink relinks the restored image"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + drop(app); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn relink_is_refused_after_file_revert_for_a_path_confirmation() { + check_relink_refused_after_file_revert(false); + } + + #[test] + fn relink_is_refused_after_file_revert_when_the_file_picker_answers() { + check_relink_refused_after_file_revert(true); + } + #[test] fn replace_popup_cancel_preserves_selected_instances_and_enter_relinks_all() { use crate::tests::panel_harness::Panel; diff --git a/docs/mcp.md b/docs/mcp.md index 8cb939c506..881f712f5c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10661,7 +10661,9 @@ one of them, in the layers, opacity-mask art, symbols, graph designs, patterns a `path` and `folder` and relinks each link to its own file. An unknown scope, `paths` without `each`, `each` with `ids`, `path` or `folder`, an entry without `path` or `ids`, an id in two entries and `missingInFolder` with `folder` are errors, and nothing is relinked. Each call is one undo step. The Links panel's Relink… opens the `relink` dialog -(`ui.relinkDialog`) with a Replace menu of these four choices. A PNG, JPEG, +(`ui.relinkDialog`) with a Replace menu of these four choices. Its OK relinks only in the document where the dialog +opened; after File › Revert it relinks nothing and the status line reads "The document was reverted. Reopen this +dialog to continue." A PNG, JPEG, another file (or each at the file of its name in a folder); images keep their bounds, one undo step each. `links.update`, and `document.open` when it reads a modified file, also read the file again for the images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of the stored brushes (a scatter or art From fc9c9f30e736d6b2c7002092885a6954495cdc72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:03:23 -0800 Subject: [PATCH 15/20] UI: give popovers, empty states and New Document buttons room The Manage Profiles and More Settings popovers pad their rows with the regular pad and the stack gap. Manage Profiles shows its heading as a section caption and lays the profiles out in a grid, so the Edit and Reset buttons line up in columns. Panel empty states (the shared empty_state helper, the Libraries notices and the Properties panel with no document) sit inside the roomy pad, so they no longer touch the tab strip, the panel edges or the library picker above them. In New Document, the Height, Orientation and Artboards row wraps whenever it does not fit the column, so Artboards is not cut off, and More Settings and Manage Profiles sit side by side the item gap apart. --- crates/ui-egui/src/dialogs/new_document.rs | 74 ++++++++++++++-------- crates/ui-egui/src/panels.rs | 30 +++++++-- crates/ui-egui/src/panels/libraries.rs | 43 +++++++------ crates/ui-egui/src/panels/properties.rs | 7 +- 4 files changed, 101 insertions(+), 53 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 8ec5e10ba1..561f7f9517 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -20,13 +20,13 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI}; -use craft::behavior::{IconId, Mixed}; +use craft::behavior::{ColumnWidth, IconId, Mixed}; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked}; -use craft::ui::display::Text; +use craft::ui::contract::{Bind, Entry, Gap, Props as _, Show as _, ShowContainer as _, clicked}; +use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Grid, Row}; use craft::ui::patterns::form_dialogs::{ CardCx, CardSource, DetailsCx, DocumentCard, DocumentSettings, HostedNewDocument, NewDocumentDialog, Orientation, PresetCategory, }; @@ -35,6 +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::style::TypeRole; use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; use super::host::open_held; @@ -296,8 +297,8 @@ impl DocumentSettings for VcNewDocument { } }); }); - // Host viewports below the desktop main window's 800-point minimum need this row to wrap. - Row::new().wrap(ui.ctx().content_rect().width() < 800.0).show(ui, |ui, _| { + // The row wraps whenever its fields do not fit the column, so Artboards is never cut off at its right edge. + Row::new().wrap(true).show(ui, |ui, _| { Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); Field::new(orientation.clone()).show(ui, |ui, _| { let entries = [ @@ -354,17 +355,24 @@ impl DocumentSettings for VcNewDocument { Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s)); - let more = Button::new(text(tl!("More Settings"))).id_salt("more-settings").show(ui); - let mut more_open = memory.more_open != clicked(&more); - Popover::new(text(tl!("More Settings")), Bind::bound(&mut more_open)).opened_by(&more).show(ui, |ui, _| more_settings(ui, s, lengths)); - memory.more_open = more_open; - - let manage = Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").show(ui); - let mut profiles_open = memory.profiles_open != clicked(&manage); - Popover::new(text(tl!("Manage Profiles")), Bind::bound(&mut profiles_open)) - .opened_by(&manage) - .show(ui, |ui, _| manage_profiles(ui, &setup, &mut action)); - memory.profiles_open = profiles_open; + // The two buttons side by side, the item gap apart. + let (mut more, mut manage) = (None, None); + Row::new().gap(Gap::Item).wrap(true).show(ui, |ui, _| { + more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").show(ui)); + manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").show(ui)); + }); + if let Some(more) = &more { + let mut more_open = memory.more_open != clicked(more); + Popover::new(text(tl!("More Settings")), Bind::bound(&mut more_open)).opened_by(more).show(ui, |ui, _| more_settings(ui, s, lengths)); + memory.more_open = more_open; + } + if let Some(manage) = &manage { + let mut profiles_open = memory.profiles_open != clicked(manage); + Popover::new(text(tl!("Manage Profiles")), Bind::bound(&mut profiles_open)) + .opened_by(manage) + .show(ui, |ui, _| manage_profiles(ui, &setup, &mut action)); + memory.profiles_open = profiles_open; + } // Drafts stay in their controls until committed: ending the preset or choosing units cannot be undone by // restoring only a scalar value. Units and orientation only change how the page shows; other edits end the preset. @@ -475,6 +483,10 @@ fn advanced(ui: &mut egui::Ui, s: &mut DocSettings) { /// More Settings' pop-up: the artboard layout, spacing and columns. All three are off with one /// artboard, Columns also for the row and column layouts; columns stay within the artboards. fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { + crate::panels::popover_body(ui, |ui| more_settings_rows(ui, s, lengths)); +} + +fn more_settings_rows(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { let several = s.artboards > 1; let grid = matches!(s.layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn); let (layout, spacing, columns, right_to_left) = @@ -531,22 +543,26 @@ fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) { /// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a /// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`. fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option) { - Text::new(text(tl!("NEW DOCUMENT PROFILES"))).show(ui); - for (name, customized) in &setup.profiles { - ui.push_id(name, |ui| { - Row::new().show(ui, |ui, _| { - Text::new(text(tl!(name))).show(ui); - if clicked(&Button::new(text(tl!("Edit"))).id_salt("edit").enabled(setup.has_profile_folder).show(ui)) { + crate::panels::popover_body(ui, |ui| { + Text::new(text(tl!("NEW DOCUMENT PROFILES"))).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui); + // The names in one column and the Edit and Reset buttons in columns of their own, so the buttons line up. + Grid::new(&PROFILE_COLUMNS).gap(Gap::Item).show(ui, |ui, _| { + for (name, customized) in &setup.profiles { + Text::new(text(tl!(name))).id_salt(("profile", name)).show(ui); + if clicked(&Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder).show(ui)) { *action = Some(format!("{EDIT_PROFILE}:{name}")); } - if clicked(&Button::new(text(tl!("Reset"))).id_salt("reset").enabled(*customized).show(ui)) { + if clicked(&Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(*customized).show(ui)) { *action = Some(format!("{RESET_PROFILE}:{name}")); } - }); + } }); - } + }); } +/// The columns of Manage Profiles' rows: the profile's name, Edit and Reset. +const PROFILE_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; + /// The category of the settings New Document opens on: the most recent, else Print. fn first_category(app: &VectorcraftApp) -> &'static str { if app.session.prefs.recent_new_docs.is_empty() { "Print" } else { "Recent" } @@ -1009,7 +1025,11 @@ mod tests { }; let landscape = bounds("Landscape", egui::accesskit::Role::RadioButton); let artboards = bounds("Artboards", egui::accesskit::Role::SpinButton); - assert!(landscape.x1 <= artboards.x0, "Landscape {landscape:?} stays left of Artboards {artboards:?}"); + // Artboards follows Landscape on its line, or wraps below it when the column has no room for it. + assert!( + landscape.x1 <= artboards.x0 || landscape.y1 <= artboards.y0, + "Landscape {landscape:?} stays clear of Artboards {artboards:?}" + ); let group = bounds("Orientation", egui::accesskit::Role::RadioGroup); let mut drawn = Vec::new(); out.shapes.iter().for_each(|s| texts(&s.shape, &mut drawn)); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 7e18b51179..005d46e890 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -65,7 +65,8 @@ use craft::theme::variant::Tone; use craft::ui::buttons::{IconButton, Link, PopupMark}; use craft::ui::choice::{Radio, RadioGroup, SwatchSpacing}; use craft::ui::contract::{ - Bind, CaptionColumn, CommandSet as _, Entry, LabelScheme, ListDrag, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, + Bind, CaptionColumn, CommandSet as _, Entry, Gap, LabelScheme, ListDrag, Pad, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, + Trigger, }; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, FieldGroup}; @@ -1068,11 +1069,28 @@ pub(crate) fn option_link(label: impl Into