From 6cce980e2bb5e1781b72452983716ed659775575 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:46:14 -0800 Subject: [PATCH] Scripts: keep targets and chosen parts when edits restore the selection - An edit a script makes puts back a Layers panel target, an object chosen inside a dynamic symbol instance and an object chosen in an Objects on Path group, each with its own selection command. - Assigning a document's selection selects a symbol instance or an Objects on Path group as a whole when one of its objects was chosen. - file.newPresets lists a grid by column's rows as set, also when there are fewer artboards than rows, and New Document's Columns shows the columns those rows give the current number of artboards. - docs/roadmap.md's M13 row names the script object model that is available. --- crates/engine/src/cmd/newdoc.rs | 5 +- crates/engine/src/script/dom.rs | 35 +++++++++-- crates/engine/src/tests/script_dom.rs | 71 ++++++++++++++++++++++ crates/ui-egui/src/dialogs/new_document.rs | 35 ++++++++--- docs/mcp.md | 5 +- docs/roadmap.md | 2 +- 6 files changed, 135 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 03be423cf3..a242b1fd20 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -265,8 +265,9 @@ impl DocSettings { pub fn to_json(&self) -> Value { let mut layout = json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}); - if let (Some(rows), Some(o)) = (self.grid_rows(), layout.as_object_mut()) { - o.insert("rows".into(), json!(rows)); + // The rows as set, also when there are fewer artboards than rows. + if let Some(o) = layout.as_object_mut().filter(|_| self.grid_rows().is_some()) { + o.insert("rows".into(), json!(self.rows)); } json!({ "name": self.name, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index dd17bb579e..0883e94099 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -443,9 +443,10 @@ fn coords_of(d: &Data) -> std::result::Result { } /// Selects `before` again in the active document `doc` with the selection commands, so that the -/// journal holds the change: the objects in their order with their direct-selected anchors, then -/// the segments, the ruler guides and the key object, guide or anchor. Objects that are now -/// deleted, hidden or locked are left out. +/// journal holds the change: a Layers panel target, a dynamic symbol instance's object or an Objects +/// on Path group's object with its own command, else the objects in their order with their +/// direct-selected anchors, then the segments, the ruler guides and the key object, guide or anchor. +/// Objects that are now deleted, hidden or locked are left out. fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { // Slices selected with the Slice Selection tool are the whole selection when there are any. let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); @@ -454,6 +455,24 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - return Ok(()); } let keep = |id: &NodeId| editable(doc, *id); + // Each of these commands sets the whole selection. One that refuses (its object is no longer + // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the + // objects are selected as below. + if let Some(t) = before.target.filter(keep) + && command(h, "layer.target", &json!({"id": t.0})).is_ok() + { + return Ok(()); + } + if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) + && command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})).is_ok() + { + return Ok(()); + } + if let Some(m) = before.on_path_member.filter(keep) + && command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})).is_ok() + { + return Ok(()); + } let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); let kept: Vec = before.objects.iter().copied().filter(keep).collect(); if kept.is_empty() { @@ -503,8 +522,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, -/// ruler guides, slices and the key included, less the objects that are now deleted, hidden or -/// locked. +/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic +/// symbol instance or an Objects on Path group included, less the objects that are now deleted, +/// hidden or locked. fn on_doc( h: &Host, uid: u64, @@ -1054,12 +1074,15 @@ fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { } /// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each -/// selected as a whole, and no ruler guide, slice, key or Layers panel target. +/// selected as a whole (no dynamic symbol instance's object or Objects on Path group's object +/// chosen in it), and no ruler guide, slice, key or Layers panel target. fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { let same = with_doc(h, doc, |_, st| { let sel = &st.selection; sel.objects == ids && sel.target.is_none() + && sel.symbol_part.is_none() + && sel.on_path_member.is_none() && sel.anchors.is_empty() && sel.segments.is_empty() && sel.guides.is_empty() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 15a8e2e950..63cebea042 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -430,6 +430,18 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn a_listed_preset_keeps_more_rows_than_artboards() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(1), &json!(4)), "{listed}"); + // Five artboards from the listing fill four rows, not two. + let more = settings.with_params(&json!({"artboards": 5, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); +} + #[test] fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); @@ -487,6 +499,65 @@ fn assigning_the_selection_clears_a_layers_panel_target() { assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); } +#[test] +fn an_edit_keeps_a_layers_panel_target() { + let (mut s, a, b) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], Some(a))); + // A targeted layer stays targeted, with its art selected. + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); +} + +/// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two +/// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the +/// group's rectangle). +fn chosen_parts() -> (Session, NodeId, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); + let (x, y) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 50.0, 10.0, 20.0, 20.0)); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [x.0, y.0], "type": "dynamic"})).unwrap()); + let member = rect(&mut s, 10.0, 100.0, 20.0, 20.0); + let line = id(s.execute("shape.line", &json!({"x1": 50, "y1": 250, "x2": 350, "y2": 250})).unwrap()); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = id(s.execute("object.objectsOnPath.attach", &json!({"path": line.0})).unwrap()); + (s, inst, group, member) +} + +#[test] +fn an_edit_keeps_an_object_chosen_inside_a_symbol_or_on_a_path() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (before.objects, before.symbol_part)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], Some(member))); +} + +#[test] +fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (vec![inst], None)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], None)); +} + #[test] fn a_held_image_stays_the_same_object_when_it_is_embedded() { let dir = super::links::Folder::new("dom-embed"); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index f64f2f6be2..6b9abbcb2f 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -233,16 +233,21 @@ fn unit(d: &Dialog) -> Unit { Unit::named(&d.str("units")).unwrap_or_default() } -/// The artboard layout fields. +/// The artboard layout fields. A grid by column with rows shows the columns those rows give the +/// current number of artboards, as `file.new` lays them out. fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { let l = d.fields.get("artboardLayout"); let get = |k: &str| l.and_then(|l| l.get(k)); - ( - get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(), - get("columns").and_then(Value::as_u64).unwrap_or(1), - get("spacing").and_then(Value::as_f64).unwrap_or(20.0), - get("rightToLeft").and_then(Value::as_bool).unwrap_or(false), - ) + let lay = get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(); + let rows = get("rows").and_then(Value::as_u64).filter(|r| *r > 0 && lay == ArtboardLayout::GridByColumn); + let columns = match rows { + Some(rows) => { + let n = d.f64("artboards", 1.0).round().clamp(1.0, MAX_ARTBOARDS as f64) as u64; + n.div_ceil(rows.min(n)) + } + None => get("columns").and_then(Value::as_u64).unwrap_or(1), + }; + (lay, columns, get("spacing").and_then(Value::as_f64).unwrap_or(20.0), get("rightToLeft").and_then(Value::as_bool).unwrap_or(false)) } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset @@ -910,6 +915,22 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); } + /// Columns shows what a preset's rows give the current number of artboards. + #[test] + fn columns_follow_a_presets_rows_as_artboards_change() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 4})); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + for (artboards, shown) in [(5, 2), (9, 3), (2, 1)] { + set(&mut app, "artboards", json!(artboards)); + assert_eq!(columns(&app), shown, "{artboards} artboards"); + } + // Without rows, Columns shows the stored count. + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); + assert_eq!(columns(&app), 2); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5f873fe10a..50e8af3d40 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8852,8 +8852,9 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is -an error with another layout; a preset keeps the rows until `columns` without `rows`, or another layout, is given, -and New Document drops them when Columns or the layout changes), +an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are +fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns +the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). diff --git a/docs/roadmap.md b/docs/roadmap.md index 27c4f78e25..3ddf3459a4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |