From 75d3fbca6213353b1edafa4cc3b054ccff2e8ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:43:59 -0800 Subject: [PATCH] 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