mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 20:38:21 +00:00
Merge pull request #6909 from dotCooCoo/feat/align-artboards
Align: the Align panel aligns and distributes the selected artboards
This commit is contained in:
@@ -0,0 +1,262 @@
|
||||
//! Align and Distribute for artboards: what the Align panel's buttons run while the Artboard tool
|
||||
//! is chosen.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::Scaling;
|
||||
use vectorcraft_geom::{Rect, Vec2};
|
||||
|
||||
use super::object::choice;
|
||||
use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards};
|
||||
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or};
|
||||
use crate::EngineError;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"artboard.align",
|
||||
"Align",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}",
|
||||
has_doc,
|
||||
align
|
||||
),
|
||||
cmd!(
|
||||
"artboard.distribute",
|
||||
"Distribute",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards? (as artboard.align), horizontal?: \"left\"|\"center\"|\"right\" | vertical?: \"top\"|\"center\"|\"bottom\" (one is needed; horizontal goes first), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.align; with `spacing` the artboard must be one of those distributed), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Objects with the Artboard tool chosen) the named edges or centers of the artboards are spaced evenly between the first and the last along the axis, which stay where they are (three or more artboards); with to: \"artboard\", the artboards are spaced the same way and then moved together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the edges or centers are placed `spacing` apart, outward from it in their order (two or more); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}",
|
||||
has_doc,
|
||||
distribute
|
||||
),
|
||||
cmd!(
|
||||
"artboard.distributeSpacing",
|
||||
"Distribute Spacing",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards? (as artboard.align), axis?: \"horizontal\"|\"vertical\" (default horizontal), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.distribute), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Spacing with the Artboard tool chosen) the gaps between the artboards along the axis become equal, the first and the last staying where they are (three or more artboards); with to: \"artboard\", the gaps become equal the same way and the artboards then move together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the others are placed with a gap of `spacing` between neighbors (two or more; a negative spacing overlaps them); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}",
|
||||
has_doc,
|
||||
distribute_spacing
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// What an artboard Align or Distribute command acts on, read from its params.
|
||||
struct Boards {
|
||||
/// The artboards named, in artboard order, each with its rectangle.
|
||||
items: Vec<(usize, Rect)>,
|
||||
/// With `to: "artboard"`, the artboard to align to and its rectangle.
|
||||
reference: Option<(usize, Rect)>,
|
||||
/// Whether the art inside each artboard moves with it.
|
||||
move_art: bool,
|
||||
/// Whether locked and hidden art moves too.
|
||||
locked_art: bool,
|
||||
}
|
||||
|
||||
/// Reads the params that `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing`
|
||||
/// (command `cmd`) share, and adds the artboards and the art choice to the journal entry. The
|
||||
/// artboard to align to is `artboard`, else `activeArtboard` (a replay of the journal), else the
|
||||
/// Artboard tool's active one, which the journal entry then records as `activeArtboard`. It fails
|
||||
/// when every artboard named is locked.
|
||||
fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
|
||||
check_switches(p, &["patterns"], cmd)?;
|
||||
let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard");
|
||||
let indices = named_or_selected(s, p, cmd)?;
|
||||
let given = |key: &str| -> Result<Option<usize>> {
|
||||
match p.get(key).filter(|v| !v.is_null()) {
|
||||
Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
};
|
||||
let (named, recorded) = (given("artboard")?, given("activeArtboard")?);
|
||||
let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?;
|
||||
let locked_art = locked_and_hidden(s, p, move_art, cmd)?;
|
||||
note_artboards(s, p, &indices);
|
||||
s.note_journal("moveArt", json!(move_art));
|
||||
let reference = match (to_artboard, named.or(recorded)) {
|
||||
(false, _) => None,
|
||||
(true, Some(i)) => Some(i),
|
||||
(true, None) => {
|
||||
let active = s.tool_options_of("artboard")["active"].clone();
|
||||
Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?)
|
||||
}
|
||||
};
|
||||
if let Some(i) = reference.filter(|_| named.is_none()) {
|
||||
s.note_journal("activeArtboard", json!(i));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let rect = |i: usize| d.artboards.get(i).map(|a| (i, a.rect)).ok_or_else(|| EngineError::Other("no such artboard".into()));
|
||||
let items = indices.iter().map(|i| rect(*i)).collect::<Result<Vec<_>>>()?;
|
||||
if indices.iter().all(|i| d.artboards.get(*i).is_some_and(|a| a.locked)) {
|
||||
return Err(EngineError::Other("the artboard is locked".into()));
|
||||
}
|
||||
Ok(Boards { items, reference: reference.map(rect).transpose()?, move_art, locked_art })
|
||||
}
|
||||
|
||||
/// `spacing` of the Distribute commands: a finite number, or `None` when it is missing or null.
|
||||
fn spacing(p: &Value, cmd: &str) -> Result<Option<f64>> {
|
||||
p.get("spacing")
|
||||
.filter(|v| !v.is_null())
|
||||
.map(|v| v.as_f64().filter(|g| g.is_finite()).ok_or_else(|| bad(cmd, "`spacing` must be a number")))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// The place in `items` of the artboard `b` aligns to, which the Distribute commands keep where it
|
||||
/// is. `None` without one, or when it is not one of `items`; with a `gap` that is an error
|
||||
/// (`no such artboard`), since the gap is measured from it.
|
||||
fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option<f64>) -> Result<Option<usize>> {
|
||||
let Some((reference, _)) = b.reference else { return Ok(None) };
|
||||
match items.iter().position(|(i, _)| *i == reference) {
|
||||
None if gap.is_some() => Err(EngineError::Other("no such artboard".into())),
|
||||
at => Ok(at),
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when
|
||||
/// `b` says so, the art inside it. Locked artboards stay where they are. When no artboard moves
|
||||
/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit
|
||||
/// fails with nothing changed when an artboard would end up past the canvas, as every edit does.
|
||||
fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let moves: Vec<(usize, Vec2)> =
|
||||
moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect();
|
||||
let moved: Vec<usize> = moves.iter().map(|(i, _)| *i).collect();
|
||||
if moves.is_empty() {
|
||||
return Ok(json!({ "moved": moved }));
|
||||
}
|
||||
let arts = artboards_art(s, &moved, b.move_art, b.locked_art, true)?;
|
||||
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
|
||||
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
|
||||
s.edit(label, |d, _| {
|
||||
for ((i, dv), (_, art)) in moves.iter().zip(&arts) {
|
||||
let a = d.artboards.get_mut(*i).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
a.rect = a.rect + *dv;
|
||||
let id = a.id;
|
||||
d.move_artboard_guides(id, *dv);
|
||||
for id in art {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.transform(Affine::translate(*dv), sc);
|
||||
super::object::keep_pixel_aligned(n, sc);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "moved": moved }))
|
||||
}
|
||||
|
||||
fn align(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "artboard.align";
|
||||
let h = choice(p, C, "horizontal", &["left", "center", "right"])?;
|
||||
let v = choice(p, C, "vertical", &["top", "center", "bottom"])?;
|
||||
if h.is_none() && v.is_none() {
|
||||
return Err(bad(C, "give horizontal or vertical"));
|
||||
}
|
||||
let b = boards(s, p, C)?;
|
||||
let Some(r) = b.reference.map(|(_, r)| r).or_else(|| b.items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b))) else {
|
||||
return Ok(json!({ "moved": [] }));
|
||||
};
|
||||
let moves: Vec<(usize, Vec2)> = b
|
||||
.items
|
||||
.iter()
|
||||
.map(|(i, a)| {
|
||||
let dx = match h {
|
||||
Some("left") => r.x0 - a.x0,
|
||||
Some("center") => r.center().x - a.center().x,
|
||||
Some("right") => r.x1 - a.x1,
|
||||
_ => 0.0,
|
||||
};
|
||||
let dy = match v {
|
||||
Some("top") => r.y0 - a.y0,
|
||||
Some("center") => r.center().y - a.center().y,
|
||||
Some("bottom") => r.y1 - a.y1,
|
||||
_ => 0.0,
|
||||
};
|
||||
(*i, Vec2::new(dx, dy))
|
||||
})
|
||||
.collect();
|
||||
apply(s, "Align", p, &b, &moves)
|
||||
}
|
||||
|
||||
fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "artboard.distribute";
|
||||
let h = choice(p, C, "horizontal", &["left", "center", "right"])?;
|
||||
let v = choice(p, C, "vertical", &["top", "center", "bottom"])?;
|
||||
let (horiz, line): (bool, fn(&Rect) -> f64) = match (h, v) {
|
||||
(Some("left"), _) => (true, |r| r.x0),
|
||||
(Some("right"), _) => (true, |r| r.x1),
|
||||
(Some(_), _) => (true, |r| r.center().x),
|
||||
(None, Some("top")) => (false, |r| r.y0),
|
||||
(None, Some("bottom")) => (false, |r| r.y1),
|
||||
(None, Some(_)) => (false, |r| r.center().y),
|
||||
(None, None) => return Err(bad(C, "give horizontal or vertical")),
|
||||
};
|
||||
let gap = spacing(p, C)?;
|
||||
let b = boards(s, p, C)?;
|
||||
let mut items = b.items.clone();
|
||||
items.sort_by(|x, y| line(&x.1).total_cmp(&line(&y.1)));
|
||||
let kept = kept(&b, &items, gap)?;
|
||||
// With a spacing: the place in the order and the line of the artboard it is measured from.
|
||||
let from = kept.zip(gap).and_then(|(at, gap)| items.get(at).map(|(_, r)| (at, gap, line(r))));
|
||||
let n = items.len();
|
||||
// Two artboards are the ends already; with a spacing the second is placed from the first.
|
||||
if n < if from.is_some() { 2 } else { 3 } {
|
||||
return Ok(json!({ "moved": [] }));
|
||||
}
|
||||
let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) };
|
||||
let (first, last) = (line(first), line(last));
|
||||
let deltas: Vec<f64> = items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, (_, r))| {
|
||||
let target = match from {
|
||||
Some((at, gap, origin)) => origin + gap * (k as f64 - at as f64),
|
||||
None => first + (last - first) * k as f64 / (n - 1) as f64,
|
||||
};
|
||||
target - line(r)
|
||||
})
|
||||
.collect();
|
||||
// The artboard aligned to stays where it is, and the others keep their places from it.
|
||||
let hold = kept.and_then(|at| deltas.get(at)).copied().unwrap_or(0.0);
|
||||
let moves: Vec<(usize, Vec2)> = items.iter().zip(&deltas).map(|((i, _), d)| (*i, along(horiz, d - hold))).collect();
|
||||
apply(s, "Distribute", p, &b, &moves)
|
||||
}
|
||||
|
||||
fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "artboard.distributeSpacing";
|
||||
let horiz = choice(p, C, "axis", &["horizontal", "vertical"])? != Some("vertical");
|
||||
let gap = spacing(p, C)?;
|
||||
let b = boards(s, p, C)?;
|
||||
let start = |r: &Rect| if horiz { r.x0 } else { r.y0 };
|
||||
let size = |r: &Rect| if horiz { r.width() } else { r.height() };
|
||||
let mut items = b.items.clone();
|
||||
items.sort_by(|x, y| start(&x.1).total_cmp(&start(&y.1)));
|
||||
let kept = kept(&b, &items, gap)?;
|
||||
let gap = gap.filter(|_| kept.is_some());
|
||||
let n = items.len();
|
||||
if n < if gap.is_some() { 2 } else { 3 } {
|
||||
return Ok(json!({ "moved": [] }));
|
||||
}
|
||||
let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) };
|
||||
let (lo, hi) = (start(first), start(last) + size(last));
|
||||
let gap = gap.unwrap_or_else(|| (hi - lo - items.iter().map(|(_, r)| size(r)).sum::<f64>()) / (n - 1) as f64);
|
||||
let mut pos = lo;
|
||||
let mut deltas = Vec::with_capacity(n);
|
||||
for (i, r) in &items {
|
||||
deltas.push((*i, pos - start(r)));
|
||||
pos += size(r) + gap;
|
||||
}
|
||||
// The artboard aligned to stays where it is, and the others keep their places from it.
|
||||
let hold = kept.and_then(|at| deltas.get(at)).map_or(0.0, |d| d.1);
|
||||
let moves: Vec<(usize, Vec2)> = deltas.into_iter().map(|(i, d)| (i, along(horiz, d - hold))).collect();
|
||||
apply(s, "Distribute Spacing", p, &b, &moves)
|
||||
}
|
||||
|
||||
/// An offset of `d` along the axis: x when `horiz`, else y.
|
||||
fn along(horiz: bool, d: f64) -> Vec2 {
|
||||
if horiz { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Align and Distribute for artboards.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use crate::Session;
|
||||
use crate::tooling::ViewInfo;
|
||||
|
||||
/// A document with three artboards, each with a 10 pt square 5 pt inside its top-left corner:
|
||||
/// 0 at (0, 0) 100 × 100, 1 at (150, 40) 60 × 80 and 2 at (400, 10) 100 × 50 → the squares' ids.
|
||||
fn three_boards() -> (Session, [u64; 3]) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
let mut sq = |x: u64, y: u64| s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let ids = [sq(5, 5), sq(155, 45), sq(405, 15)];
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
/// The top-left corner of each artboard.
|
||||
fn corners(s: &Session) -> Vec<(f64, f64)> {
|
||||
s.doc().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect()
|
||||
}
|
||||
|
||||
/// The top-left corner of object `id`.
|
||||
fn corner(s: &Session, id: u64) -> (f64, f64) {
|
||||
let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
|
||||
(b.x0, b.y0)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
const ALL: [u64; 3] = [0, 1, 2];
|
||||
|
||||
/// Align Objects lines the artboards up on the bounds of all of them, each with the art inside
|
||||
/// it, in one undo step.
|
||||
#[test]
|
||||
fn align_moves_the_artboards_to_their_common_edge_with_their_art() {
|
||||
let (mut s, [a, b, c]) = three_boards();
|
||||
let before = corners(&s);
|
||||
let steps = undo_steps(&s);
|
||||
let out = s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap();
|
||||
assert_eq!(out, json!({"moved": [1, 2]}));
|
||||
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 0.0), (400.0, 0.0)]);
|
||||
assert_eq!([corner(&s, a), corner(&s, b), corner(&s, c)], [(5.0, 5.0), (155.0, 5.0), (405.0, 5.0)], "each square stays on its artboard");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((corners(&s), corner(&s, b)), (before, (155.0, 45.0)), "one undo step");
|
||||
s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "right", "vertical": "bottom"})).unwrap();
|
||||
assert_eq!(corners(&s), [(400.0, 20.0), (440.0, 40.0), (400.0, 70.0)], "the right edges at 500 and the bottom edges at 120");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "center", "moveArt": false})).unwrap();
|
||||
assert_eq!(corners(&s), [(200.0, 0.0), (220.0, 40.0), (200.0, 10.0)], "the centers at 250");
|
||||
assert_eq!(corner(&s, a), (5.0, 5.0), "moveArt false leaves the art");
|
||||
}
|
||||
|
||||
/// Align to an artboard: that artboard stays where it is and the others line up on it. It need not
|
||||
/// be one of the artboards aligned.
|
||||
#[test]
|
||||
fn align_to_an_artboard_keeps_that_artboard_in_place() {
|
||||
let (mut s, _) = three_boards();
|
||||
let out = s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 2})).unwrap();
|
||||
assert_eq!(out, json!({"moved": [0, 1]}));
|
||||
assert_eq!(corners(&s), [(400.0, 0.0), (400.0, 40.0), (400.0, 10.0)]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.align", &json!({"index": 0, "vertical": "center", "to": "artboard", "artboard": 1})).unwrap();
|
||||
assert_eq!(corners(&s), [(0.0, 30.0), (150.0, 40.0), (400.0, 10.0)], "artboard 1's center is at y 80");
|
||||
}
|
||||
|
||||
/// With no artboard named, the commands act on the artboards the Artboard tool has selected and
|
||||
/// align to its active one; the journal records both for a replay, and an action leaves them out.
|
||||
#[test]
|
||||
fn the_artboard_tools_selection_is_the_default_and_is_recorded() {
|
||||
let (mut s, [_, _, c]) = three_boards();
|
||||
s.select_tool("artboard", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([1, 2]));
|
||||
let start = s.journal.len();
|
||||
assert_eq!(s.execute("artboard.align", &json!({"horizontal": "left"})).unwrap(), json!({"moved": [2]}));
|
||||
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (150.0, 10.0)]);
|
||||
assert_eq!(corner(&s, c), (155.0, 15.0), "the tool's Move Artwork with Artboard option is on");
|
||||
let recorded = json!({"horizontal": "left", "selectedArtboards": [1, 2], "moveArt": true, "lockedAndHidden": false});
|
||||
assert_eq!(s.journal.last().unwrap(), &("artboard.align".to_string(), recorded));
|
||||
assert_eq!(
|
||||
s.journal_for_action(start),
|
||||
[("artboard.align".to_string(), json!({"horizontal": "left", "moveArt": true, "lockedAndHidden": false}))]
|
||||
);
|
||||
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap();
|
||||
assert_eq!(corners(&s)[2], (150.0, 40.0), "artboard 2 lines up on the active artboard, 1");
|
||||
assert_eq!(s.journal.last().unwrap().1["activeArtboard"], json!(1));
|
||||
assert_eq!(s.journal_for_action(start)[1].1.get("activeArtboard"), None, "an action aligns to the artboard active when it plays");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard", "activeArtboard": 0})).unwrap();
|
||||
assert_eq!(corners(&s)[1..], [(150.0, 0.0), (150.0, 0.0)], "a replay aligns to the artboard it recorded, 0");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.align", &json!({"vertical": "bottom", "to": "artboard", "artboard": 0, "activeArtboard": 2})).unwrap();
|
||||
assert_eq!(corners(&s)[1..], [(150.0, 20.0), (150.0, 50.0)], "`artboard` goes ahead of the recorded one");
|
||||
let action = s.journal_for_action(start);
|
||||
let entry = &action.last().unwrap().1;
|
||||
assert_eq!((entry.get("artboard"), entry.get("activeArtboard")), (Some(&json!(0)), None), "an action keeps the artboard a call named");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap();
|
||||
s.set_tool_option("moveArt", &json!(false));
|
||||
s.execute("artboard.align", &json!({"horizontal": "right"})).unwrap();
|
||||
assert_eq!((corners(&s)[1], corner(&s, c)), ((190.0, 40.0), (155.0, 45.0)), "with the option off the art stays");
|
||||
}
|
||||
|
||||
/// A command that moves no artboard leaves the document and its undo history as they are.
|
||||
#[test]
|
||||
fn nothing_to_move_records_no_undo_step() {
|
||||
let (mut s, _) = three_boards();
|
||||
s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap();
|
||||
let (steps, before) = (undo_steps(&s), corners(&s));
|
||||
for (id, p) in [
|
||||
("artboard.align", json!({"indices": ALL, "vertical": "top"})),
|
||||
("artboard.align", json!({"index": 1, "horizontal": "left", "vertical": "bottom"})),
|
||||
("artboard.align", json!({"index": 1, "horizontal": "center", "to": "artboard", "artboard": 1})),
|
||||
("artboard.distribute", json!({"indices": [0, 2], "horizontal": "center"})),
|
||||
("artboard.distribute", json!({"index": 2, "vertical": "top", "to": "artboard", "artboard": 2, "spacing": 30})),
|
||||
("artboard.distributeSpacing", json!({"indices": [0, 1], "axis": "horizontal"})),
|
||||
("artboard.distributeSpacing", json!({"indices": [1], "axis": "vertical"})),
|
||||
] {
|
||||
assert_eq!(s.execute(id, &p).unwrap(), json!({"moved": []}), "{id} {p}");
|
||||
assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A locked artboard stays where it is and still counts in the bounds and in the order. When every
|
||||
/// artboard named is locked, the command fails.
|
||||
#[test]
|
||||
fn a_locked_artboard_stays_where_it_is() {
|
||||
let (mut s, _) = three_boards();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
assert_eq!(s.execute("artboard.align", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(), json!({"moved": [0, 2]}));
|
||||
assert_eq!(corners(&s), [(0.0, 20.0), (150.0, 40.0), (400.0, 70.0)], "the bottom edges at 120, the locked artboard's");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": []}), "the middle artboard is locked");
|
||||
let out =
|
||||
s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 0, "spacing": 100})).unwrap();
|
||||
assert_eq!((out, corners(&s)), (json!({"moved": [2]}), vec![(0.0, 0.0), (150.0, 40.0), (200.0, 10.0)]), "the third left edge goes to 200");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let (steps, before) = (undo_steps(&s), corners(&s));
|
||||
for (id, p) in [
|
||||
("artboard.align", json!({"index": 1, "horizontal": "left", "to": "artboard", "artboard": 0})),
|
||||
("artboard.distribute", json!({"index": 1, "horizontal": "left"})),
|
||||
("artboard.distributeSpacing", json!({"indices": [1]})),
|
||||
] {
|
||||
assert_eq!(s.execute(id, &p).unwrap_err().to_string(), "the artboard is locked", "{id}");
|
||||
assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Distribute Objects spaces the named edges or centers evenly between the outermost artboards;
|
||||
/// with a spacing and an artboard to align to, it places them that far apart from that artboard.
|
||||
#[test]
|
||||
fn distribute_spaces_the_edges_or_centers() {
|
||||
let (mut s, [_, b, _]) = three_boards();
|
||||
assert_eq!(s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "center"})).unwrap(), json!({"moved": [1]}));
|
||||
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "the centers at 50, 250 and 450");
|
||||
assert_eq!(corner(&s, b), (225.0, 45.0));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.distribute", &json!({"indices": ALL, "vertical": "bottom"})).unwrap();
|
||||
assert_eq!(corners(&s), [(0.0, -10.0), (150.0, 40.0), (400.0, 10.0)], "the bottom edges at 60, 90 and 120");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let p = json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 1, "spacing": 100});
|
||||
assert_eq!(s.execute("artboard.distribute", &p).unwrap(), json!({"moved": [0, 2]}));
|
||||
assert_eq!(corners(&s), [(50.0, 0.0), (150.0, 40.0), (250.0, 10.0)], "the left edges 100 apart, artboard 1 in place");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let two = json!({"indices": [0, 2], "horizontal": "right", "to": "artboard", "artboard": 2, "spacing": 150});
|
||||
assert_eq!(s.execute("artboard.distribute", &two).unwrap(), json!({"moved": [0]}));
|
||||
assert_eq!(corners(&s)[0], (250.0, 0.0), "two artboards are enough with a spacing: the right edges at 350 and 500");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let held = json!({"indices": ALL, "horizontal": "center", "to": "artboard", "artboard": 1});
|
||||
assert_eq!(s.execute("artboard.distribute", &held).unwrap(), json!({"moved": [0, 2]}));
|
||||
assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "the centers 200 apart, artboard 1 in place");
|
||||
}
|
||||
|
||||
/// Distribute Spacing makes the gaps between the artboards equal; with a spacing and an artboard
|
||||
/// to align to, the gaps are that wide and that artboard stays.
|
||||
#[test]
|
||||
fn distribute_spacing_makes_the_gaps_equal() {
|
||||
let (mut s, _) = three_boards();
|
||||
assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": [1]}));
|
||||
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120 between 0 and 500");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.distributeSpacing", &json!({"indices": ALL, "axis": "vertical"})).unwrap();
|
||||
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (400.0, 45.0)], "top to bottom: artboards 0, 2 and 1, overlapping by 55");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let p = json!({"indices": ALL, "axis": "horizontal", "to": "artboard", "artboard": 1, "spacing": 20});
|
||||
assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [0, 2]}));
|
||||
assert_eq!(corners(&s), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20 on both sides of artboard 1");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.distributeSpacing", &json!({"indices": [0, 2], "to": "artboard", "artboard": 0, "spacing": -25})).unwrap();
|
||||
assert_eq!(corners(&s)[2], (75.0, 10.0), "a negative spacing overlaps them");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let held = json!({"indices": ALL, "to": "artboard", "artboard": 1});
|
||||
assert_eq!(s.execute("artboard.distributeSpacing", &held).unwrap(), json!({"moved": [0, 2]}));
|
||||
assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "gaps of 120, artboard 1 in place");
|
||||
}
|
||||
|
||||
/// A value outside what a param takes is an error, and nothing changes.
|
||||
#[test]
|
||||
fn bad_params_are_errors() {
|
||||
let (mut s, _) = three_boards();
|
||||
let (steps, before) = (undo_steps(&s), corners(&s));
|
||||
let with = |extra: Value| {
|
||||
let mut p = json!({"indices": ALL, "horizontal": "left"});
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
p
|
||||
};
|
||||
let shared = [
|
||||
json!({"horizontal": "middle"}),
|
||||
json!({"horizontal": 1}),
|
||||
json!({"to": "key"}),
|
||||
json!({"to": "artboard", "artboard": 9}),
|
||||
json!({"artboard": "1"}),
|
||||
json!({"artboard": -1}),
|
||||
json!({"moveArt": "yes"}),
|
||||
json!({"patterns": 1}),
|
||||
json!({"lockedAndHidden": "no"}),
|
||||
json!({"indices": [9]}),
|
||||
json!({"indices": []}),
|
||||
json!({"indices": "0"}),
|
||||
];
|
||||
for id in ["artboard.align", "artboard.distribute", "artboard.distributeSpacing"] {
|
||||
let axis = if id == "artboard.distributeSpacing" { json!({"horizontal": null, "axis": "horizontal"}) } else { json!({}) };
|
||||
for extra in &shared {
|
||||
let mut p = with(axis.clone());
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
if id == "artboard.distributeSpacing" && extra.get("horizontal").is_some() {
|
||||
p = json!({"indices": ALL, "axis": extra["horizontal"]});
|
||||
}
|
||||
assert!(s.execute(id, &p).is_err(), "{id} {p}");
|
||||
}
|
||||
}
|
||||
for (id, p) in [
|
||||
("artboard.align", json!({"indices": ALL})),
|
||||
("artboard.align", json!({"indices": ALL, "vertical": "middle"})),
|
||||
("artboard.distribute", json!({"indices": ALL})),
|
||||
("artboard.distribute", with(json!({"spacing": "10"}))),
|
||||
("artboard.distribute", with(json!({"spacing": true}))),
|
||||
("artboard.distribute", json!({"indices": [0, 1], "horizontal": "left", "to": "artboard", "artboard": 2, "spacing": 10})),
|
||||
("artboard.distributeSpacing", json!({"indices": ALL, "spacing": [10]})),
|
||||
("artboard.distributeSpacing", json!({"indices": [0, 1], "to": "artboard", "artboard": 2, "spacing": 10})),
|
||||
] {
|
||||
assert!(s.execute(id, &p).is_err(), "{id} {p}");
|
||||
}
|
||||
// Spacings that would put an artboard past the canvas, or overflow to infinity.
|
||||
for (id, p) in [
|
||||
("artboard.distribute", with(json!({"to": "artboard", "artboard": 0, "spacing": 1e9}))),
|
||||
("artboard.distribute", with(json!({"to": "artboard", "artboard": 1, "spacing": 1e308}))),
|
||||
("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 1e9})),
|
||||
("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 1, "spacing": 1e308})),
|
||||
] {
|
||||
let e = s.execute(id, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("exceed the canvas"), "{id} {p}: {e}");
|
||||
}
|
||||
assert_eq!((undo_steps(&s), corners(&s)), (steps, before));
|
||||
}
|
||||
|
||||
/// An artboard's own guides move with it.
|
||||
#[test]
|
||||
fn an_artboards_guides_move_with_it() {
|
||||
let (mut s, _) = three_boards();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 160, "artboard": 1})).unwrap();
|
||||
s.execute("artboard.align", &json!({"indices": [0, 1], "horizontal": "left"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let positions: Vec<f64> = d.ruler_guides().iter().map(|g| g.pos).collect();
|
||||
assert_eq!(positions, [10.0], "the guide stays 10 pt inside artboard 1");
|
||||
}
|
||||
@@ -122,7 +122,7 @@ pub(crate) fn boards_and_art_noted(s: &mut Session, p: &Value, cmd: &str) -> Res
|
||||
/// Add `selectedArtboards` to the running command's journal entry when `p` names no artboard, so a
|
||||
/// replay acts on the artboards the Artboard tool had selected. An action leaves it out
|
||||
/// (`REPLAY_ONLY`) and keeps an `index` or `indices` the call gave.
|
||||
fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) {
|
||||
pub(crate) fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) {
|
||||
if p.get("index").is_none() && p.get("indices").is_none() {
|
||||
s.note_journal("selectedArtboards", json!(indices));
|
||||
}
|
||||
@@ -130,7 +130,7 @@ fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) {
|
||||
|
||||
/// The artboards `cmd` acts on: `index` or `indices`, else `selectedArtboards` (a replay of the
|
||||
/// journal), else those the Artboard tool has selected, else its active one.
|
||||
fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
let t = s.tool_options_of("artboard");
|
||||
let d = &s.doc()?.doc;
|
||||
if p.get("index").is_some() || p.get("indices").is_some() {
|
||||
|
||||
@@ -86,9 +86,12 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"appearance.showAllHidden",
|
||||
"appearance.targetContents",
|
||||
"appearance.transfer",
|
||||
"artboard.align",
|
||||
"artboard.convertToArtboards",
|
||||
"artboard.delete",
|
||||
"artboard.deleteEmpty",
|
||||
"artboard.distribute",
|
||||
"artboard.distributeSpacing",
|
||||
"artboard.duplicate",
|
||||
"artboard.fitToArt",
|
||||
"artboard.fitToSelection",
|
||||
|
||||
Reference in New Issue
Block a user