diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index ba09a537a7..ab7a3808ce 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -8,10 +8,12 @@ //! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their //! visual bounds share, 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. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object. +//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object, +//! and 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; pub mod marks; #[cfg(test)] mod tests; @@ -144,6 +146,7 @@ pub fn specs() -> Vec { ), ] .into_iter() + .chain(artboard_guides::specs()) .chain(marks::specs()) .collect() } 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..d849047fb9 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -0,0 +1,202 @@ +//! 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 std::collections::HashSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +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}; +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) +} + +/// `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)); + // The anchors' bounds: `traces` only accepts segments that stay between their anchors. + if let NodeKind::Path { path, guide: true, .. } = &c.kind + && 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)); + } + } + }); + } + 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; + } + 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 + .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) && points.iter().enumerate().all(|(k, p)| *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)?; + 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 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 }; + 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 !existing.insert(rect_key(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..5152dcffe9 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -0,0 +1,312 @@ +//! 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::{PathData, Point, Rect, SubPath}; + +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 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 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 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(); + 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(); + 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 94565b3ce8..c35ad702f4 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 5f970bb568..b08207d904 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.groupRows", diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 753c315a9a..e3bbe41d23 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; 10] = [ +/// 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; 11] = [ + "addon.arrange.artboardGuides", "edit.copy", "edit.cut", "edit.pasteInPlace", @@ -37,10 +39,11 @@ 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); 38] = [ +const REPLAY_ONLY: [(&str, &str); 39] = [ ("edit.copy", "artboard"), ("edit.cut", "artboard"), ("file.new", "created"), + ("addon.arrange.artboardGuides", "artboard"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), ("file.saveAs", "modified"), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 62d9ac97f8..55f6b4518c 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1555,7 +1555,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.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index ea78593400..df763b4425 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, Offset Objects, Replace with Top Object, Set Size of Each, Match Objects, Group by Row, Randomize -//! Opacity, Sort Objects and Mark Bounds of Each, 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. +//! Opacity, Sort Objects, Add Artboard Guides and Mark Bounds of Each, 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; @@ -29,9 +30,10 @@ const MATCH: &str = "addon.arrange.match"; const ROWS: &str = "addon.arrange.groupRows"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; +const GUIDES: &str = "addon.arrange.artboardGuides"; const MARKS: &str = "addon.arrange.markBounds"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 9] = [ +const DIALOGS: [(&str, &str); 10] = [ (GRID, "Arrange in Grid"), (OFFSET, "Offset Objects"), (REPLACE, "Replace with Top Object"), @@ -40,8 +42,11 @@ const DIALOGS: [(&str, &str); 9] = [ (ROWS, "Group by Row"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), + (GUIDES, "Add Artboard Guides"), (MARKS, "Mark Bounds of Each"), ]; +/// The artboards Add Artboard Guides puts guides around: `all` false or true. +const SCOPES: [(&str, &str); 2] = [("active", "Active Artboard"), ("all", "All Artboards")]; /// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights. const MARK_LENGTHS: std::ops::RangeInclusive = 0.001..=1e6; const WEIGHTS: std::ops::RangeInclusive = 0.01..=1000.0; @@ -77,6 +82,7 @@ pub fn menu() -> Vec { c("Group by Row…", ROWS), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), + c("Add Artboard Guides…", GUIDES), c("Mark Bounds of Each…", MARKS), Sep, cp("Zoom to Selection", ZOOM, json!({})), @@ -91,6 +97,7 @@ static MATCH_SPEC: Spec = Spec { command: MATCH, params: match_params, found: No static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_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 }; static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None }; /// The dialog over `rows`, titled by the heading of `command`. @@ -201,6 +208,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 marks_rows(lengths: LengthUnits) -> Vec { let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")]; let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")]; @@ -258,10 +270,39 @@ 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("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)?; 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); @@ -295,6 +336,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option ( + guides_rows(lengths), + 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). _ => { @@ -328,6 +376,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))), MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_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); diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 6c68fa385b..2e9beac838 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -164,6 +164,182 @@ 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_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_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(); + 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"); +} + /// The objects of the first layer, from the back. fn stacking(panel: &Harness) -> Vec { panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index ecbcf6856d..02f9745b5d 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 { @@ -141,11 +151,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 { @@ -172,11 +190,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/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 818863408d..f7fb6b2ba1 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -124,10 +124,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/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 63683cca2f..21792ec792 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/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ebdb694870..be4a65ce83 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1556,7 +1556,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.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.commonTangents|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.type.numbers|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.color.randomFill|addon.select.byArtboards|addon.select.editPointsOnly|addon.document.floodFillArtboards|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, `addon.pathtools.commonTangents` for addon.pathtools.bridge, `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; addon.document.floodFillArtboards is refused, with the command's reason, while that command is disabled (for example with no document open); 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/mcp.md b/docs/mcp.md index 5ce1fd6cfd..52bb158dd9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4032,7 +4032,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. Once the script has called `setActiveArtboardIndex` on that document, it is the artboard the script chose while that artboard exists. If it @@ -18856,11 +18857,21 @@ records the value used, and a replay of that entry scales corners the same way w | `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more 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`; `corners` (the Scale Corners preference); `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}` | | `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, clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or clipping pieces group) that holds it, so a blend key or compound shape operand gets its marks outside the live object. In isolation mode, an object whose marks would go outside the isolated art is an error that makes no step. Selected parts of compound paths, envelopes, meshes, repeats, Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. 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. 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 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`. 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 @@ -18878,6 +18889,7 @@ Draw is Corner Marks. {"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.match","params":{"source":"key","size":"both","rotate":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 1e9bbb5050..e0d4005c60 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3198,6 +3198,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, 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) A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. An object aligned to the pixel grid snaps to it after it moves, so the gap before it can differ from the requested gap, and the next one starts from where it snapped. An Objects on Path group is measured with its members put back on the path after it moves. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 367cfeb413..aca8b4b68c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -196,9 +196,9 @@ tools, never checked side by side) isn't captured row by row. ## Headless (RFC-0052) -**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 368 unknown.** +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 369 unknown.** -Every parity table on this page has a Headless column: the Summary table (12 area rows, including the overall row) and the behaviour tables (356 rows). Every row is `unknown` until it is checked. A checked row may be marked `no ()` or `partial ()` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the row cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows. +Every parity table on this page has a Headless column: the Summary table (12 area rows, including the overall row) and the behaviour tables (357 rows). Every row is `unknown` until it is checked. A checked row may be marked `no ()` or `partial ()` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the row cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows. ## Pen, Curvature and anchor tools @@ -588,6 +588,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 | unknown | | 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 | unknown | | 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 | unknown | +| 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 | unknown | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | unknown | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws inward Corner Marks or a Rectangle on each selected object's Geometric Bounds or Visual Bounds, with Length, Weight, Color and Preview. Marks go above the object or its outermost clip group, clipping sublayer or live object and become selected in one undo step. Marks that would go outside isolated art cause an error without an undo step. Selected parts of compound paths, envelopes, meshes, repeats, Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. | done | `addon.arrange.markBounds`, `crates/engine/src/cmd/addons/arrange/marks.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | unknown | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group by Row… groups the selected objects whose visual bounds overlap from top to bottom into one group for each row, or with Group By Columns from left to right (within one layer or group and one artboard), each group at its frontmost member's stacking place; Preview; one undo step | done | `addon.arrange.groupRows`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | unknown |