From 118dcf9ef8a9436c17b5a47eff7579df606aab6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 07:14:10 -0800 Subject: [PATCH 1/7] Arrange Tools: Add Artboard Guides puts a guide rectangle inside or outside artboards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at a typed offset: more than 0 puts it outside the artboard, less than 0 inside it. The dialog has Offset, Artboards (Active Artboard or All Artboards) and Preview, and OK applies as one undo step. - addon.arrange.artboardGuides {offset?, artboards?, artboard?, all?} puts the guide paths on the topmost top-level layer named Artboard Guides, made above the others when there is none. That layer keeps its lock and visibility. A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no undo step. - An inset that leaves an artboard no width or height, an edge past the canvas, and bad params are refused with an error. The command is off without artboards. - The command is in ON_ACTIVE_ARTBOARD, so the app passes the active artboard as `artboard`, and command.batch and action playback pass it to a step that names none; when it is left out, the journal records the artboard used, so a replay acts on the same one. The dialog sends the artboard the view showed when it opened. - Plug-ins may call it (plugin_call/reviewed.rs). Docs: docs/mcp.md › Arrange Tools add-on and app.doScript, docs/target-app-parity.md, docs/ui-parity.md; command.batch params text. --- crates/engine/src/cmd/addons/arrange.rs | 9 +- .../src/cmd/addons/arrange/artboard_guides.rs | 126 +++++++++++ .../addons/arrange/artboard_guides/tests.rs | 205 ++++++++++++++++++ crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/command_sets.rs | 9 +- crates/ui-egui/src/addons/arrange.rs | 38 +++- crates/ui-egui/src/addons/arrange/tests.rs | 88 ++++++++ crates/ui-egui/src/app/commands.rs | 9 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 12 files changed, 485 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/cmd/addons/arrange/artboard_guides.rs create mode 100644 crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index f81d7a599a..2857b71f0d 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -5,9 +5,11 @@ //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the //! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in -//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection -//! (a view command) are the UI's. +//! that order. Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]). +//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view +//! command) are the UI's. +mod artboard_guides; #[cfg(test)] mod tests; @@ -107,6 +109,9 @@ pub fn specs() -> Vec { sort ), ] + .into_iter() + .chain(artboard_guides::specs()) + .collect() } /// Exactly two objects are selected (Swap Objects). diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs new file mode 100644 index 0000000000..69231b1f8e --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -0,0 +1,126 @@ +//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen +//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named +//! Artboard Guides. Its dialog is the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::super::super::panelcmds::{artboard_at, listed_artboards}; +use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; +use super::{LIMIT, number_in}; +use crate::sanity::rect_in_range; +use crate::{DocState, Result, Session}; + +/// The command. +pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides"; +/// The top-level layer the guides go on, made when the document has none of that name. +pub(crate) const LAYER: &str = "Artboard Guides"; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.arrange.artboardGuides", + "Add Artboard Guides", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}", + has_artboards, + artboard_guides + )] +} + +/// A document with at least one artboard is open. +fn has_artboards(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) } +} + +/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no +/// longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &DocState) -> usize { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).unwrap_or(0) +} + +/// The topmost top-level layer named [`LAYER`]. +fn guide_layer(d: &Document) -> Option { + d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) +} + +/// Does `layer` already hold a guide path drawn as `rect` is? +fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { + let path = shapes::rectangle(rect); + layer.and_then(|id| d.node(id)).is_some_and(|n| { + let mut found = false; + n.walk(&mut |c| { + found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if *p == path); + }); + found + }) +} + +fn artboard_guides(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?; + let all = switch_or(p, "all", false, C)?; + let listed = p.get("artboards").filter(|v| !v.is_null()); + if all && listed.is_some() { + return Err(bad(C, "give `all` or `artboards`, not both")); + } + let st = s.doc()?; + let d = &st.doc; + if d.artboards.is_empty() { + return Err(bad(C, "the document has no artboards")); + } + // The active artboard: the one the app passes, else the view's, recorded for a replay. + let active = artboard_at(d, p, "artboard", C)?; + let indices: Vec = match listed { + Some(v) => listed_artboards(d, v, "artboards", C)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![active.unwrap_or_else(|| active_artboard(st))], + }; + if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) { + s.note_journal("artboard", json!(i)); + } + let st = s.doc()?; + let d = &st.doc; + let layer = guide_layer(d); + let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0); + for i in indices { + let Some(board) = d.artboards.get(i) else { continue }; + let r = board.rect.inflate(offset, offset); + if !(r.width() > 0.0 && r.height() > 0.0) { + return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name))); + } + if !rect_in_range(r) { + return Err(bad(C, "the guide would reach past the edge of the canvas")); + } + if holds_guide(d, layer, r) || rects.contains(&r) { + skipped += 1; + } else { + rects.push(r); + } + } + if rects.is_empty() { + return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped })); + } + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let (layer, ids) = s.edit("Add Artboard Guides", |d, _| { + let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER))); + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default()); + look.apply(d, &mut n); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + Ok((layer, ids)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "skipped": skipped })) +} diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs new file mode 100644 index 0000000000..5b8093b07e --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -0,0 +1,205 @@ +//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer +//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused +//! without a change. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::Rect; + +use super::{COMMAND, LAYER}; +use crate::Session; + +/// A new document with one 400 × 300 pt artboard and a second one beside it. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn board(s: &Session, i: usize) -> Rect { + s.doc().unwrap().doc.artboards[i].rect +} + +fn ids(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() +} + +/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`. +fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect { + let d = &s.doc().unwrap().doc; + let n = d.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path"); + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer"); + n.geometric_bounds().unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9) +} + +fn layer_names(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +#[test] +fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() { + let mut s = session(); + let n = steps(&s); + let before = layer_names(&s); + let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let layer = NodeId(r["layer"].as_u64().unwrap()); + assert_eq!(r["skipped"], json!(0)); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + // The active artboard is the first when the view has not picked one. + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id)); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others"); + assert_eq!(d.layers.last().unwrap().display_name(), LAYER); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide"); +} + +#[test] +fn the_active_artboard_is_the_one_the_view_keeps() { + let mut s = session(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges"); + assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay"); + // The artboard the app passes wins over the view's. + let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0))); + assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard"); +} + +#[test] +fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() { + let mut s = session(); + let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap(); + let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s)); + let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for every artboard"); + assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused"); + assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added"); + let added = ids(&r); + assert_eq!(added.len(), 2); + for (i, id) in added.into_iter().enumerate() { + assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}"); + } + let l = s.doc().unwrap().doc.node(layer).unwrap().clone(); + assert!(l.locked && !l.visible, "the layer keeps its lock and visibility"); +} + +#[test] +fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0))); + // Again: nothing to add, and no undo step. + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before); + // Both artboards: only the new one is added. + let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap(); + assert_eq!(both["skipped"], json!(1)); + let [first] = ids(&both)[..] else { panic!("one guide: {both}") }; + assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0))); + assert_eq!(steps(&s), n + 1); +} + +#[test] +fn a_guide_grouped_inside_the_layer_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group)); + assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id)); + let (before, n) = (d.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); +} + +#[test] +fn release_guides_gives_back_a_rectangle_path() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(n.kind, NodeKind::Path { guide: false, .. })); + assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0))); +} + +#[test] +fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() { + let mut s = session(); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + // The second artboard is 100 pt tall: an inset of 50 leaves it no height. + for p in [ + json!({"offset": -50, "all": true}), + json!({"offset": -200}), + json!({"offset": "9 pt"}), + json!({"offset": 1_000_001}), + json!({"offset": -1e308}), + json!({"all": 1}), + json!({"all": true, "artboards": [0]}), + json!({"artboards": []}), + json!({"artboards": [2]}), + json!({"artboards": [-1]}), + json!({"artboards": [0.5]}), + json!({"artboards": "0"}), + ] { + assert!(s.execute(COMMAND, &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); + let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string(); + assert!(e.contains("no width or height"), "{e}"); +} + +#[test] +fn a_guide_past_the_edge_of_the_canvas_is_refused() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap(); + let n = steps(&s); + let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string(); + assert!(e.contains("past the edge of the canvas"), "{e}"); + assert_eq!(steps(&s), n); + s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap(); +} + +#[test] +fn it_is_off_without_artboards() { + let mut s = session(); + let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled; + assert!(enabled(&s)); + Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + assert!(!enabled(&s)); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a48ac3e85b..31db92bfd5 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each addon.arrange.artboardGuides, edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..947f644be9 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -4,6 +4,7 @@ /// Commands a plug-in may call when its manifest lists them, in order. pub(super) const ALLOWED: &[&str] = &[ + "addon.arrange.artboardGuides", "addon.arrange.grid", "addon.arrange.groupOverlapping", "addon.arrange.randomizeOpacity", diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 1346dc40c5..75a30965ea 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -4,8 +4,10 @@ use super::{NodeId, Value, cmd, find_command}; /// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute /// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on /// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art -/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none. -pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ +/// on it, and Add Artboard Guides puts its guide around it. A `command.batch` given `artboard` +/// passes it on to each of their steps that names none. +pub const ON_ACTIVE_ARTBOARD: [&str; 9] = [ + "addon.arrange.artboardGuides", "edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack", @@ -35,8 +37,9 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 35] = [ +const REPLAY_ONLY: [(&str, &str); 36] = [ ("file.new", "created"), + ("addon.arrange.artboardGuides", "artboard"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), ("file.saveAs", "modified"), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a26f5f7a28..bfb5d53bce 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,7 +1,8 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, -//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping -//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. +//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity, Sort Objects and +//! Add Artboard Guides, which preview on the canvas and run their `addon.arrange.*` command on OK; +//! Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the +//! selection. use std::borrow::Cow; @@ -26,14 +27,18 @@ const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; +const GUIDES: &str = "addon.arrange.artboardGuides"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 5] = [ +const DIALOGS: [(&str, &str); 6] = [ (GRID, "Arrange in Grid"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), + (GUIDES, "Add Artboard Guides"), ]; +/// The artboards Add Artboard Guides puts guides around: `all` false or true. +const SCOPES: [(&str, &str); 2] = [("active", "Active Artboard"), ("all", "All Artboards")]; /// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. const SIZES: std::ops::RangeInclusive = 0.001..=1e6; const GAPS: std::ops::RangeInclusive = -1e6..=1e6; @@ -63,6 +68,7 @@ pub fn menu() -> Vec { cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), + c("Add Artboard Guides…", GUIDES), Sep, cp("Zoom to Selection", ZOOM, json!({})), ] @@ -73,6 +79,7 @@ static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, fou static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; +static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None }; /// The dialog over `rows`, titled by the heading of `command`. fn dialog<'a>(command: &str, rows: Vec) -> ParamDialog<'a> { @@ -152,6 +159,11 @@ fn sort_rows() -> Vec { ] } +fn guides_rows(lengths: LengthUnits) -> Vec { + // More than 0 outside the artboard, less than 0 inside it. + vec![length("offset", "Offset:", 0.0, GAPS, lengths), choice("scope", "Artboards:", &SCOPES, "active")] +} + fn grid_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&grid_rows(POINTS), fields)) } @@ -181,6 +193,18 @@ fn sort_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&sort_rows(), fields)) } +/// Add Artboard Guides' offset, and `all` for All Artboards, else the artboard active when the dialog opened. +fn guides_params(fields: &DialogFields) -> Value { + let mut params = form::json_of(&guides_rows(POINTS), fields); + let all = fields.text("scope") == Some("all"); + params.remove("scope"); + if all { + params.remove("artboard"); + } + params.insert("all".into(), json!(all)); + Value::Object(params) +} + /// Opens the dialog of command `id` on the active document; `None` for another command and without a document. pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option> { let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?; @@ -207,6 +231,11 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option ( + guides_rows(lengths), + json!({ "offset": 0, "scope": "active", "artboard": crate::panels::artboards::selected(app, st.doc.artboards.len()) }), + ), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { let (w, h) = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { @@ -229,6 +258,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), + GUIDES => super::dialogs::open(app, &GUIDES_SPEC, fields, move |fields| dialog(GUIDES, guides_rows(lengths)).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 420bfdb01d..44978f978b 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -109,6 +109,94 @@ fn real_opacity_edits_drive_validation_confirmation_and_cancel() { assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); } +/// The bounds of the guide paths on the top-level layer Artboard Guides, from the back. +fn artboard_guides(app: &VectorcraftApp) -> Vec { + let d = &app.session.doc().unwrap().doc; + let layer = d.layers.iter().find(|l| l.name.as_deref() == Some("Artboard Guides")); + let guides = layer.and_then(|l| l.children()).into_iter().flatten(); + guides.filter(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: true, .. })).map(|n| n.geometric_bounds().unwrap()).collect() +} + +#[test] +fn real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step() { + for cancel in [true, false] { + let (app, _, _) = app(); + let board = app.session.doc().unwrap().doc.artboards[0].rect; + let (original, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len()); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Add Artboard Guides…"); + panel.frame(); + type_number(&mut panel, "Offset", "-12"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.number("offset")), Some(-12.0)); + assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)], "the preview insets the active artboard"); + panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX); + panel.frame(); + assert!(artboard_guides(&panel.app()).is_empty(), "no guide with Preview off"); + panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX); + panel.frame(); + assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)]); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo, "a preview makes no step"); + panel.click(if cancel { "Cancel" } else { "OK" }); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + let state = app.session.doc().unwrap(); + if cancel { + assert!(*state.doc == *original, "Cancel leaves the document as it was"); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(artboard_guides(&app), vec![board.inflate(-12.0, -12.0)]); + assert_eq!(state.history.undo.len(), undo + 1, "OK adds the guide as one undo step"); + } + } +} + +#[test] +fn add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset() { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + let boards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| (f.number("offset"), f.text("scope").map(str::to_owned))), (Some(0.0), Some("active".to_owned()))); + host::set(&app, id, "offset", json!(18)); + host::set(&app, id, "scope", json!("all")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), boards.iter().map(|b| b.inflate(18.0, 18.0)).collect::>()); + // The second artboard is 100 pt tall: an inset of 50 leaves it nothing, so OK adds nothing. + let (before, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len()); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "offset", json!(-50)); + host::set(&app, id, "scope", json!("all")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(*app.session.doc().unwrap().doc == *before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn add_artboard_guides_uses_the_artboard_the_view_shows() { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + let second = app.session.doc().unwrap().doc.artboards[1].rect; + // The view moves to the second artboard without a command that tells the document, which + // still names the first. + app.view_mut().unwrap().artboard = 1; + let first = app.session.doc().unwrap().doc.artboards[0].id; + app.session.active_mut().unwrap().active_artboard = Some(first); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "offset", json!(6)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "the preview"); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "OK"); +} + #[test] fn set_size_of_each_sets_the_sides_ticked() { let (mut app, a, b) = app(); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index b7ff421414..35aeae8ea5 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -121,10 +121,11 @@ impl VectorcraftApp { } } - /// Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align, - /// Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols - /// panel act on the active artboard, the view's, which the app adds to command `id`'s `params` as - /// `artboard`. A batch passes it on to those steps. While the Artboard tool has several artboards + /// Add Artboard Guides (Object › Plug-ins › Arrange Tools), Paste in place, in front and in + /// back (#693), Select › All on Active Artboard (#1006), and Align, Distribute Objects and + /// Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols panel act on the + /// active artboard, the view's, which the app adds to command `id`'s `params` as `artboard`. A + /// batch passes it on to those steps. While the Artboard tool has several artboards /// selected, the paste commands get those as `artboards` instead, and paste a copy on each; in a /// document without artboards they get neither. fn add_active_artboard(&self, id: &str, params: &mut Value) { diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..c64140765c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3238,7 +3238,8 @@ through `$`: https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own - steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and + steps. A step that acts on the active artboard (Add Artboard Guides, Paste in Place, in Front and in Back, Align, + Distribute Objects and Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one @@ -17441,10 +17442,13 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | +| `addon.arrange.artboardGuides` | `offset` pt −1000000…1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside); `artboards` [index…] (0-based; the active artboard); `artboard` index (the active artboard, which the app passes; the view's when left out, and the journal then records it for a replay); `all` (false; true: every artboard; not with `artboards`) | Adds a rectangular guide path around each of those artboards, `offset` from its edges, on the topmost top-level layer named Artboard Guides (made above the other layers when there is none; it keeps its lock and visibility). It acts on artboards, not on the selection. The guides have the current paint, which `view.guides.release` gives back with the path. A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. An inset that leaves an artboard no width or no height, and a guide edge more than 4,000,000 pt from the origin, are errors. Off without artboards. → `{ids, layer, skipped}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, -and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs +and fails with nothing selected. Add Artboard Guides… opens a dialog with Offset and Artboards (Active Artboard, or All +Artboards, which sends `all: true`) and a Preview; for Active Artboard it sends the artboard the view showed when the +dialog opened as `artboard`. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. @@ -17452,6 +17456,7 @@ fields are the command's parameters, with Preview (Randomize Opacity's seed, and {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} +{"name":"run_command","arguments":{"command":"addon.arrange.artboardGuides","params":{"offset":-18,"all":true}}} ``` ## Document Tools add-on diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..57c5ac4ae1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3156,6 +3156,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Sort Objects… sorts the top-level selected objects (or `ids`, at most 20000) by one attribute (width, height, area, x or y position, opacity or stacking order; small to large, large to small, or a random order from a seed) and gives them another in that order, the first the smallest value: the objects trade the values they have, or with Distribute Evenly the values step evenly from the smallest to the largest. Lining objects up left to right by size, restacking them so the largest is at the back, or giving them heights that step with their x position are each one run. Sizes and places are measured and set as `object.setBounds` measures them (Use Preview Bounds); a width, height or area changes about each object's centre (an area in proportion), and stacking order trades places only among objects of the same layer or group. One undo step; no step when nothing changes. Tests: `sort_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each attribute sorted by and applied, both directions, distribute, layers kept apart, the seeded random order, `ids`, no step when in order, bad params), `sort_objects_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Add Artboard Guides (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at the Offset typed: more than 0 puts it outside the artboard (a bleed line), less than 0 inside it (a safe-area line). The guides go on a top-level layer named Artboard Guides, made above the others the first time and reused after that with its lock and visibility as they are; a guide already anywhere in that layer with the same rectangle is not added again. The dialog acts on the artboard the view shows. One undo step; no step when nothing is added. An inset that leaves an artboard no width or no height is refused. `addon.arrange.artboardGuides` also takes a list of artboards. Tests: `cmd::addons::arrange::artboard_guides::tests` in `vectorcraft-engine` (outside and inside offsets, the active artboard and the one the journal records, every artboard and listed ones, the layer reused with its lock and visibility, no repeat and no step, a guide grouped inside the layer, Release Guides, bad params and too large an inset refused, off without artboards), `real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step`, `add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset` and `add_artboard_guides_uses_the_artboard_the_view_shows` in `vectorcraft-ui-egui`, and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 453bda832d..82ff2667eb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -567,6 +567,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard or every artboard at an Offset (outside when more than 0, inside when less) on a reused Artboard Guides layer; a guide already there is not repeated; an inset that leaves no width or height is refused; Preview; one undo step | done | `addon.arrange.artboardGuides`, `crates/engine/src/cmd/addons/arrange/artboard_guides.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | From 4fed06a3a68479bbfc6ac2f221ba61df3e18cf91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:02:20 -0800 Subject: [PATCH 2/7] MCP: ui.menuDialog's params text lists addon.arrange.artboardGuides Add Artboard Guides opens its dialog through ui.menuDialog, but the command list in the params text (ui_commands.rs and the MCP catalog) left it out, so menu_dialog_params_text_lists_every_command_whose_dialog_it_opens failed. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..66d931f39f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..d0adeef1b8 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 04198e416ea74c17de6aae95d93c7821819f83ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:17:29 -0800 Subject: [PATCH 3/7] Add Artboard Guides: a guide drawn from another corner is a duplicate, and the dialog needs an artboard A guide already on the Artboard Guides layer with the same four corners is skipped whichever corner its path starts from and whichever way it runs. The dialog no longer opens on a document without artboards; ui.menuDialog returns an error instead. --- .../src/cmd/addons/arrange/artboard_guides.rs | 29 ++++++++++++++++--- .../addons/arrange/artboard_guides/tests.rs | 23 ++++++++++++++- crates/ui-egui/src/addons/arrange.rs | 3 ++ crates/ui-egui/src/addons/arrange/tests.rs | 9 ++++++ docs/mcp.md | 3 +- 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 69231b1f8e..862eef710e 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -7,7 +7,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; use super::super::super::panelcmds::{artboard_at, listed_artboards}; use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; @@ -51,18 +51,39 @@ fn guide_layer(d: &Document) -> Option { d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) } -/// Does `layer` already hold a guide path drawn as `rect` is? +/// Does `layer` already hold a guide path with `rect`'s four corners, starting at any corner and +/// running either way round? fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { - let path = shapes::rectangle(rect); + let r = rect.abs(); + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; layer.and_then(|id| d.node(id)).is_some_and(|n| { let mut found = false; n.walk(&mut |c| { - found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if *p == path); + found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)); }); found }) } +/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? +fn traces(path: &PathData, corners: &[Point; 4]) -> bool { + let [sp] = &path.subpaths[..] else { return false }; + if !sp.closed || sp.anchors.len() != 4 { + return false; + } + let anchors: Vec<&Anchor> = sp.anchors.iter().collect(); + let [first, second, ..] = anchors[..] else { return false }; + if anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { + return false; + } + let (Some(start), Some(next)) = (corners.iter().position(|&c| c == first.p), corners.iter().position(|&c| c == second.p)) else { + return false; + }; + // 1 runs the way `corners` does, 3 the other way. + let step = (next + 4 - start) % 4; + (step == 1 || step == 3) && anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) +} + fn artboard_guides(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?; diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs index 5b8093b07e..ba345a85ca 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; -use vectorcraft_geom::Rect; +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; use super::{COMMAND, LAYER}; use crate::Session; @@ -145,6 +145,27 @@ fn a_guide_grouped_inside_the_layer_is_not_added_again() { assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); } +#[test] +fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0).inflate(5.0, 5.0); + let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)]; + // Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one. + for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] { + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = PathData::single(SubPath::polyline(&points, true)); + } + let n = steps(&s); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}"); + assert_eq!(steps(&s), n); + } +} + #[test] fn release_guides_gives_back_a_rectangle_path() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 6aad8c5fbb..224cbddf50 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -249,6 +249,9 @@ fn guides_params(fields: &DialogFields) -> Value { pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option> { let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?; let st = app.session.active()?; + if command == GUIDES && st.doc.artboards.is_empty() { + return Some(Err("the document has no artboards".into())); + } let strokes = app.session.prefs.scale_strokes; let key = st.selection.key.is_some(); let lengths = general_lengths(app); diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 924c3064a7..e659e2ee79 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -232,6 +232,15 @@ fn add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_i assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); } +#[test] +fn add_artboard_guides_does_not_open_without_artboards() { + let (mut app, _, _) = app(); + std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).artboards.clear(); + let opened = crate::addons::dialogs::open_from_menu(&mut app, "addon.arrange.artboardGuides"); + assert!(matches!(opened, Some(Err(_))), "{opened:?}"); + assert!(!app.any_dialog_open()); +} + #[test] fn add_artboard_guides_uses_the_artboard_the_view_shows() { let (mut app, _, _) = app(); diff --git a/docs/mcp.md b/docs/mcp.md index aad5c88e8c..ab10050e91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17751,7 +17751,8 @@ Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mod active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Add Artboard Guides… opens a dialog with Offset and Artboards (Active Artboard, or All Artboards, which sends `all: true`) and a Preview; for Active Artboard it sends the artboard the view showed when the -dialog opened as `artboard`. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs +dialog opened as `artboard`. It does not open, and `ui.menuDialog` returns an error, when the document has no +artboards. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`; each dialog's `key` is its command id, such as `addon.arrange.grid`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. Match Objects… opens a dialog of its own in the same way, keyed by its command, whose fields are the command's From 0b5e647aa1bc302bb880b466047c8611d08e4e18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:35:02 -0800 Subject: [PATCH 4/7] Add Artboard Guides: the duplicate check stops at the first match without allocating ui.menuDialog's params text and the progress line say the dialog needs an artboard. --- .../src/cmd/addons/arrange/artboard_guides.rs | 23 +++++++++++-------- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 862eef710e..4c4f42d719 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -7,7 +7,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{PathData, Point, Rect, shapes}; use super::super::super::panelcmds::{artboard_at, listed_artboards}; use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; @@ -57,11 +57,14 @@ fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { let r = rect.abs(); let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; layer.and_then(|id| d.node(id)).is_some_and(|n| { - let mut found = false; - n.walk(&mut |c| { - found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)); - }); - found + n.try_walk(&mut |c| { + if matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)) { + std::ops::ControlFlow::Break(()) + } else { + std::ops::ControlFlow::Continue(()) + } + }) + .is_break() }) } @@ -71,9 +74,9 @@ fn traces(path: &PathData, corners: &[Point; 4]) -> bool { if !sp.closed || sp.anchors.len() != 4 { return false; } - let anchors: Vec<&Anchor> = sp.anchors.iter().collect(); - let [first, second, ..] = anchors[..] else { return false }; - if anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { + let mut anchors = sp.anchors.iter(); + let (Some(first), Some(second)) = (anchors.next(), anchors.next()) else { return false }; + if sp.anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { return false; } let (Some(start), Some(next)) = (corners.iter().position(|&c| c == first.p), corners.iter().position(|&c| c == second.p)) else { @@ -81,7 +84,7 @@ fn traces(path: &PathData, corners: &[Point; 4]) -> bool { }; // 1 runs the way `corners` does, 3 the other way. let step = (next + 4 - start) % 4; - (step == 1 || step == 3) && anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) + (step == 1 || step == 3) && sp.anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) } fn artboard_guides(s: &mut Session, p: &Value) -> Result { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 66d931f39f..6bb92bc665 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d0adeef1b8..c19d0a4401 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6973a56d11..77ed9f6a3c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3158,7 +3158,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Arrange Tools add-on: Add Artboard Guides (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at the Offset typed: more than 0 puts it outside the artboard (a bleed line), less than 0 inside it (a safe-area line). The guides go on a top-level layer named Artboard Guides, made above the others the first time and reused after that with its lock and visibility as they are; a guide already anywhere in that layer with the same rectangle is not added again. The dialog acts on the artboard the view shows. One undo step; no step when nothing is added. An inset that leaves an artboard no width or no height is refused. `addon.arrange.artboardGuides` also takes a list of artboards. Tests: `cmd::addons::arrange::artboard_guides::tests` in `vectorcraft-engine` (outside and inside offsets, the active artboard and the one the journal records, every artboard and listed ones, the layer reused with its lock and visibility, no repeat and no step, a guide grouped inside the layer, Release Guides, bad params and too large an inset refused, off without artboards), `real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step`, `add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset` and `add_artboard_guides_uses_the_artboard_the_view_shows` in `vectorcraft-ui-egui`, and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at the Offset typed: more than 0 puts it outside the artboard (a bleed line), less than 0 inside it (a safe-area line). The guides go on a top-level layer named Artboard Guides, made above the others the first time and reused after that with its lock and visibility as they are; a guide already anywhere in that layer with the same rectangle, from whichever corner and in whichever direction its path runs, is not added again. The dialog acts on the artboard the view shows. One undo step; no step when nothing is added. The dialog does not open, and `ui.menuDialog` returns an error, when the document has no artboards. An inset that leaves an artboard no width or no height is refused. `addon.arrange.artboardGuides` also takes a list of artboards. Tests: `cmd::addons::arrange::artboard_guides::tests` in `vectorcraft-engine` (outside and inside offsets, the active artboard and the one the journal records, every artboard and listed ones, the layer reused with its lock and visibility, no repeat and no step, a guide grouped inside the layer, a guide drawn from another corner or the other way round, Release Guides, bad params and too large an inset refused, off without artboards), `real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step`, `add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset`, `add_artboard_guides_does_not_open_without_artboards` and `add_artboard_guides_uses_the_artboard_the_view_shows` in `vectorcraft-ui-egui`, and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Offset Objects (2026-11-29) From 75d3fbca6213353b1edafa4cc3b054ccff2e8ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:43:59 -0800 Subject: [PATCH 5/7] Arrange Tools: Add Artboard Guides keeps its artboard and matches guides with extra anchors The dialog keeps the opening artboard's id and resolves its index for Preview and OK, so reordering artboards while it is open no longer moves the guide to another artboard, and a deleted artboard is an error with no undo step. A guide rectangle with collinear anchors along its sides counts as the same rectangle. Each run walks the guides layer once. The dialog's menu item is available without a selection. --- .../src/cmd/addons/arrange/artboard_guides.rs | 67 +++++++++++----- .../addons/arrange/artboard_guides/tests.rs | 48 +++++++++++ crates/ui-egui/src/addons/arrange.rs | 22 +++++- crates/ui-egui/src/addons/arrange/tests.rs | 79 +++++++++++++++++++ crates/ui-egui/src/addons/dialogs.rs | 34 ++++++-- crates/ui-egui/src/menus/state.rs | 8 +- docs/mcp.md | 5 ++ 7 files changed, 232 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 4c4f42d719..98c6598d87 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -5,6 +5,8 @@ #[cfg(test)] mod tests; +use std::collections::HashSet; + use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, Rect, shapes}; @@ -51,40 +53,64 @@ fn guide_layer(d: &Document) -> Option { d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) } -/// Does `layer` already hold a guide path with `rect`'s four corners, starting at any corner and -/// running either way round? -fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { - let r = rect.abs(); - let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; - layer.and_then(|id| d.node(id)).is_some_and(|n| { - n.try_walk(&mut |c| { - if matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)) { - std::ops::ControlFlow::Break(()) - } else { - std::ops::ControlFlow::Continue(()) +/// `r`'s corners as an exact hash key, whichever way round `r` runs. +fn rect_key(r: Rect) -> [u64; 4] { + let r = r.abs(); + [r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() }) +} + +#[cfg(test)] +thread_local! { + static GUIDE_NODES_VISITED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { + let mut rects = HashSet::new(); + if let Some(n) = layer.and_then(|id| d.node(id)) { + n.walk(&mut |c| { + #[cfg(test)] + GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1)); + if let NodeKind::Path { path, guide: true, .. } = &c.kind + && let Some(r) = path.bounds() + { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + if traces(path, &corners) { + rects.insert(rect_key(r)); + } } - }) - .is_break() - }) + }); + } + rects } /// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? fn traces(path: &PathData, corners: &[Point; 4]) -> bool { let [sp] = &path.subpaths[..] else { return false }; - if !sp.closed || sp.anchors.len() != 4 { + if !sp.closed || sp.anchors.len() < 4 { return false; } - let mut anchors = sp.anchors.iter(); - let (Some(first), Some(second)) = (anchors.next(), anchors.next()) else { return false }; if sp.anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { return false; } - let (Some(start), Some(next)) = (corners.iter().position(|&c| c == first.p), corners.iter().position(|&c| c == second.p)) else { + let points: Vec = sp + .anchors + .iter() + .enumerate() + .filter_map(|(i, a)| { + let prev = sp.anchors[(i + sp.anchors.len() - 1) % sp.anchors.len()].p; + let next = sp.anchors[(i + 1) % sp.anchors.len()].p; + let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y)) + || (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x)); + (!interior).then_some(a.p) + }) + .collect(); + let [first, second, _, _] = &points[..] else { return false }; + let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else { return false; }; // 1 runs the way `corners` does, 3 the other way. let step = (next + 4 - start) % 4; - (step == 1 || step == 3) && sp.anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) + (step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4]) } fn artboard_guides(s: &mut Session, p: &Value) -> Result { @@ -113,6 +139,7 @@ fn artboard_guides(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let d = &st.doc; let layer = guide_layer(d); + let mut existing = guide_rectangles(d, layer); let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0); for i in indices { let Some(board) = d.artboards.get(i) else { continue }; @@ -123,7 +150,7 @@ fn artboard_guides(s: &mut Session, p: &Value) -> Result { if !rect_in_range(r) { return Err(bad(C, "the guide would reach past the edge of the canvas")); } - if holds_guide(d, layer, r) || rects.contains(&r) { + if !existing.insert(rect_key(r)) { skipped += 1; } else { rects.push(r); diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs index ba345a85ca..3013130f3f 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -166,6 +166,54 @@ fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() } } +#[test] +fn collinear_midpoints_do_not_add_another_guide_or_history_step() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let points = [ + Point::new(b.center().x, b.y0), + Point::new(b.x1, b.y0), + Point::new(b.x1, b.center().y), + Point::new(b.x1, b.y1), + Point::new(b.center().x, b.y1), + Point::new(b.x0, b.y1), + Point::new(b.x0, b.center().y), + Point::new(b.x0, b.y0), + ]; + for reverse in [false, true] { + let mut points = points.to_vec(); + if reverse { + points.reverse(); + } + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(SubPath::polyline(&points, true)); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1})); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } +} + +#[test] +fn every_artboard_shares_one_walk_of_existing_guides() { + let mut s = session(); + s.execute(COMMAND, &json!({"all": true})).unwrap(); + super::GUIDE_NODES_VISITED.with(|count| count.set(0)); + s.execute(COMMAND, &json!({})).unwrap(); + let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0)); + assert!(single > 0); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"all": true})).unwrap(); + assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single); + assert!(ids(&r).is_empty()); + assert_eq!(r["skipped"], json!(2)); + assert_eq!(steps(&s), n); +} + #[test] fn release_guides_gives_back_a_rectangle_path() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 9ef6be163a..df763b4425 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -276,12 +276,26 @@ fn guides_params(fields: &DialogFields) -> Value { let all = fields.text("scope") == Some("all"); params.remove("scope"); if all { - params.remove("artboard"); + params.remove("artboardId"); } params.insert("all".into(), json!(all)); Value::Object(params) } +pub(super) fn resolve_guides_artboard(app: &VectorcraftApp, params: &mut Value) -> Result<(), String> { + if params["all"] == true { + return Ok(()); + } + let id = params["artboardId"].as_u64(); + let index = app.session.active().and_then(|st| st.doc.artboards.iter().position(|a| Some(u64::from(a.id)) == id)); + let Some(index) = index else { return Err("The artboard no longer exists.".into()) }; + if let Some(params) = params.as_object_mut() { + params.remove("artboardId"); + params.insert("artboard".into(), json!(index)); + } + Ok(()) +} + /// Opens the dialog of command `id` on the active document; `None` for another command and without a document. pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option> { let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?; @@ -322,10 +336,12 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option ( guides_rows(lengths), - json!({ "offset": 0, "scope": "active", "artboard": crate::panels::artboards::selected(app, st.doc.artboards.len()) }), + json!({ + "offset": 0, "scope": "active", + "artboardId": st.doc.artboards.get(crate::panels::artboards::selected(app, st.doc.artboards.len())).map(|a| a.id), + }), ), MARKS => (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })), // The first selected object's size, as the command measures it (a side it lacks: the least). diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index fa360d6f6e..2e9beac838 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -241,6 +241,85 @@ fn add_artboard_guides_does_not_open_without_artboards() { assert!(!app.any_dialog_open()); } +#[test] +fn add_artboard_guides_keeps_the_opening_artboard_after_reordering() { + for preview in [false, true] { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + app.view_mut().unwrap().artboard = 0; + let board = app.session.doc().unwrap().doc.artboards[0].rect; + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "preview", json!(preview)); + if preview { + host::frame(&mut app); + app.session.cancel_interaction().unwrap(); + } + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + let n = steps(&app); + if preview { + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![board]); + assert_eq!(steps(&app), n); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![board]); + assert_eq!(steps(&app), n + 1); + } +} + +#[test] +fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() { + for preview in [false, true] { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + app.view_mut().unwrap().artboard = 0; + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "preview", json!(preview)); + if preview { + host::frame(&mut app); + app.session.cancel_interaction().unwrap(); + } + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let (before, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + if preview { + host::frame(&mut app); + assert!(artboard_guides(&app).is_empty()); + assert_eq!(steps(&app), n); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(artboard_guides(&app).is_empty()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(steps(&app), n); + assert_eq!(app.ui.status, "The artboard no longer exists."); + } +} + +#[test] +fn artboard_guides_menu_dialog_is_available_without_a_selection() { + let (mut app, _, _) = app(); + app.run("select.none", json!({})).unwrap(); + assert!(menus::enabled(&app, "ui.menuDialog")); + let guides = json!({"command": "addon.arrange.artboardGuides"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &guides).map(|s| s.0), Some(true)); + let transform = json!({"command": "object.move"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(false)); + let grid = json!({"command": "addon.arrange.grid"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(false)); + app.run("select.all", json!({})).unwrap(); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(true)); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(true)); + app.run("select.none", json!({})).unwrap(); + app.run("ui.menuDialog", guides).unwrap(); + let id = host::dialog_id(&app); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![app.session.doc().unwrap().doc.artboards[0].rect]); +} + #[test] fn add_artboard_guides_uses_the_artboard_the_view_shows() { let (mut app, _, _) = app(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 18816efa11..0d21c2dc32 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -29,6 +29,16 @@ pub(crate) struct Spec { pub found: Option, } +impl Spec { + fn params(&self, app: &VectorcraftApp, fields: &DialogFields) -> Result { + let mut params = (self.params)(fields); + if self.command == "addon.arrange.artboardGuides" { + super::arrange::resolve_guides_artboard(app, &mut params)?; + } + Ok(params) + } +} + /// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document. #[derive(Default)] pub(crate) struct AddonDialogs { @@ -140,11 +150,19 @@ fn pump_commit(app: &mut VectorcraftApp) { app.addon_dialogs.preview = LivePreview::default(); app.addon_dialogs.preview_error = None; } - let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); + let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), spec.params(app, d.fields())))); if on_document && let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); - let answer = preview.run(app, *previewing, label, spec.command, params); + let answer = match params { + Ok(params) => preview.run(app, *previewing, label, spec.command, params), + Err(error) => { + preview.cancel(app); + preview = LivePreview::default(); + app.status(error.clone()); + Some(Err(error.clone())) + } + }; app.addon_dialogs.preview = preview; if spec.command == super::select::points_only::COMMAND { match &answer { @@ -171,11 +189,13 @@ fn pump_commit(app: &mut VectorcraftApp) { } else if !on_document { app.status("The add-on settings apply only to the drawing where the dialog opened."); } else { - let params = (spec.params)(&result.fields); - let answer = if spec.command == super::select::points_only::COMMAND { - preview.commit_selection(app, spec.command, params) - } else { - preview.commit(app, spec.command, params) + let answer = match spec.params(app, &result.fields) { + Ok(params) if spec.command == super::select::points_only::COMMAND => preview.commit_selection(app, spec.command, params), + Ok(params) => preview.commit(app, spec.command, params), + Err(error) => { + preview.cancel(app); + Err(error) + } }; if let Err(error) = answer { app.status(error); diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 6ae7c66be0..a174769e60 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -186,6 +186,12 @@ pub(crate) fn shown_state_with( why_off: &mut dyn FnMut(&str) -> Option>, ) -> Option<(bool, Option)> { let en = why_off(id).is_none() + && (id != "ui.menuDialog" + || if p.get("command").and_then(Value::as_str) == Some("addon.arrange.artboardGuides") { + why_off("addon.arrange.artboardGuides").is_none() + } else { + app.session.active().is_some_and(|d| !d.selection.is_empty()) + }) && (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(id, why_off) || east_asian_hidden(app, id) { @@ -416,7 +422,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.saveBrushLibrary" => crate::panels::brushes::has_brushes(app), id if id.starts_with(crate::panels::brushes::USER_SLOT) => crate::panels::brushes::user_library(app, id).is_some(), "ui.spotColors" => app.session.active().is_some(), - "ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()), + "ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty() || !d.doc.artboards.is_empty()), "ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app), "ui.smoothAuto" => crate::dialogs::smooth_slider::showing(app), "ui.recolorUndo" => crate::dialogs::recolor::can_step(app, true), diff --git a/docs/mcp.md b/docs/mcp.md index 705f10c92d..a619275594 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17990,6 +17990,11 @@ with strokes and vector effects included and raster effects left out (see its ro | `addon.arrange.artboardGuides` | `offset` pt −1000000…1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside); `artboards` [index…] (0-based; the active artboard); `artboard` index (the active artboard, which the app passes; the view's when left out, and the journal then records it for a replay); `all` (false; true: every artboard; not with `artboards`) | Adds a rectangular guide path around each of those artboards, `offset` from its edges, on the topmost top-level layer named Artboard Guides (made above the other layers when there is none; it keeps its lock and visibility). It acts on artboards, not on the selection. The guides have the current paint, which `view.guides.release` gives back with the path. A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. An inset that leaves an artboard no width or no height, and a guide edge more than 4,000,000 pt from the origin, are errors. Off without artboards. → `{ids, layer, skipped}` | | `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | +`ui.menuDialog {command: "addon.arrange.artboardGuides"}` is available without a selection. The dialog keeps the +opening artboard's id and resolves its current index for Preview and OK. If that artboard was deleted, Preview and +OK report an error without adding a guide or an undo step. A guide with extra anchors along its sides counts as the +same rectangle. + Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Add Artboard Guides… opens a dialog with Offset and Artboards (Active Artboard, or All From fa659626b948063af57b3929c94d64d003ed0561 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:58:07 -0800 Subject: [PATCH 6/7] Docs: the deleted-artboard error applies to Active Artboard only With All Artboards, Add Artboard Guides acts on the artboards the document has when Preview or OK runs, so a deleted opening artboard is not an error there. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index a619275594..ab24cc4fa6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17991,8 +17991,9 @@ with strokes and vector effects included and raster effects left out (see its ro | `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | `ui.menuDialog {command: "addon.arrange.artboardGuides"}` is available without a selection. The dialog keeps the -opening artboard's id and resolves its current index for Preview and OK. If that artboard was deleted, Preview and -OK report an error without adding a guide or an undo step. A guide with extra anchors along its sides counts as the +opening artboard's id and resolves its current index for Preview and OK. With Active Artboard, if that artboard was +deleted, Preview and OK report an error without adding a guide or an undo step; All Artboards acts on the artboards +the document has then. A guide with extra anchors along its sides counts as the same rectangle. Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the From dc8460b909463883e7d8940934b71db7f49d8b49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:44:59 -0800 Subject: [PATCH 7/7] Artboard Guides: a guide with straight handled sides is not added again An existing guide rectangle whose anchors carry handles along its sides (an extra anchor on a side with handles on that side, or a handle past a corner on a segment that still runs one way) traced the rectangle but was rejected, so the command added a duplicate guide. A segment now counts as straight when its handles lie on the side's line and the curve never turns back along it, and the rectangle is taken from the anchors instead of the curve bounds. Handles off the side still do not match. --- .../src/cmd/addons/arrange/artboard_guides.rs | 31 +++++++++++++-- .../addons/arrange/artboard_guides/tests.rs | 38 +++++++++++++++++++ 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 98c6598d87..d849047fb9 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -9,7 +9,7 @@ use std::collections::HashSet; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; -use vectorcraft_geom::{PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; use super::super::super::panelcmds::{artboard_at, listed_artboards}; use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; @@ -70,9 +70,12 @@ fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { n.walk(&mut |c| { #[cfg(test)] GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1)); + // The anchors' bounds: `traces` only accepts segments that stay between their anchors. if let NodeKind::Path { path, guide: true, .. } = &c.kind - && let Some(r) = path.bounds() + && let [sp] = &path.subpaths[..] + && let Some(first) = sp.anchors.first() { + let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p)); let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; if traces(path, &corners) { rects.insert(rect_key(r)); @@ -83,13 +86,35 @@ fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { rects } +/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b` +/// without turning back? Its handles lie on that line, and the curve's position along it never reverses. +fn straight(a: &Anchor, b: &Anchor) -> bool { + let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| { + if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) { + return false; + } + let s = (f(b.p) - f(a.p)).signum(); + let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s); + // The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1]. + let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2); + let curve = u - 2.0 * v + w; + let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 }; + u >= 0.0 && w >= 0.0 && vertex >= 0.0 + }; + if a.p == b.p { + return a.h_out == a.p && b.h_in == a.p; + } + along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x) +} + /// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? fn traces(path: &PathData, corners: &[Point; 4]) -> bool { let [sp] = &path.subpaths[..] else { return false }; if !sp.closed || sp.anchors.len() < 4 { return false; } - if sp.anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { + let n = sp.anchors.len(); + if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) { return false; } let points: Vec = sp diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs index 3013130f3f..5152dcffe9 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -198,6 +198,44 @@ fn collinear_midpoints_do_not_add_another_guide_or_history_step() { } } +#[test] +fn handles_along_a_side_still_match_and_handles_off_it_do_not() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let mid = Point::new(b.center().x, b.y0); + let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)]; + let corner = points[1]; + let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| { + let mut sp = SubPath::polyline(&points, true); + sp.anchors[0].h_in = h_in; + sp.anchors[0].h_out = h_out; + sp.anchors[1].h_in = corner_in; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(sp); + }; + // The extra anchor's handles lie along the top side: the guide still matches. + // Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths). + let eighth = (corner.x - mid.x) / 8.0; + for (h_out, corner_in) in + [(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))] + { + set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } + // A handle off the side bends it: the path is not that guide, so one is added. + set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner); + let other = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(other["skipped"], json!(0)); + assert_eq!(ids(&other).len(), 1); +} + #[test] fn every_artboard_shares_one_walk_of_existing_guides() { let mut s = session();