mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge pull request #10124 from dotCooCoo/feat/screen-print-marks
Color Effects: Create Screen Print Marks draws registration targets and ink lines
This commit is contained in:
18 files changed
+1969
-40
No files matched your search
@@ -16,6 +16,10 @@ mod shapes;
|
||||
mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use color::screen_marks::{
|
||||
LAYER_NAME as SCREEN_MARKS_LAYER, adopt_layer as adopt_screen_marks_layer, copied_owners as screen_marks_copied, layer_id as screen_marks_layer,
|
||||
managed_owners as screen_marks_owners, owned_by as screen_marks_of, release as release_screen_marks, retag as retag_screen_marks,
|
||||
};
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
@@ -4,15 +4,17 @@
|
||||
//! objects that use spot colours, carry a live colour adjustment, or are images of a colour model,
|
||||
//! Print Ink Fixes ([`print_fixes`]) prepares a CMYK document's inks for print, Find Nearest
|
||||
//! Swatch ([`nearest`]) matches colours to a swatch library's, Create Swatch Legend
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, and Apply Fill to Stroke and Apply
|
||||
//! Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and Randomize Fill Colors
|
||||
//! ([`random_fill`]) gives each filled path its own color at random. Its panel and its submenu,
|
||||
//! Object › Plug-ins › Color Effects, are the UI's.
|
||||
//! ([`legend`]) draws labelled chips of the document's swatches, Create Screen Print Marks
|
||||
//! ([`screen_marks`]) draws registration targets and ink and file lines on the artboard, Apply
|
||||
//! Fill to Stroke and Apply Stroke to Fill ([`copy_paint`]) copy each object's own paint across, and
|
||||
//! Randomize Fill Colors ([`random_fill`]) gives each filled path its own color at random. Its
|
||||
//! panel and its submenu, Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
mod random_fill;
|
||||
pub mod screen_marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -106,6 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
.chain(screen_marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,515 @@
|
||||
//! Create Screen Print Marks (`addon.color.screenMarks`; Object › Plug-ins › Color Effects ›
|
||||
//! Create Screen Print Marks…): registration targets at chosen corners and side centers of an
|
||||
//! artboard, in [Registration] or a spot ink, with optional lines that list the document's spot
|
||||
//! inks (each name in its own ink) and give the file name with the date and time. The marks are
|
||||
//! document art, one group per artboard on a locked "Screen Print Marks" layer at the bottom of the
|
||||
//! stack, so they print and export with the rest. Running it again replaces that artboard's marks,
|
||||
//! in one undo step, and makes none when the marks would come out the same.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
|
||||
use super::super::super::{CommandSpec, bad, clock_date, cmd, date_param, has_doc, index_opt, switch_or, text_param};
|
||||
use crate::{DocState, Result, Session};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.color.screenMarks",
|
||||
"Create Screen Print Marks",
|
||||
["Object", "Plug-ins", "Color Effects"],
|
||||
None,
|
||||
"{positions?: [topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight…] (each at most once; default: [top, bottom, left, right]; [] draws no targets), size?: target width in pt 4..1000 (36), weight?: stroke weight in pt 0.1..20 (1), inset?: pt from the artboard's edge to the target's outer edge -1000..1000 (18; below 0 the targets sit outside the artboard), ink?: \"[Registration]\" (default) or a spot swatch's name (the targets and the file line), inks?: false (a line naming the document's spot inks, each name in its own ink; tints and [Registration] left out), info?: false (a line with the file name, or the title of a document never saved, and the date and time in UTC), time?: Unix seconds (default: now; null, or no clock as on the web: no date), textSize?: pt 4..72 (9), textPlace?: \"top\"|\"bottom\" (default), textAlign?: \"left\" (default)|\"right\" (the lines start past a target ticked in that corner, and move in past the top or bottom target they would cross; they stay where they are when moving would cross another target or leave the artboard), artboard?: index (default: the active artboard), activeArtboard?: index (the active artboard the journal records for a replay; used when artboard is left out; omitted from recorded actions), allArtboards?: false; null is refused except for time} draw registration targets (a circle half the target's width with a cross through it, stroked) inside each artboard, and the lines asked for, as one group per artboard on the layer \"Screen Print Marks\", which is made locked at the bottom of the stack when there is none; running it again replaces that artboard's group. Another artboard's group lying on a copied artboard goes with its own artboard. One undo step, none when the marks come out the same; the selection is kept → {changed, layer, ids: [group id…], inks: [spot ink name…]}",
|
||||
has_doc,
|
||||
screen_marks
|
||||
)]
|
||||
}
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.color.screenMarks";
|
||||
|
||||
/// Where a target can go, in the order the command draws them.
|
||||
pub const POSITIONS: [&str; 8] = ["topLeft", "top", "topRight", "left", "right", "bottomLeft", "bottom", "bottomRight"];
|
||||
/// The targets drawn when `positions` is left out.
|
||||
pub const DEFAULT_POSITIONS: [&str; 4] = ["top", "bottom", "left", "right"];
|
||||
/// The name of the layer the marks go on, and of each artboard's group.
|
||||
pub const LAYER_NAME: &str = "Screen Print Marks";
|
||||
/// The object data key that marks the layer (`layer`) and each artboard's group (the artboard's id).
|
||||
pub const KEY: &str = "vc-screen-print-marks";
|
||||
/// Most spot inks one line names.
|
||||
const MAX_INKS: usize = 256;
|
||||
|
||||
fn number(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && range.contains(n))
|
||||
.ok_or_else(|| bad(COMMAND, format!("`{key}` must be a number {}..{}", range.start(), range.end()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// One of `options` for `key`, else `default`.
|
||||
fn choice(p: &Value, key: &str, options: [&'static str; 2], default: &'static str) -> Result<&'static str> {
|
||||
match text_param(p, key, COMMAND)? {
|
||||
None => Ok(default),
|
||||
Some(v) => options.into_iter().find(|o| *o == v).ok_or_else(|| bad(COMMAND, format!("`{key}` must be {} or {}", options[0], options[1]))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The target positions `p` asks for, in [`POSITIONS`] order.
|
||||
fn positions(p: &Value) -> Result<Vec<&'static str>> {
|
||||
let asked: Vec<&str> = match p.get("positions") {
|
||||
None => return Ok(POSITIONS.into_iter().filter(|w| DEFAULT_POSITIONS.contains(w)).collect()),
|
||||
Some(Value::Array(a)) => {
|
||||
a.iter().map(|v| v.as_str().ok_or_else(|| bad(COMMAND, "`positions` must be a list of position names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(COMMAND, "`positions` must be a list of position names")),
|
||||
};
|
||||
for (i, w) in asked.iter().enumerate() {
|
||||
if !POSITIONS.contains(w) {
|
||||
return Err(bad(COMMAND, format!("`{w}` is not a position: give {}", POSITIONS.join(", "))));
|
||||
}
|
||||
if asked[..i].contains(w) {
|
||||
return Err(bad(COMMAND, format!("`positions` names `{w}` twice")));
|
||||
}
|
||||
}
|
||||
Ok(POSITIONS.into_iter().filter(|w| asked.contains(w)).collect())
|
||||
}
|
||||
|
||||
/// The paint of ink `name`: [Registration], or a spot swatch linked to it.
|
||||
fn ink_paint(doc: &Document, name: &str) -> Result<Paint> {
|
||||
if name == REGISTRATION {
|
||||
return Ok(Paint::registration());
|
||||
}
|
||||
let w = doc.swatch(name).ok_or_else(|| bad(COMMAND, format!("no swatch named `{name}`")))?;
|
||||
if !w.spot || w.tint_of().is_some() || w.paint.color().is_none() {
|
||||
return Err(bad(COMMAND, format!("`{name}` is not a spot color swatch: give [Registration] or a spot swatch")));
|
||||
}
|
||||
super::super::super::paint::swatch_solid(doc, name, None).map_err(|e| bad(COMMAND, e))
|
||||
}
|
||||
|
||||
/// The document's spot inks in panel order, each with the paint that links to it: spot color
|
||||
/// swatches that are not tints, [Registration] left out.
|
||||
fn spot_inks(doc: &Document) -> Vec<(String, Paint)> {
|
||||
doc.swatches_iter()
|
||||
.filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some())
|
||||
.map(|w| (w.name.clone(), super::super::super::paint::swatch_solid(doc, &w.name, None).unwrap_or_else(|_| w.paint.clone())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The index of the view's active artboard: when the document no longer has it, the one the
|
||||
/// document opened on, else the first.
|
||||
fn active_artboard(st: &DocState) -> Option<usize> {
|
||||
let d = &st.doc;
|
||||
let at = |id: Option<u32>| id.and_then(|id| d.artboards.iter().position(|a| a.id == id));
|
||||
at(st.active_artboard).or_else(|| at(d.opened_artboard)).or((!d.artboards.is_empty()).then_some(0))
|
||||
}
|
||||
|
||||
/// The settings every artboard's marks are drawn with.
|
||||
struct Marks {
|
||||
positions: Vec<&'static str>,
|
||||
size: f64,
|
||||
weight: f64,
|
||||
inset: f64,
|
||||
ink: Paint,
|
||||
/// The lines of type, top to bottom: each a list of (text, fill) runs.
|
||||
lines: Vec<Vec<(String, Paint)>>,
|
||||
style: CharStyle,
|
||||
system_layout: bool,
|
||||
top: bool,
|
||||
left: bool,
|
||||
}
|
||||
|
||||
impl Marks {
|
||||
/// The center of the target at `position` on artboard `r`.
|
||||
fn center(&self, r: Rect, position: &str) -> Point {
|
||||
let near = self.inset + self.size / 2.0;
|
||||
let x = if position.ends_with("Left") || position == "left" {
|
||||
r.x0 + near
|
||||
} else if position.ends_with("Right") || position == "right" {
|
||||
r.x1 - near
|
||||
} else {
|
||||
r.center().x
|
||||
};
|
||||
let y = if position.starts_with("top") {
|
||||
r.y0 + near
|
||||
} else if position.starts_with("bottom") {
|
||||
r.y1 - near
|
||||
} else {
|
||||
r.center().y
|
||||
};
|
||||
Point::new(x, y)
|
||||
}
|
||||
|
||||
/// The target at `c`: a circle half the target's width and a cross the target's width, stroked.
|
||||
fn target(&self, c: Point, alloc: &mut dyn FnMut() -> NodeId) -> Node {
|
||||
let ap = Appearance::basic(Paint::None, self.ink.clone(), self.weight);
|
||||
let (half, ring) = (self.size / 2.0, self.size / 4.0);
|
||||
let paths = [
|
||||
shapes::ellipse(Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring)),
|
||||
shapes::line(Point::new(c.x - half, c.y), Point::new(c.x + half, c.y)),
|
||||
shapes::line(Point::new(c.x, c.y - half), Point::new(c.x, c.y + half)),
|
||||
];
|
||||
let children = paths.into_iter().map(|path| Arc::new(Node::path(alloc(), path, ap.clone()))).collect();
|
||||
let mut g = Node::group(alloc(), children);
|
||||
g.name = Some("Registration Target".into());
|
||||
g
|
||||
}
|
||||
|
||||
/// A point type line of `runs` placed with its box's top-left (or top-right) corner at `at`, or
|
||||
/// its bottom corner there when `from_bottom`, with its box.
|
||||
fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, Rect) {
|
||||
let runs: Vec<TextRun> = runs
|
||||
.iter()
|
||||
.map(|(text, fill)| {
|
||||
let mut style = self.style.clone();
|
||||
style.fill = fill.clone();
|
||||
style.stroke = Paint::None;
|
||||
TextRun::new(text.clone(), style)
|
||||
})
|
||||
.collect();
|
||||
let mut t = TextObject::point(Point::ZERO, "", self.style.clone());
|
||||
t.runs = runs;
|
||||
t.para = super::super::super::create::new_type_para();
|
||||
t.system_layout = self.system_layout;
|
||||
super::super::super::typecmd::refresh_bounds(&mut t);
|
||||
let b = t.cached_bounds.unwrap_or(Rect::new(0.0, -self.style.size * 0.8, 0.0, self.style.size * 0.2));
|
||||
let dx = if self.left { at.x - b.x0 } else { at.x - b.x1 };
|
||||
let dy = if from_bottom { at.y - b.y1 } else { at.y - b.y0 };
|
||||
t.xf = Affine::translate((dx, dy));
|
||||
(t, Rect::new(b.x0 + dx, b.y0 + dy, b.x1 + dx, b.y1 + dy))
|
||||
}
|
||||
|
||||
/// The lines placed in a column from `y`, at `x`: down from `y` at the top, up
|
||||
/// from it at the bottom. Each with its box.
|
||||
fn column(&self, x: f64, mut y: f64) -> Vec<(TextObject, Rect)> {
|
||||
let gap = self.style.size * 0.25;
|
||||
let mut placed = Vec::with_capacity(self.lines.len());
|
||||
if self.top {
|
||||
for runs in &self.lines {
|
||||
let (t, b) = self.line(runs, Point::new(x, y), false);
|
||||
y += b.height() + gap;
|
||||
placed.push((t, b));
|
||||
}
|
||||
} else {
|
||||
for runs in self.lines.iter().rev() {
|
||||
let (t, b) = self.line(runs, Point::new(x, y), true);
|
||||
y -= b.height() + gap;
|
||||
placed.insert(0, (t, b));
|
||||
}
|
||||
}
|
||||
placed
|
||||
}
|
||||
|
||||
/// The marks of artboard `r` (id `board`) as one group, with ids from `alloc` (the group's last).
|
||||
fn group(&self, r: Rect, board: u32, alloc: &mut dyn FnMut() -> NodeId) -> Node {
|
||||
let mut children: Vec<Arc<Node>> = self.positions.iter().map(|w| Arc::new(self.target(self.center(r, w), alloc))).collect();
|
||||
if !self.lines.is_empty() {
|
||||
// The lines start past a target in the corner they start from.
|
||||
let corner = match (self.top, self.left) {
|
||||
(true, true) => "topLeft",
|
||||
(true, false) => "topRight",
|
||||
(false, true) => "bottomLeft",
|
||||
(false, false) => "bottomRight",
|
||||
};
|
||||
let skip = if self.positions.contains(&corner) { self.size + self.style.size } else { 0.0 };
|
||||
let x = if self.left { r.x0 + self.inset + skip } else { r.x1 - self.inset - skip };
|
||||
let (edge, sign) = if self.top { (r.y0, 1.0) } else { (r.y1, -1.0) };
|
||||
let mut placed = self.column(x, edge + sign * self.inset);
|
||||
// Lines that would cross the center target on their side move in past it, unless they
|
||||
// would then cross another target or leave the artboard.
|
||||
let side = if self.top { "top" } else { "bottom" };
|
||||
// A target's paint: its two bars and the box of its ring, each with half the stroke weight.
|
||||
let (half, ring, w2) = (self.size / 2.0, self.size / 4.0 + self.weight / 2.0, self.weight / 2.0);
|
||||
let crosses = |placed: &[(TextObject, Rect)], w: &str| {
|
||||
let c = self.center(r, w);
|
||||
let paint = [
|
||||
Rect::new(c.x - half - w2, c.y - w2, c.x + half + w2, c.y + w2),
|
||||
Rect::new(c.x - w2, c.y - half - w2, c.x + w2, c.y + half + w2),
|
||||
Rect::new(c.x - ring, c.y - ring, c.x + ring, c.y + ring),
|
||||
];
|
||||
placed.iter().any(|(_, b)| paint.iter().any(|p| b.x0 < p.x1 && b.x1 > p.x0 && b.y0 < p.y1 && b.y1 > p.y0))
|
||||
};
|
||||
if self.positions.contains(&side) && crosses(&placed, side) {
|
||||
let moved = self.column(x, edge + sign * (self.inset + self.size + self.weight / 2.0 + self.style.size * 0.25));
|
||||
if moved.iter().all(|(_, b)| b.y0 >= r.y0 && b.y1 <= r.y1) && !self.positions.iter().any(|w| crosses(&moved, w)) {
|
||||
placed = moved;
|
||||
}
|
||||
}
|
||||
children.extend(placed.into_iter().map(|(t, _)| Arc::new(Node::new(alloc(), NodeKind::Text(Box::new(t))))));
|
||||
}
|
||||
let mut g = Node::group(alloc(), children);
|
||||
g.name = Some(LAYER_NAME.into());
|
||||
g.edit_attrs(|a| a.data.push((KEY.into(), board.to_string())));
|
||||
g
|
||||
}
|
||||
}
|
||||
|
||||
/// The marks layer: the top-level layer whose data says so.
|
||||
fn marks_layer(doc: &Document) -> Option<&Arc<Node>> {
|
||||
doc.layers.iter().find(|l| tag(l) == Some("layer"))
|
||||
}
|
||||
|
||||
/// What `n`'s data holds under [`KEY`].
|
||||
fn tag(n: &Node) -> Option<&str> {
|
||||
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The id of the artboard marks group `n` belongs to, from its data.
|
||||
fn owner(n: &Node) -> Option<u32> {
|
||||
tag(n)?.parse().ok()
|
||||
}
|
||||
|
||||
/// Each marks group on the marks layer of `d`, with the id of the artboard it belongs to.
|
||||
pub(crate) fn managed_owners(d: &Document) -> std::collections::HashMap<NodeId, u32> {
|
||||
marks_layer(d).and_then(|l| l.children()).into_iter().flatten().filter_map(|k| Some((k.id, owner(k)?))).collect()
|
||||
}
|
||||
|
||||
/// The id of the marks layer of `d`, when it has one.
|
||||
pub(crate) fn layer_id(d: &Document) -> Option<NodeId> {
|
||||
marks_layer(d).map(|l| l.id)
|
||||
}
|
||||
|
||||
/// Is `n` the marks group of one of the artboards with ids `boards`?
|
||||
pub(crate) fn owned_by(n: &Node, boards: &[u32]) -> bool {
|
||||
owner(n).is_some_and(|o| boards.contains(&o))
|
||||
}
|
||||
|
||||
/// Each marks group on the marks layer of `d` that goes with an artboard copy, in paint order,
|
||||
/// with the id of the artboard it belongs to. Locked and hidden ones, and all of them while the
|
||||
/// marks layer is locked or hidden, only with `locked_and_hidden`.
|
||||
pub(crate) fn copied_owners(d: &Document, locked_and_hidden: bool) -> Vec<(NodeId, u32)> {
|
||||
let layer = marks_layer(d).filter(|l| l.rides_with_artboard(locked_and_hidden));
|
||||
let kids = layer.and_then(|l| l.children()).into_iter().flatten();
|
||||
kids.filter(|k| k.rides_with_artboard(locked_and_hidden)).filter_map(|k| Some((k.id, owner(k)?))).collect()
|
||||
}
|
||||
|
||||
/// Make copy `n` of an artboard's marks group belong to the artboard copied with it: its data
|
||||
/// names artboard `from`, and from now on names `to`. Duplicate Artboards, Alt-drag and paste call
|
||||
/// it on each copy they make. → whether `n` was such a group.
|
||||
pub(crate) fn retag(n: &mut Node, from: u32, to: u32) -> bool {
|
||||
if owner(n) != Some(from) {
|
||||
return false;
|
||||
}
|
||||
let (from, to) = (from.to_string(), to.to_string());
|
||||
n.edit_attrs(|a| {
|
||||
for (k, v) in a.data.iter_mut() {
|
||||
if k == KEY && *v == from {
|
||||
v.clone_from(&to);
|
||||
}
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Make the marks groups of the deleted artboards with ids `gone` ordinary art: a file opened
|
||||
/// again can give a new artboard one of those ids, and its marks are drawn afresh.
|
||||
pub(crate) fn release(d: &mut Document, gone: &std::collections::HashSet<u32>) {
|
||||
// Groups moved off the marks layer keep their tag and count too.
|
||||
let mut groups: Vec<NodeId> = vec![];
|
||||
for l in &d.layers {
|
||||
l.walk(&mut |n: &Node| {
|
||||
if owner(n).is_some_and(|o| gone.contains(&o)) {
|
||||
groups.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
for id in groups {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.edit_attrs(|a| a.data.retain(|(k, _)| k != KEY));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Make top-level layer `layer`, which a paste made for a marks group it copied with an artboard,
|
||||
/// the marks layer, when the document has none.
|
||||
pub(crate) fn adopt_layer(d: &mut Document, layer: NodeId) {
|
||||
if marks_layer(d).is_some() || !d.layers.iter().any(|l| l.id == layer) {
|
||||
return;
|
||||
}
|
||||
if let Some(l) = d.node_mut(layer) {
|
||||
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` with every object's id 0: marks drawn again compare equal to marks drawn the same way.
|
||||
fn without_ids(n: &Node) -> Node {
|
||||
let mut n = n.clone();
|
||||
n.id = NodeId(0);
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(without_ids(c));
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn screen_marks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = COMMAND;
|
||||
let positions = positions(p)?;
|
||||
let size = number(p, "size", 36.0, 4.0..=1000.0)?;
|
||||
let weight = number(p, "weight", 1.0, 0.1..=20.0)?;
|
||||
let inset = number(p, "inset", 18.0, -1000.0..=1000.0)?;
|
||||
let text_size = number(p, "textSize", 9.0, 4.0..=72.0)?;
|
||||
let top = choice(p, "textPlace", ["top", "bottom"], "bottom")? == "top";
|
||||
let left = choice(p, "textAlign", ["left", "right"], "left")? == "left";
|
||||
let want_inks = switch_or(p, "inks", false, C)?;
|
||||
let want_info = switch_or(p, "info", false, C)?;
|
||||
let all = switch_or(p, "allArtboards", false, C)?;
|
||||
let given_time = date_param(p, "time", C)?;
|
||||
let ink_name = text_param(p, "ink", C)?.unwrap_or(REGISTRATION).to_string();
|
||||
// Defaults are for values left out; only `time` takes null (no date).
|
||||
if let Some((key, _)) = p.as_object().and_then(|o| o.iter().find(|(k, v)| v.is_null() && *k != "time")) {
|
||||
return Err(bad(C, format!("`{key}` must not be null: leave it out for the default")));
|
||||
}
|
||||
let artboard = index_opt(p, "artboard", C)?;
|
||||
if all && artboard.is_some() {
|
||||
return Err(bad(C, "give `artboard` or `allArtboards`, not both"));
|
||||
}
|
||||
// The active artboard, noted in the journal (`activeArtboard`) so a replay marks the same one;
|
||||
// recorded actions leave it out and use the active artboard when played.
|
||||
let recorded = index_opt(p, "activeArtboard", C)?;
|
||||
let artboard = match artboard {
|
||||
None if !all => {
|
||||
let i = match recorded {
|
||||
Some(i) => Some(i),
|
||||
None => active_artboard(s.doc()?),
|
||||
};
|
||||
if let Some(i) = i {
|
||||
s.note_journal("activeArtboard", json!(i));
|
||||
}
|
||||
i
|
||||
}
|
||||
given => given,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
if doc.artboards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboards"));
|
||||
}
|
||||
let boards: Vec<(Rect, u32)> = if all {
|
||||
doc.artboards.iter().map(|a| (a.rect, a.id)).collect()
|
||||
} else {
|
||||
let i = artboard.unwrap_or(0);
|
||||
let a = doc.artboards.get(i).ok_or_else(|| bad(C, format!("there is no artboard {i}")))?;
|
||||
vec![(a.rect, a.id)]
|
||||
};
|
||||
let ink = ink_paint(doc, &ink_name)?;
|
||||
let inks = if want_inks { spot_inks(doc) } else { vec![] };
|
||||
if inks.len() > MAX_INKS {
|
||||
return Err(bad(C, format!("a line names at most {MAX_INKS} spot inks")));
|
||||
}
|
||||
let file = st
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| std::path::Path::new(path).file_name())
|
||||
.map(|f| f.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| doc.title.clone());
|
||||
let system_layout = doc.setup.system_layout;
|
||||
if positions.is_empty() && inks.is_empty() && !want_info {
|
||||
let why = if want_inks { "the document has no spot inks" } else { "give `positions`, `inks` or `info`" };
|
||||
return Err(bad(C, format!("nothing to draw: {why}")));
|
||||
}
|
||||
let mut lines: Vec<Vec<(String, Paint)>> = vec![];
|
||||
if !inks.is_empty() {
|
||||
let last = inks.len() - 1;
|
||||
lines.push(
|
||||
inks.iter().enumerate().map(|(i, (name, paint))| (if i < last { format!("{name} ") } else { name.clone() }, paint.clone())).collect(),
|
||||
);
|
||||
}
|
||||
if want_info {
|
||||
let date = clock_date(s, "time", given_time).map(|t| {
|
||||
let [y, mo, d, h, mi, _] = vectorcraft_doc::metadata::civil(t);
|
||||
format!("{y:04}-{mo:02}-{d:02} {h:02}:{mi:02} UTC")
|
||||
});
|
||||
let text = match date {
|
||||
Some(date) => format!("{file} {date}"),
|
||||
None => file,
|
||||
};
|
||||
lines.push(vec![(text, ink.clone())]);
|
||||
}
|
||||
let style = super::super::super::create::new_type_style(s, &json!({ "size": text_size }), C)?;
|
||||
let marks = Marks { positions, size, weight, inset, ink, lines, style, system_layout, top, left };
|
||||
let names: Vec<String> = inks.into_iter().map(|(name, _)| name).collect();
|
||||
|
||||
// The marks as they would come out, to tell whether anything changes.
|
||||
let st = s.doc()?;
|
||||
let layer = marks_layer(&st.doc).map(|l| (l.id, l.children().cloned().unwrap_or_default()));
|
||||
let drawn: Vec<Node> = boards.iter().map(|(r, board)| marks.group(*r, *board, &mut || NodeId(0))).collect();
|
||||
// Only the stroked targets reach past their paths, by half the target weight. The lines of type
|
||||
// have no stroke; their glyphs' ink, underline and strikethrough bars included, is checked as well.
|
||||
let past = |b: Rect, reach: f64| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD);
|
||||
let beyond = |n: &Node| match &n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
n.geometric_bounds().is_some_and(|b| past(b, 0.0)) || t.ink().flatten().is_some_and(|ink| past(t.xf.transform_rect_bbox(ink), 0.0))
|
||||
}
|
||||
_ => n.geometric_bounds().is_some_and(|b| past(b, marks.weight / 2.0)),
|
||||
};
|
||||
if drawn.iter().any(|g| g.children().is_some_and(|kids| kids.iter().any(|k| beyond(k)))) {
|
||||
return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)")));
|
||||
}
|
||||
// Each existing group under the artboard it belongs to, worked out once.
|
||||
let mut owned: std::collections::HashMap<u32, Vec<&Arc<Node>>> = std::collections::HashMap::new();
|
||||
for k in layer.iter().flat_map(|(_, kids)| kids) {
|
||||
if let Some(board) = owner(k) {
|
||||
owned.entry(board).or_default().push(k);
|
||||
}
|
||||
}
|
||||
if let Some((layer, _)) = &layer {
|
||||
let same = boards
|
||||
.iter()
|
||||
.zip(&drawn)
|
||||
.all(|((_, board), new)| matches!(owned.get(board).map(Vec::as_slice), Some([one]) if without_ids(one) == without_ids(new)));
|
||||
if same {
|
||||
let ids: Vec<u64> = boards.iter().filter_map(|(_, board)| owned.get(board).and_then(|g| g.first()).map(|g| g.id.0)).collect();
|
||||
return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names }));
|
||||
}
|
||||
}
|
||||
let owned: std::collections::HashMap<u32, Vec<NodeId>> = owned.into_iter().map(|(b, g)| (b, g.into_iter().map(|k| k.id).collect())).collect();
|
||||
let (layer, ids) = s.edit("Create Screen Print Marks", |d, sel| {
|
||||
let layer = match marks_layer(d).map(|l| l.id) {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let id = d.alloc_id();
|
||||
let color = LayerColor::Preset((d.layers.len() % LAYER_COLORS.len()) as u8);
|
||||
let mut l = Node::layer(id, LAYER_NAME, color);
|
||||
l.locked = true;
|
||||
l.edit_attrs(|a| a.data.push((KEY.into(), "layer".into())));
|
||||
d.insert(None, 0, l)?;
|
||||
id
|
||||
}
|
||||
};
|
||||
let mut ids = Vec::with_capacity(boards.len());
|
||||
for (r, board) in &boards {
|
||||
let kids = d.children(Some(layer)).cloned().unwrap_or_default();
|
||||
let old: Vec<NodeId> = owned.get(board).cloned().unwrap_or_default();
|
||||
let at = kids.iter().position(|k| old.first() == Some(&k.id)).unwrap_or(usize::MAX);
|
||||
// Only what the selection holds of the marks leaves it; the rest of the selection stays as it is.
|
||||
let mut held = vec![];
|
||||
for k in kids.iter().filter(|k| old.contains(&k.id)) {
|
||||
k.walk(&mut |n: &Node| {
|
||||
if sel.objects.contains(&n.id) || sel.anchors.contains_key(&n.id) || sel.segments.contains_key(&n.id) {
|
||||
held.push(n.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
if !held.is_empty() {
|
||||
sel.remove_all(held);
|
||||
}
|
||||
d.remove_many(&old)?;
|
||||
let g = marks.group(*r, *board, &mut || d.alloc_id());
|
||||
ids.push(g.id.0);
|
||||
d.insert(Some(layer), at, g)?;
|
||||
}
|
||||
Ok((layer, ids))
|
||||
})?;
|
||||
Ok(json!({ "changed": true, "layer": layer.0, "ids": ids, "inks": names }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,935 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::{COMMAND, LAYER_NAME};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: Value) -> Value {
|
||||
s.execute(COMMAND, &p).unwrap()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: u64) -> Node {
|
||||
s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone()
|
||||
}
|
||||
|
||||
/// The targets of group `g`: each one's three paths.
|
||||
fn targets(g: &Node) -> Vec<Vec<Node>> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref() == Some("Registration Target"))
|
||||
.map(|t| t.children().unwrap().iter().map(|p| (**p).clone()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The type lines of group `g`, top to bottom as stored.
|
||||
fn lines(g: &Node) -> Vec<vectorcraft_doc::TextObject> {
|
||||
g.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some((**t).clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bounds(n: &Node) -> Rect {
|
||||
n.geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// The swatch solid paint `p` links to.
|
||||
fn swatch_of(p: &Paint) -> Option<String> {
|
||||
match p {
|
||||
Paint::Solid { swatch, .. } => swatch.clone(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_targets_go_on_a_locked_bottom_layer_in_registration_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let art = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, json!({}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(undo_len(&s), undo + 1, "one undo step");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [NodeId(art)], "the selection is kept");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let layer = &doc.layers[0];
|
||||
assert_eq!(layer.id.0, r["layer"].as_u64().unwrap(), "the marks layer is at the bottom of the stack");
|
||||
assert_eq!(layer.name.as_deref(), Some(LAYER_NAME));
|
||||
assert!(layer.locked && layer.visible, "the marks layer is locked");
|
||||
assert_eq!(doc.layers.len(), 2);
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 1, "one group for the active artboard");
|
||||
let g = node(&s, ids[0].as_u64().unwrap());
|
||||
assert_eq!(super::tag(&g), Some(doc.artboards[0].id.to_string().as_str()));
|
||||
let t = targets(&g);
|
||||
assert_eq!(t.len(), 4, "top, bottom, left and right by default");
|
||||
assert!(lines(&g).is_empty(), "no type lines unless asked for");
|
||||
for paths in &t {
|
||||
assert_eq!(paths.len(), 3, "a ring and two cross lines");
|
||||
for p in paths {
|
||||
assert!(p.appearance.stroke_paint().is_registration(), "stroked in [Registration]");
|
||||
assert!(p.appearance.fill_paint().is_none());
|
||||
assert!(close(p.appearance.stroke_width(), 1.0));
|
||||
}
|
||||
}
|
||||
// The top target: its 36 pt box 18 pt in from the top edge, centered across.
|
||||
let top = &t[0];
|
||||
let ring = bounds(&top[0]);
|
||||
assert!(close(ring.width(), 18.0) && close(ring.center().x, 300.0) && close(ring.center().y, 36.0), "{ring:?}");
|
||||
let across = bounds(&top[1]);
|
||||
assert!(close(across.x0, 282.0) && close(across.x1, 318.0), "{across:?}");
|
||||
let down = bounds(&top[2]);
|
||||
assert!(close(down.y0, 18.0) && close(down.y1, 54.0), "{down:?}");
|
||||
// Left, right and bottom.
|
||||
let centers: Vec<_> = t.iter().map(|p| bounds(&p[0]).center()).collect();
|
||||
assert!(close(centers[1].x, 36.0) && close(centers[1].y, 200.0), "left: {:?}", centers[1]);
|
||||
assert!(close(centers[2].x, 564.0) && close(centers[2].y, 200.0), "right: {:?}", centers[2]);
|
||||
assert!(close(centers[3].x, 300.0) && close(centers[3].y, 364.0), "bottom: {:?}", centers[3]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers.len(), 1, "undo removes the layer and its marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_size_weight_inset_and_a_spot_ink_shape_the_targets() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
let p = json!({"positions": ["bottomRight", "topLeft"], "size": 20, "weight": 0.5, "inset": -30, "ink": "Plate Red"});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let t = targets(&g);
|
||||
assert_eq!(t.len(), 2);
|
||||
// Drawn in POSITIONS order: top left first. A negative inset puts the targets outside.
|
||||
let tl = bounds(&t[0][0]).center();
|
||||
let br = bounds(&t[1][0]).center();
|
||||
assert!(close(tl.x, -20.0) && close(tl.y, -20.0), "{tl:?}");
|
||||
assert!(close(br.x, 620.0) && close(br.y, 420.0), "{br:?}");
|
||||
assert!(close(bounds(&t[0][0]).width(), 10.0), "the ring is half the target's width");
|
||||
assert!(close(bounds(&t[0][1]).width(), 20.0));
|
||||
for p in t.iter().flatten() {
|
||||
assert_eq!(swatch_of(&p.appearance.stroke_paint()).as_deref(), Some("Plate Red"), "the stroke links to the spot swatch");
|
||||
assert!(close(p.appearance.stroke_width(), 0.5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_replaces_the_marks_and_an_unchanged_run_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let first = run(&mut s, json!({"size": 30}));
|
||||
let layer = first["layer"].clone();
|
||||
let undo = undo_len(&s);
|
||||
let again = run(&mut s, json!({"size": 30}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
assert_eq!(again["ids"], first["ids"], "the same group stays");
|
||||
assert_eq!(undo_len(&s), undo, "nothing changed: no undo step");
|
||||
let r = run(&mut s, json!({"size": 40, "positions": ["top"]}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert_eq!(r["layer"], layer, "the same layer is reused");
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.layers.len(), 2, "no second marks layer");
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
assert_eq!(kids.len(), 1, "the earlier marks are replaced");
|
||||
let t = targets(&kids[0]);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert!(close(bounds(&t[0][1]).width(), 40.0));
|
||||
assert!(doc.node(NodeId(first["ids"][0].as_u64().unwrap())).is_none(), "the earlier group is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widening_an_artboard_without_changing_the_marks_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let p = json!({"positions": ["topLeft"]});
|
||||
let first = run(&mut s, p.clone());
|
||||
let before = node(&s, first["ids"][0].as_u64().unwrap());
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 800})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let again = run(&mut s, p);
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
assert_eq!(again["ids"], first["ids"], "the same group stays");
|
||||
assert!(node(&s, again["ids"][0].as_u64().unwrap()) == before, "the existing group stays unchanged");
|
||||
assert_eq!(undo_len(&s), undo, "unchanged marks add no undo step after a resize");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_the_marks_keeps_a_selected_slice_selected() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("object.slice.make", &json!({})).unwrap();
|
||||
s.execute("select.object.slices", &json!({})).unwrap();
|
||||
let before = s.doc().unwrap().selection.clone();
|
||||
assert!(!before.slices.is_empty());
|
||||
let r = run(&mut s, json!({"size": 50}));
|
||||
assert_eq!(r["changed"], json!(true));
|
||||
assert!(s.doc().unwrap().selection == before, "the selection is kept as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_past_the_canvas_edge_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 3999000, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "inset": -1000})).unwrap_err().to_string();
|
||||
assert!(err.contains("edge of the canvas"), "{err}");
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_target_weight_does_not_pad_lines_of_type_at_the_canvas_edge() {
|
||||
let mut s = session();
|
||||
// The artboard ends 10 pt inside the canvas edge.
|
||||
s.execute("artboard.new", &json!({"x": 3999090, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
let p = json!({"artboard": 1, "positions": [], "info": true, "textAlign": "right", "inset": 0, "weight": 20});
|
||||
let r = run(&mut s, p);
|
||||
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_reaches_past_its_paths_by_half_its_weight_at_the_canvas_edge() {
|
||||
let mut s = session();
|
||||
// The artboard ends at the canvas edge.
|
||||
s.execute("artboard.new", &json!({"x": 3999100, "y": 0, "width": 900, "height": 100})).unwrap();
|
||||
// The cross ends 15 pt inside the edge, and its 20 pt stroke reaches 10 pt past that.
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 15}));
|
||||
assert_eq!(targets(&node(&s, r["ids"][0].as_u64().unwrap())).len(), 1);
|
||||
// 5 pt inside the edge, the stroke reaches 5 pt past it.
|
||||
let err = s.execute(COMMAND, &json!({"artboard": 1, "positions": ["right"], "size": 36, "weight": 20, "inset": 5})).unwrap_err().to_string();
|
||||
assert!(err.contains("edge of the canvas"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_artboard_gets_its_group_and_one_artboard_rerun_keeps_the_others() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 800, "y": 0, "width": 200, "height": 100})).unwrap();
|
||||
let r = run(&mut s, json!({"allArtboards": true, "positions": ["top"]}));
|
||||
assert_eq!(r["ids"].as_array().unwrap().len(), 2);
|
||||
let second = node(&s, r["ids"][1].as_u64().unwrap());
|
||||
let c = bounds(&targets(&second)[0][0]).center();
|
||||
assert!(close(c.x, 900.0) && close(c.y, 36.0), "the second artboard's own target: {c:?}");
|
||||
let only = run(&mut s, json!({"artboard": 1, "positions": ["bottom"]}));
|
||||
assert_eq!(only["ids"].as_array().unwrap().len(), 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let kids = doc.layers[0].children().unwrap();
|
||||
assert_eq!(kids.len(), 2, "the first artboard's marks stay");
|
||||
assert!(kids.iter().any(|k| k.id.0 == r["ids"][0].as_u64().unwrap()));
|
||||
let c = bounds(&targets(&node(&s, only["ids"][0].as_u64().unwrap()))[0][0]).center();
|
||||
assert!(close(c.x, 900.0) && close(c.y, 64.0), "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ink_line_names_each_spot_ink_in_its_own_ink_and_the_file_line_gives_name_and_time() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Blue", "color": "#1122cc", "spot": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"colors": [{"swatch": "Plate Red", "tint": 50}]})).unwrap();
|
||||
// A tint swatch marked spot, as a file can hold one, is still a tint of its ink.
|
||||
let st = s.doc_mut().unwrap();
|
||||
let mut tints = 0;
|
||||
for w in std::sync::Arc::make_mut(&mut st.doc).swatches_iter_mut().filter(|w| w.tint_of().is_some()) {
|
||||
w.spot = true;
|
||||
tints += 1;
|
||||
}
|
||||
assert_eq!(tints, 1);
|
||||
let title = s.doc().unwrap().doc.title.clone();
|
||||
// 2026-03-04 05:06 UTC.
|
||||
let r = run(&mut s, json!({"positions": [], "inks": true, "info": true, "time": 1772600760}));
|
||||
assert_eq!(r["inks"], json!(["Plate Red", "Plate Blue"]), "spot inks only: process, tints and [Registration] left out");
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
assert!(targets(&g).is_empty());
|
||||
let l = lines(&g);
|
||||
assert_eq!(l.len(), 2);
|
||||
let names: Vec<_> = l[0].runs.iter().map(|run| (run.text.trim().to_string(), swatch_of(&run.style.fill))).collect();
|
||||
assert_eq!(names, [("Plate Red".into(), Some("Plate Red".into())), ("Plate Blue".into(), Some("Plate Blue".into()))]);
|
||||
assert_eq!(l[1].plain_text(), format!("{title} 2026-03-04 05:06 UTC"));
|
||||
assert!(l[1].runs[0].style.fill.is_registration(), "the file line prints on every plate");
|
||||
assert!(l.iter().all(|t| close(t.runs[0].style.size, 9.0)));
|
||||
// At the bottom left by default: the file line is the lower one, both 18 pt in.
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let kids = g.children().unwrap();
|
||||
let texts: Vec<_> = kids.iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).collect();
|
||||
assert!(texts[0].y1 <= texts[1].y0 + 1e-6, "the ink line sits above the file line");
|
||||
assert!((texts[1].y1 - 382.0).abs() < 0.5 && (texts[0].x0 - 18.0).abs() < 0.5, "{texts:?}");
|
||||
// No date without a time.
|
||||
let r = run(&mut s, json!({"positions": [], "info": true, "time": null}));
|
||||
assert_eq!(lines(&node(&s, r["ids"][0].as_u64().unwrap()))[0].plain_text(), title);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_at_the_top_right_start_past_a_corner_target() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
let p = json!({"positions": ["topRight"], "inks": true, "textPlace": "top", "textAlign": "right", "textSize": 12});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let target = bounds(&targets(&g)[0][1]);
|
||||
// 600 - 18 (inset) - 36 (target) - 12 (a gap of the type size).
|
||||
assert!((text.x1 - 534.0).abs() < 0.5, "{text:?}");
|
||||
assert!(text.x1 < target.x0, "the line clears the corner target");
|
||||
assert!((text.y0 - 18.0).abs() < 0.5, "{text:?}");
|
||||
assert!(close(lines(&g)[0].runs[0].style.size, 12.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_move_up_past_a_bottom_center_target_they_would_cross() {
|
||||
let mut s = session();
|
||||
let p = json!({"positions": ["bottom"], "info": true, "time": 1772600760, "textSize": 72});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the line is long enough to reach the target: {text:?} {target:?}");
|
||||
assert!(text.y1 <= target.y0, "the line sits above the bottom target: {text:?} {target:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_do_not_move_above_a_short_artboard_to_clear_a_bottom_target() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 100, "height": 56})).unwrap();
|
||||
let p = json!({"positions": [], "info": true, "time": 1772600760});
|
||||
let original = run(&mut s, p.clone());
|
||||
let original_bounds = bounds(&node(&s, original["ids"][0].as_u64().unwrap()));
|
||||
let mut with_target = p;
|
||||
with_target["positions"] = json!(["bottom"]);
|
||||
let r = run(&mut s, with_target);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| bounds(n)).unwrap();
|
||||
let target = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x0 < target.x1 && text.x1 > target.x0, "the file line reaches the bottom target: {text:?} {target:?}");
|
||||
assert!(text.y0 >= 0.0 && text.y1 <= 56.0, "the line stays vertically inside the artboard: {text:?}");
|
||||
assert_eq!(text, original_bounds, "the line keeps its original placement when shifting would leave the artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_do_not_move_onto_the_opposite_target_on_a_short_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 110})).unwrap();
|
||||
let p = json!({"artboard": 1, "positions": ["top", "bottom"], "info": true, "time": 1772600760, "textSize": 24});
|
||||
let r = run(&mut s, p);
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let text = g.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| doc.bounds_of(&[n.id], false).unwrap()).unwrap();
|
||||
let top = targets(&g)[0].iter().map(bounds).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!(text.x1 <= top.x0 || text.y0 >= top.y1, "the line stays off the top target: {text:?} {top:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_duplicated_artboard_belong_to_the_copy() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(kids(&s), 2, "the duplicate carries a copy of the marks");
|
||||
let copy = run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the duplicate replaces the copy");
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
|
||||
assert_eq!(kids(&s), 2);
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(copy["ids"][0].as_u64().unwrap())).is_some(), "the duplicate's marks stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_pasted_artboard_belong_to_the_pasted_one() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |k| k.len())).sum::<usize>();
|
||||
let before = kids(&s);
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(kids(&s), before, "marking the pasted artboard replaces the pasted copy");
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the source artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_an_artboard_paste_back_into_their_locked_layer() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the marks layer, which stays locked");
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(marks(&s), Some((true, 2)), "marking the pasted artboard replaces the pasted copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_from_an_unnamed_marks_layer_paste_back_into_it() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let st = s.doc_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).node_mut(layer).unwrap().name = None;
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let marks = |s: &Session| s.doc().unwrap().doc.node(layer).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(marks(&s), Some((true, 2)), "the pasted marks go into the unnamed marks layer, which stays locked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_into_another_document_go_into_its_marks_layer_not_a_layer_of_the_same_name() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({}));
|
||||
let layer = NodeId(r["layer"].as_u64().unwrap());
|
||||
let plain = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let kids = |s: &Session, l: NodeId| s.doc().unwrap().doc.node(l).map(|l| (l.locked, l.children().map_or(0, |k| k.len())));
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(kids(&s, layer), Some((true, 2)), "the pasted marks go into the locked marks layer");
|
||||
assert_eq!(kids(&s, plain), Some((false, 0)), "the ordinary layer of the same name stays empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_without_a_marks_layer_make_one_and_skip_a_layer_of_the_same_name() {
|
||||
for props in [json!({}), json!({"visible": false}), json!({"locked": true})] {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let plain = s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].clone();
|
||||
let mut set = props.clone();
|
||||
set["id"] = plain.clone();
|
||||
s.execute("layer.setProps", &set).unwrap();
|
||||
let plain = NodeId(plain.as_u64().unwrap());
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.artboards.len(), 2, "{props}");
|
||||
assert_eq!(doc.node(plain).and_then(|l| l.children().map(|k| k.len())), Some(0), "the ordinary layer stays empty: {props}");
|
||||
let made: Vec<_> = doc.layers.iter().filter(|l| l.id != plain && l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(made.len(), 1, "a marks layer is made: {props}");
|
||||
assert_eq!(made[0].children().map_or(0, |k| k.len()), 1, "the pasted marks go into it: {props}");
|
||||
let made = made[0].id.0;
|
||||
let r = run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
assert_eq!(r["layer"], json!(made), "the command uses the made layer: {props}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_and_art_from_a_layer_of_the_same_name_paste_into_separate_layers() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "name": "Renamed Marks"})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
for paste in 1..=2 {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let marks = super::layer_id(doc).expect("a marks layer is made");
|
||||
let named: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(named.len(), 2, "the marks layer and the ordinary layer are separate: paste {paste}");
|
||||
for l in named {
|
||||
let items = l.children().unwrap().len();
|
||||
assert_eq!(items, paste, "each paste adds one item to each layer: paste {paste}, marks {}", l.id == marks);
|
||||
}
|
||||
let ordinary = doc.layers.iter().find(|l| l.name.as_deref() == Some(LAYER_NAME) && l.id != marks).unwrap();
|
||||
assert_eq!(ordinary.children().unwrap().len(), paste, "the ordinary layer holds one rectangle per paste: paste {paste}");
|
||||
assert!(
|
||||
ordinary.children().unwrap().iter().all(|k| k.children().is_none()),
|
||||
"only the rectangle goes into the ordinary layer: paste {paste}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_pasted_again_skips_a_marks_layer_above_its_ordinary_layer() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
let ordinary = NodeId(s.execute("layer.new", &json!({"name": LAYER_NAME})).unwrap()["id"].as_u64().unwrap());
|
||||
for paste in 1..=2 {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let marks = super::layer_id(doc).expect("a marks layer is made");
|
||||
assert_ne!(marks, ordinary);
|
||||
let kids = |l: NodeId| doc.node(l).unwrap().children().unwrap().iter().map(|k| k.children().is_none()).collect::<Vec<_>>();
|
||||
assert_eq!(kids(ordinary), vec![true; paste], "the rectangles go into the ordinary layer: paste {paste}");
|
||||
assert_eq!(kids(marks), vec![false; paste], "only marks go into the marks layer: paste {paste}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_off_an_artboard_go_with_its_copy_made_by_moving_it() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
let b = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert!(b.x0 >= 600.0, "the marks lie wholly off the artboard: {b:?}");
|
||||
let p = json!({"index": 0, "dy": 500, "copy": true, "moveArt": true, "lockedAndHidden": true});
|
||||
s.execute("artboard.move", &p).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(kids(&s), 2, "the copy carries a copy of the marks");
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_art_copied_with_an_artboard_does_not_paste_into_a_locked_layer() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": other, "locked": true})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("edit.paste", &json!({})).unwrap_err().to_string();
|
||||
assert!(err.contains("locked or hidden"), "{err}");
|
||||
assert!(s.doc().unwrap().doc == before, "nothing is pasted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_pasted_after_their_layer_was_deleted_are_found_again() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, json!({}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("layer.delete", &json!({"ids": [r["layer"]]})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
run(&mut s, json!({"artboard": 1, "size": 30}));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let layers: Vec<_> = doc.layers.iter().filter(|l| l.name.as_deref() == Some(LAYER_NAME)).collect();
|
||||
assert_eq!(layers.len(), 1, "one marks layer");
|
||||
assert_eq!(layers[0].children().unwrap().len(), 1, "marking the pasted artboard replaces the pasted copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_artboards_marks_lying_on_a_copied_artboard_stay_with_their_own() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
let g = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let b = bounds(&g);
|
||||
assert!(b.x0 >= 700.0 && b.x1 <= 1300.0, "the marks lie wholly on the second artboard: {b:?}");
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), 1, "duplicating the second artboard leaves the first one's marks out");
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let copied = s.execute("artboard.copy", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(copied["copied"], json!(0), "copying the second artboard leaves the first one's marks out");
|
||||
let again = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicating_overlapping_artboards_copies_marks_lying_on_both_once() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
|
||||
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the second artboard's copy carries its marks");
|
||||
let copy = run(&mut s, json!({"artboard": 3, "positions": ["left"], "size": 30}));
|
||||
assert_eq!(copy["changed"], json!(true));
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "marking that copy replaces the copied marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_on_another_copied_artboard_go_with_their_own_artboards_copy() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let p = json!({"positions": ["right"], "inset": -200});
|
||||
run(&mut s, p.clone());
|
||||
s.execute("artboard.duplicate", &json!({"indices": [0, 1], "art": true, "lockedAndHidden": true})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks");
|
||||
run(&mut s, json!({"artboard": 2, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the first artboard's copy replaces the copied marks");
|
||||
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
/// `target` (`index` or `indices`) with the parameters each artboard copy command takes: an
|
||||
/// Alt-drag for `artboard.move`, and the artboards' art for the others.
|
||||
fn copy_params(command: &str, target: Value) -> Value {
|
||||
let mut p = match command {
|
||||
"artboard.move" => json!({"moveArt": true, "copy": true, "dy": 500, "lockedAndHidden": true}),
|
||||
_ => json!({"art": true, "lockedAndHidden": true}),
|
||||
};
|
||||
if let (Some(p), Some(t)) = (p.as_object_mut(), target.as_object()) {
|
||||
p.extend(t.clone());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_artboard_copies_keep_one_marks_group_per_owner() {
|
||||
for command in ["artboard.duplicate", "artboard.move", "artboard.copy"] {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let first = run(&mut s, json!({"artboard": 0, "positions": ["right"]}));
|
||||
let second = run(&mut s, json!({"artboard": 1, "positions": ["left"]}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let originals = [node(&s, first["ids"][0].as_u64().unwrap()), node(&s, second["ids"][0].as_u64().unwrap())];
|
||||
let p = copy_params(command, json!({"indices": [0, 1]}));
|
||||
s.execute(command, &p).unwrap();
|
||||
if command == "artboard.copy" {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let groups = d.layers[0].children().unwrap();
|
||||
assert_eq!(groups.len(), 4, "{command}");
|
||||
for (source, original) in originals.iter().enumerate() {
|
||||
assert!(d.node(original.id).unwrap() == original, "{command}");
|
||||
let copied_board = &d.artboards[source + 2];
|
||||
let copies: Vec<_> = groups.iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
|
||||
assert_eq!(copies.len(), 1, "{command}: owner {source}");
|
||||
let offset = copied_board.rect.origin() - d.artboards[source].rect.origin();
|
||||
assert_eq!(bounds(copies[0]), bounds(original) + offset, "{command}: owner {source}");
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before, "{command}: one undo restores both artboards and marks");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_board_marks_follow_artboard_copies_and_cuts_by_owner() {
|
||||
for command in ["artboard.duplicate", "artboard.move", "artboard.copy", "artboard.cut"] {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
|
||||
let original = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
|
||||
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
|
||||
assert!(bounds(&original).y1 < 0.0);
|
||||
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let p = copy_params(command, json!({"index": 0}));
|
||||
let reply = s.execute(command, &p).unwrap();
|
||||
if command == "artboard.cut" {
|
||||
assert_eq!(reply["copied"], json!(1));
|
||||
assert!(s.doc().unwrap().doc.node(original.id).is_none());
|
||||
}
|
||||
if matches!(command, "artboard.copy" | "artboard.cut") {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let copied_board = d.artboards.last().unwrap();
|
||||
let copies: Vec<_> = d.layers[0].children().unwrap().iter().filter(|g| super::owner(g) == Some(copied_board.id)).collect();
|
||||
assert_eq!(copies.len(), 1, "{command}");
|
||||
assert!(d.node(foreign.id).unwrap() == &foreign, "{command}: another artboard's marks stay unchanged");
|
||||
let offset = copied_board.rect.origin() - before.artboards[0].rect.origin();
|
||||
assert_eq!(bounds(copies[0]), bounds(&original) + offset, "{command}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
if command == "artboard.cut" {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_uses_marks_ownership_instead_of_containment() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let outside = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}));
|
||||
let other = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}));
|
||||
let own = node(&s, outside["ids"][0].as_u64().unwrap());
|
||||
let foreign = node(&s, other["ids"][0].as_u64().unwrap());
|
||||
assert!(bounds(&own).y1 < 0.0);
|
||||
assert!(s.doc().unwrap().doc.artboards[0].rect.contains_rect(bounds(&foreign)));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for (move_art, all) in [(false, true), (true, false)] {
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": move_art, "lockedAndHidden": all})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own);
|
||||
assert!(node(&s, foreign.id.0) == foreign);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
}
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let start = bounds(&own);
|
||||
let moved = bounds(&node(&s, own.id.0));
|
||||
let expected = (start.x0, start.y0 + 500.0, start.x1, start.y1 + 500.0);
|
||||
assert_eq!((moved.x0, moved.y0, moved.x1, moved.y1), expected, "the marks move 500 pt down with their artboard");
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert_eq!(board.y0, before.artboards[0].rect.y0 + 500.0, "the artboard itself moved");
|
||||
assert!(moved.y1 < board.y0, "the top marks stay above their moved artboard");
|
||||
assert!(node(&s, foreign.id.0) == foreign);
|
||||
assert_eq!(super::owner(&node(&s, own.id.0)), super::owner(&own));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_lying_on_another_artboard_go_with_their_own_artboards_copy_alone() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let p = json!({"positions": ["right"], "inset": -200});
|
||||
run(&mut s, p.clone());
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true})).unwrap();
|
||||
assert_eq!(kids(&s), 1, "the locked marks stay without lockedAndHidden");
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), 2, "the first artboard's copy carries its marks lying on the second artboard");
|
||||
run(&mut s, json!({"artboard": 3, "positions": ["right"], "inset": -200, "size": 30}));
|
||||
assert_eq!(kids(&s), 2, "marking the copy replaces the copied marks");
|
||||
assert_eq!(run(&mut s, p)["changed"], json!(false), "the first artboard's marks are unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marks_group_moved_off_the_marks_layer_is_copied_like_other_art() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[1].children().unwrap().len();
|
||||
let before = kids(&s);
|
||||
s.execute("artboard.duplicate", &json!({"index": 1, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(kids(&s), before + 1, "the duplicate carries a copy of the moved group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_of_a_deleted_artboard_are_copied_like_other_art() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"positions": ["right"], "inset": -200}));
|
||||
s.execute("artboard.delete", &json!({"indices": [0]})).unwrap();
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the duplicate carries a copy of the marks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_copied_with_a_duplicated_artboard_stay_with_the_copy_after_a_resize() {
|
||||
let mut s = session();
|
||||
run(&mut s, json!({}));
|
||||
s.execute("artboard.duplicate", &json!({"index": 0, "art": true, "lockedAndHidden": true})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "width": 500})).unwrap();
|
||||
let kids = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
let source = run(&mut s, json!({}));
|
||||
assert_eq!(source["changed"], json!(false), "the copy's marks are not the source's");
|
||||
assert_eq!(kids(&s), 2);
|
||||
run(&mut s, json!({"artboard": 1}));
|
||||
assert_eq!(kids(&s), 2, "marking the resized duplicate replaces the copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrinking_an_artboard_keeps_its_marks_when_a_new_artboard_covers_more_of_the_stored_rectangle() {
|
||||
let mut s = session();
|
||||
let original = run(&mut s, json!({}));
|
||||
let id = original["ids"][0].as_u64().unwrap();
|
||||
let before = node(&s, id);
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "width": 100})).unwrap();
|
||||
s.execute("artboard.new", &json!({"x": 120, "y": 0, "width": 480, "height": 400})).unwrap();
|
||||
run(&mut s, json!({"artboard": 1}));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_some(), "marking the new artboard keeps the original group");
|
||||
assert!(node(&s, id) == before, "the original group's art and metadata stay unchanged");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
run(&mut s, json!({"artboard": 0}));
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id)).is_none(), "marking the resized source replaces its old group");
|
||||
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_that_reach_onto_the_next_artboard_stay_with_their_own() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 620, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
|
||||
let ids = r["ids"].as_array().unwrap();
|
||||
assert_eq!(ids.len(), 2);
|
||||
for id in ids {
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some(), "group {id} is kept");
|
||||
}
|
||||
let again = run(&mut s, json!({"allArtboards": true, "positions": ["right"], "inset": -60}));
|
||||
assert_eq!(again["changed"], json!(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_refused_and_leave_the_document_unchanged() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Process", "color": "#22cc11"})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = undo_len(&s);
|
||||
for bad in [
|
||||
json!({"positions": ["middle"]}),
|
||||
json!({"positions": ["top", "top"]}),
|
||||
json!({"positions": "top"}),
|
||||
json!({"positions": [1]}),
|
||||
json!({"size": 2}),
|
||||
json!({"size": "36"}),
|
||||
json!({"weight": 0}),
|
||||
json!({"inset": 5000}),
|
||||
json!({"textSize": 100}),
|
||||
json!({"textPlace": "middle"}),
|
||||
json!({"textAlign": 1}),
|
||||
json!({"ink": "Nope"}),
|
||||
json!({"ink": "Process"}),
|
||||
json!({"ink": 3}),
|
||||
json!({"inks": "yes"}),
|
||||
json!({"info": 1}),
|
||||
json!({"time": "today", "info": true}),
|
||||
json!({"artboard": 5}),
|
||||
json!({"artboard": -1}),
|
||||
json!({"artboard": 0, "allArtboards": true}),
|
||||
json!({"positions": null}),
|
||||
json!({"artboard": null}),
|
||||
json!({"size": null}),
|
||||
json!({"positions": [], "inks": false, "info": false}),
|
||||
json!({"positions": [], "inks": true}),
|
||||
] {
|
||||
assert!(s.execute(COMMAND, &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
// An ink line with no spot inks draws the targets and no line.
|
||||
let r = run(&mut s, json!({"inks": true}));
|
||||
assert_eq!(r["inks"], json!([]));
|
||||
assert!(lines(&node(&s, r["ids"][0].as_u64().unwrap())).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_of_a_deleted_artboard_belong_to_no_artboard_that_later_takes_its_id() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
let gone = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "the marks stay as art");
|
||||
// A reopened file does not remember the deleted id, so a new artboard can take it.
|
||||
assert!(!super::managed_owners(&s.doc().unwrap().doc).values().any(|o| *o == gone), "no marks group names the deleted artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_moved_off_the_marks_layer_forget_their_deleted_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 1, "positions": ["right"]}));
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
let other = s.doc().unwrap().doc.layers[1].id.0;
|
||||
s.execute("layer.move", &json!({"ids": [r["ids"][0]], "target": other})).unwrap();
|
||||
s.execute("artboard.delete", &json!({"indices": [1]})).unwrap();
|
||||
assert_eq!(super::owner(&node(&s, r["ids"][0].as_u64().unwrap())), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_leaves_its_marks_lying_on_another_locked_artboard() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let own = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
s.execute("artboard.move", &json!({"index": 0, "dy": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "Move Artboard leaves them on the locked artboard");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "a new position leaves them on the locked artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_artboard_scaled_in_the_same_call_leaves_a_moving_artboards_marks_to_it() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
let edits = json!([{"index": 1, "width": 1200}, {"index": 0, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let moved = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert_eq!((moved.x0, moved.y0, moved.width()), (start.x0, start.y0 + 500.0, start.width()), "the marks move with their own artboard, unscaled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_on_an_artboard_unlocked_in_the_same_call_stay_when_their_own_artboard_moves() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let r = run(&mut s, json!({"artboard": 0, "positions": ["right"], "inset": -200}));
|
||||
let own = node(&s, r["ids"][0].as_u64().unwrap());
|
||||
s.execute("layer.setProps", &json!({"id": r["layer"], "locked": false})).unwrap();
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "the marks lay on a locked artboard when the call began");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let edits = json!([{"index": 0, "y": 500}, {"index": 1, "locked": false, "width": 1200}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": false})).unwrap();
|
||||
assert!(node(&s, own.id.0) == own, "the artboard scaled in the same call leaves them too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marks_group_of_a_missing_artboard_goes_with_the_first_listed_artboard() {
|
||||
let mut s = session();
|
||||
for _ in 0..2 {
|
||||
s.execute("artboard.new", &json!({"x": 0, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
}
|
||||
let r = run(&mut s, json!({"artboard": 2, "positions": ["top"]}));
|
||||
// A file saved before deleting an artboard cleared its marks' tag.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.remove(2);
|
||||
let start = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
let edits = json!([{"index": 0, "width": 1200}, {"index": 1, "y": 500}]);
|
||||
s.execute("artboard.setProps", &json!({"artboards": edits, "scaleArt": true, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let now = bounds(&node(&s, r["ids"][0].as_u64().unwrap()));
|
||||
assert!(close(now.width(), start.width() * 2.0), "it scales with the first artboard listed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboard_by_its_position_takes_its_own_marks_and_leaves_others() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let own = run(&mut s, json!({"artboard": 0, "positions": ["top"], "inset": -200}))["ids"][0].as_u64().unwrap();
|
||||
let foreign = run(&mut s, json!({"artboard": 1, "positions": ["left"], "inset": -200}))["ids"][0].as_u64().unwrap();
|
||||
let (own, foreign) = (node(&s, own), node(&s, foreign));
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "y": 500, "moveArt": true, "lockedAndHidden": true})).unwrap();
|
||||
let start = bounds(&own);
|
||||
let moved = bounds(&node(&s, own.id.0));
|
||||
assert_eq!((moved.x0, moved.y0), (start.x0, start.y0 + 500.0), "the marks lying above the artboard move with it");
|
||||
assert!(node(&s, foreign.id.0) == foreign, "another artboard's marks lying on it stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_drawn_on_the_active_artboard_record_it_for_a_replay() {
|
||||
let mut s = session();
|
||||
s.execute("artboard.new", &json!({"x": 700, "y": 0, "width": 600, "height": 400})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(second);
|
||||
let start = s.journal.len();
|
||||
run(&mut s, json!({"positions": ["right"]}));
|
||||
let (cmd, recorded) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(cmd, COMMAND);
|
||||
assert_eq!(recorded["activeArtboard"], json!(1), "the journal names the artboard the marks went on");
|
||||
// A replay on another active artboard marks the recorded one.
|
||||
let first = s.doc().unwrap().doc.artboards[0].id;
|
||||
s.doc_mut().unwrap().active_artboard = Some(first);
|
||||
let replayed = run(&mut s, recorded);
|
||||
assert_eq!(replayed["changed"], json!(false), "the second artboard's marks are drawn again the same");
|
||||
// A recorded action leaves it out and marks the artboard active when it plays.
|
||||
let action = s.journal_for_action(start);
|
||||
assert_eq!(action.len(), 2, "the action holds the first run and the replay");
|
||||
assert!(action.iter().all(|(_, p)| p.get("activeArtboard").is_none()));
|
||||
}
|
||||
@@ -189,7 +189,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Paste",
|
||||
["Edit"],
|
||||
Some("Cmd+V"),
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own, also for a pie in the art of a symbol, pattern, brush or graph design the paste brings) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted, except the Screen Print Marks layer for the marks copied with their artboard). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
|
||||
has_clipboard,
|
||||
|s, p| paste(s, p, PasteMode::Offset)
|
||||
),
|
||||
@@ -1657,9 +1657,16 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
&& inside.is_none()
|
||||
&& (st.doc.paste_remembers_layers || boards.is_some())
|
||||
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
|
||||
// Screen print marks copied with an artboard that is pasted once go back into the marks layer,
|
||||
// locked or hidden as it is.
|
||||
let pasted_once: Vec<u32> = match boards {
|
||||
Some((all, _)) => all.iter().map(|a| a.id).filter(|id| all.iter().filter(|a| a.id == *id).count() == 1).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
let marks: Vec<bool> = clip.nodes.iter().map(|n| super::addons::screen_marks_of(n, &pasted_once)).collect();
|
||||
// Each object's remembered layer, found before anything is pasted: a hidden or locked one
|
||||
// refuses the whole paste.
|
||||
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] };
|
||||
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, &marks, same_doc)? } else { vec![] };
|
||||
// Front/back: relative to the selection (top-most / bottom-most selected object); with
|
||||
// nothing selected, the top / bottom of the current layer. Art other than paths goes beside
|
||||
// the compound path that holds the selected object, not into it.
|
||||
@@ -1700,13 +1707,22 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let mut imported = clip.import_into(d, choices, same_doc)?;
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
let artboards: Vec<usize> = boards
|
||||
let made_boards: Vec<(u32, usize)> = boards
|
||||
.into_iter()
|
||||
.flat_map(|(all, dv)| all.iter().map(move |a| (a, dv)))
|
||||
.map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv))
|
||||
.map(|(a, dv)| (a.id, super::panelcmds::push_artboard_copy(d, a, a.rect + dv)))
|
||||
.collect();
|
||||
let artboards: Vec<usize> = made_boards.iter().map(|(_, i)| *i).collect();
|
||||
// Screen print marks copied with an artboard pasted once belong to the pasted artboard.
|
||||
let board_ids: Vec<(u32, u32)> = made_boards
|
||||
.iter()
|
||||
.filter(|(src, _)| made_boards.iter().filter(|(s, _)| s == src).count() == 1)
|
||||
.filter_map(|(src, i)| d.artboards.get(*i).map(|a| (*src, a.id)))
|
||||
.collect();
|
||||
// The layers made for remembered layers the document lacks, by parent and name.
|
||||
let mut made = HashMap::new();
|
||||
// The marks layer made for screen print marks, kept apart from ordinary layers of its name.
|
||||
let mut made_marks: HashMap<(Option<NodeId>, String), NodeId> = HashMap::new();
|
||||
// Objects pasted into each parent so far (keeps their order in front and back pastes).
|
||||
let mut placed: BTreeMap<Option<NodeId>, usize> = BTreeMap::new();
|
||||
let mut new_ids = vec![];
|
||||
@@ -1721,6 +1737,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c, d);
|
||||
let marks = board_ids.iter().any(|(from, to)| super::addons::retag_screen_marks(&mut c, *from, *to));
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
// A cross-document drag carries the graphic's appearance with it,
|
||||
@@ -1729,7 +1746,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
let layer = match remembered.get(k) {
|
||||
Some(Some(Remembered::Layer(l))) => Some(*l),
|
||||
Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?,
|
||||
Some(Some(Remembered::Make { parent, names })) => make_remembered(d, &mut made, &mut made_marks, marks, *parent, names)?,
|
||||
_ => None,
|
||||
};
|
||||
// In a clip group or a clipping layer the bottom child is the clipping path: art pasted
|
||||
@@ -1869,18 +1886,27 @@ enum Remembered {
|
||||
Make { parent: Option<NodeId>, names: Vec<String> },
|
||||
}
|
||||
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new();
|
||||
/// [`remembered_layer`] for each object's source layer, worked out once for each layer. The objects
|
||||
/// `marks` marks are screen print marks groups, which may go back into the marks layer while it
|
||||
/// is locked or hidden.
|
||||
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], marks: &[bool], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
|
||||
let mut found: HashMap<(&SourceLayer, bool), Remembered> = HashMap::new();
|
||||
sources
|
||||
.iter()
|
||||
.map(|src| {
|
||||
.enumerate()
|
||||
.map(|(k, src)| {
|
||||
// A marks group goes into the marks layer even when the layer it was copied from has
|
||||
// no name.
|
||||
if marks.get(k).copied().unwrap_or(false) && src.is_none() {
|
||||
return Ok(Some(marks_layer_target(d)));
|
||||
}
|
||||
let Some(src) = src else { return Ok(None) };
|
||||
if let Some(r) = found.get(src) {
|
||||
let key = (src, marks.get(k).copied().unwrap_or(false));
|
||||
if let Some(r) = found.get(&key) {
|
||||
return Ok(Some(r.clone()));
|
||||
}
|
||||
let r = remembered_layer(d, src, same_doc)?;
|
||||
found.insert(src, r.clone());
|
||||
let r = remembered_layer(d, src, key.1, same_doc)?;
|
||||
found.insert(key, r.clone());
|
||||
Ok(Some(r))
|
||||
})
|
||||
.collect()
|
||||
@@ -1891,8 +1917,15 @@ fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bo
|
||||
/// it still where they were (by id) are kept. Below them, and in another document from the top,
|
||||
/// each name is matched among the layers inside the one above (the topmost of the same name whose
|
||||
/// layers match the most names, a shown and unlocked one first). The names left unmatched are
|
||||
/// made. A matched layer that is hidden or locked, or inside one that is, is an error.
|
||||
fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<Remembered> {
|
||||
/// made. A matched layer that is hidden or locked, or inside one that is, is an error. A screen
|
||||
/// print marks group (`marks`) goes into the document's marks layer, locked or hidden as it is,
|
||||
/// or into a new top-level marks layer when the document has none.
|
||||
fn remembered_layer(d: &Document, src: &SourceLayer, marks: bool, same_doc: bool) -> Result<Remembered> {
|
||||
// A marks group goes into the document's marks layer, never into an ordinary layer of the
|
||||
// same name.
|
||||
if marks {
|
||||
return Ok(marks_layer_target(d));
|
||||
}
|
||||
let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last());
|
||||
let kept = if same_doc && src.ids.last().is_some_and(held) {
|
||||
src.ids.len()
|
||||
@@ -1917,6 +1950,15 @@ fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<R
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a screen print marks group goes: the document's marks layer, locked or hidden as it is,
|
||||
/// or a new top-level marks layer when the document has none.
|
||||
fn marks_layer_target(d: &Document) -> Remembered {
|
||||
match super::addons::screen_marks_layer(d) {
|
||||
Some(l) => Remembered::Layer(l),
|
||||
None => Remembered::Make { parent: None, names: vec![super::addons::SCREEN_MARKS_LAYER.to_string()] },
|
||||
}
|
||||
}
|
||||
|
||||
/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the
|
||||
/// other: its last layer (`parent` when none matches), how many names it matched and whether all
|
||||
/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins.
|
||||
@@ -1927,7 +1969,9 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
None => Some(&d.layers),
|
||||
Some(p) => d.node(p).and_then(Node::children),
|
||||
};
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) {
|
||||
// Ordinary art never goes into the screen print marks layer by its name.
|
||||
let marks_layer = parent.is_none().then(|| super::addons::screen_marks_layer(d)).flatten();
|
||||
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str()) && Some(l.id) != marks_layer) {
|
||||
let (end, n, open) = named_chain(d, Some(l.id), rest);
|
||||
let chain = (end, n + 1, open && l.visible && !l.locked);
|
||||
if (chain.1, chain.2) > (best.1, best.2) {
|
||||
@@ -1937,6 +1981,25 @@ fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Optio
|
||||
best
|
||||
}
|
||||
|
||||
/// Makes the layers of a `Remembered::Make` for one pasted object. The marks layer for a screen
|
||||
/// print marks group (`marks`) is made apart from ordinary layers of its name (`made_marks`) and
|
||||
/// becomes the marks layer, so Create Screen Print Marks finds the copy there.
|
||||
fn make_remembered(
|
||||
d: &mut Document,
|
||||
made: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
made_marks: &mut HashMap<(Option<NodeId>, String), NodeId>,
|
||||
marks: bool,
|
||||
parent: Option<NodeId>,
|
||||
names: &[String],
|
||||
) -> Result<Option<NodeId>> {
|
||||
let is_marks = marks && parent.is_none() && matches!(names, [n] if n == super::addons::SCREEN_MARKS_LAYER);
|
||||
let last = make_layers(d, if is_marks { made_marks } else { made }, parent, names)?;
|
||||
if let (true, Some(l)) = (is_marks, last) {
|
||||
super::addons::adopt_screen_marks_layer(d, l);
|
||||
}
|
||||
Ok(last)
|
||||
}
|
||||
|
||||
/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made`
|
||||
/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or
|
||||
/// none when `names` is empty.
|
||||
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Artboard Options…",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
"{index | artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on. Supported artboard exports and printing include it by default. This includes raster exports with `selectedOnly: true` when the output area is an artboard. Set `includeArtboardFill: false` on the export or print command to omit it. Exports cropped to selection bounds, artwork bounds, or an explicit raster region leave it out, as do formats that do not support artboard fills) | null (no background color), guideLabel?: name | \"#rrggbb\" | null (the guide label: the canvas draws the artboard's own guides (guide.add with artboard) in this color instead of the guide color preference, selected ones still in the selection color; a layer color's name spelled exactly as Layer Options lists it (\"Light Blue\", \"Red\", …) or #rrggbb; null for none, which new artboards and older files have; screen-only, so exports and print leave it out; it can change on a locked artboard; an invalid value anywhere in the list changes nothing), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard, and the artboard's own screen print marks group wherever it lies, while another artboard's group lying on it stays with its own), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}; no undo step when nothing changes",
|
||||
has_doc,
|
||||
artboard_set
|
||||
),
|
||||
@@ -1273,6 +1273,7 @@ pub(crate) fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Sele
|
||||
for &id in &gone {
|
||||
d.retire_artboard_id(id);
|
||||
}
|
||||
super::addons::release_screen_marks(d, &gone);
|
||||
d.retain_guides(sel, |g| !g.artboard.is_some_and(|a| gone.contains(&a)));
|
||||
count_artboard_pass();
|
||||
Ok(())
|
||||
@@ -1417,7 +1418,6 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let delta = now.origin() - was.origin();
|
||||
let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO;
|
||||
let transform = fit.or_else(|| moving.then(|| Affine::translate(delta)));
|
||||
let art = if transform.is_some() { d.art_moving_with(index, all).into_iter().filter(|id| taken.insert(*id)).collect() } else { vec![] };
|
||||
edits.push(ArtboardEdit {
|
||||
index,
|
||||
now,
|
||||
@@ -1433,9 +1433,29 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
resized,
|
||||
fit,
|
||||
transform,
|
||||
art,
|
||||
art: vec![],
|
||||
});
|
||||
}
|
||||
// The artboards that move take their own screen print marks groups wherever they lie, and not
|
||||
// another artboard's lying on them, as Move Artboard does. An artboard that scales in the same
|
||||
// call leaves a moving artboard's marks lying on it to their own artboard.
|
||||
// One pass for all of them, in the order listed.
|
||||
let movers: Vec<usize> = edits.iter().filter(|e| e.transform.is_some() && e.fit.is_none()).map(|e| e.index).collect();
|
||||
let mut found = super::panelcmds::artboards_art(s, &movers, true, all, true)?.into_iter();
|
||||
let moved: Vec<Option<Vec<NodeId>>> =
|
||||
edits.iter().map(|e| (e.transform.is_some() && e.fit.is_none()).then(|| found.next().map(|(_, a)| a).unwrap_or_default())).collect();
|
||||
// Every group that belongs to a moving artboard, taken by it or left where it is; a group whose
|
||||
// artboard was deleted is ordinary art.
|
||||
let boards: HashSet<u32> = movers.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.id)).collect();
|
||||
let reserved: HashSet<NodeId> = super::addons::screen_marks_owners(d).into_iter().filter(|(_, o)| boards.contains(o)).map(|(id, _)| id).collect();
|
||||
for (e, own) in edits.iter_mut().zip(moved) {
|
||||
let art = match own {
|
||||
Some(art) => art,
|
||||
None if e.fit.is_some() => d.art_moving_with(e.index, all).into_iter().filter(|id| !reserved.contains(id)).collect(),
|
||||
None => vec![],
|
||||
};
|
||||
e.art = art.into_iter().filter(|id| taken.insert(*id)).collect();
|
||||
}
|
||||
// Nothing to change: no undo step.
|
||||
if !edits.iter().any(|e| d.artboards.get(e.index).is_none_or(|a| e.changes(a))) {
|
||||
return if scale_art { Ok(json!({ "scaled": [] })) } else { ok() };
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, a locked one, or the one an open Create Font Sheet dialog uses; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden). With art, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden; edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -306,16 +306,74 @@ pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving:
|
||||
})
|
||||
}
|
||||
|
||||
/// `arts` (artboard indices with their art) with each artboard's screen print marks group in its
|
||||
/// own artboard's entry: another artboard's group lying on one of them goes with its own artboard
|
||||
/// when that one is among `arts`, and is left out when it is not. Only the groups on the marks
|
||||
/// layer count; a group whose artboard was deleted stays where it is.
|
||||
/// `held(i, id)` says group `id` stays put for artboard `i`.
|
||||
pub(crate) fn marks_with_owners(
|
||||
d: &vectorcraft_doc::Document,
|
||||
arts: Vec<(usize, Vec<NodeId>)>,
|
||||
held: impl Fn(usize, NodeId) -> bool,
|
||||
) -> Vec<(usize, Vec<NodeId>)> {
|
||||
let owners = super::addons::screen_marks_owners(d);
|
||||
if owners.is_empty() {
|
||||
return arts;
|
||||
}
|
||||
let board = |i: usize| d.artboards.get(i).map(|a| a.id);
|
||||
let owner = |id: NodeId| owners.get(&id).copied().filter(|o| d.artboards.iter().any(|a| a.id == *o));
|
||||
let mut moved: Vec<(u32, NodeId)> = vec![];
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = arts
|
||||
.into_iter()
|
||||
.map(|(i, art)| {
|
||||
let art = art
|
||||
.into_iter()
|
||||
.filter(|id| match owner(*id) {
|
||||
Some(o) if Some(o) != board(i) => {
|
||||
moved.push((o, *id));
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
.collect();
|
||||
(i, art)
|
||||
})
|
||||
.collect();
|
||||
for (o, id) in moved {
|
||||
if let Some((i, art)) = arts.iter_mut().find(|(i, _)| board(*i) == Some(o))
|
||||
&& !held(*i, id)
|
||||
{
|
||||
art.push(id);
|
||||
}
|
||||
}
|
||||
arts
|
||||
}
|
||||
|
||||
/// Each of `indices` with the art that goes with it when `art` ([`artboard_art`]), an object
|
||||
/// counted once, with the first of them it is on (artboards can overlap).
|
||||
/// counted once, with the first of them it is on (artboards can overlap). With `art`, each
|
||||
/// artboard takes its own eligible screen print marks group, wherever the group lies.
|
||||
pub(crate) fn artboards_art(s: &Session, indices: &[usize], art: bool, all: bool, moving: bool) -> Result<Vec<(usize, Vec<NodeId>)>> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut arts = vec![];
|
||||
for &i in indices {
|
||||
let art = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
let art: Vec<NodeId> = artboard_art(s, i, art, all, moving)?.into_iter().filter(|id| seen.insert(*id)).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
Ok(arts)
|
||||
let d = &s.doc()?.doc;
|
||||
// A move or a cut leaves a group lying on an artboard locked other than its own, as it leaves
|
||||
// other art there, unless locked and hidden art goes too.
|
||||
let held = |i: usize, id: NodeId| moving && !all && d.node(id).is_some_and(|n| d.locked_artboards_except(i).holds(n));
|
||||
if art {
|
||||
for (id, o) in super::addons::screen_marks_copied(d, all) {
|
||||
if let Some((i, own)) = arts.iter_mut().find(|(i, _)| d.artboards.get(*i).is_some_and(|a| a.id == o))
|
||||
&& !held(*i, id)
|
||||
&& seen.insert(id)
|
||||
{
|
||||
own.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(marks_with_owners(d, arts, held))
|
||||
}
|
||||
|
||||
/// How far a copy of `rect` moves to sit right of the last artboard (Duplicate Artboards, Paste).
|
||||
@@ -399,7 +457,12 @@ pub(crate) fn copy_artboard(d: &mut vectorcraft_doc::Document, i: usize, dv: Vec
|
||||
if let Some(id) = d.artboards.get(index).map(|a| a.id) {
|
||||
d.copy_artboard_guides(src.id, id, dv);
|
||||
}
|
||||
let to = d.artboards.get(index).map(|a| a.id);
|
||||
let copies = super::edit::copy_above(d, art, |_, _, c| {
|
||||
// A copy of the artboard's screen print marks belongs to the copy.
|
||||
if let Some(to) = to {
|
||||
let _ = super::addons::retag_screen_marks(c, src.id, to);
|
||||
}
|
||||
c.transform(Affine::translate(dv), sc);
|
||||
super::object::keep_pixel_aligned(c, sc);
|
||||
})?;
|
||||
|
||||
@@ -35,6 +35,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.color.filter",
|
||||
"addon.color.nearestSwatch",
|
||||
"addon.color.randomFill",
|
||||
"addon.color.screenMarks",
|
||||
"addon.color.select",
|
||||
"addon.color.strokeToFill",
|
||||
"addon.color.swatchLegend",
|
||||
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
"{index | indices: [index…], dx, dy, moveArt?: bool, copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard)} move artboards (and the art fully inside them; locked and hidden art, and art also on another locked artboard, only with lockedAndHidden), several in one step (an error when one is locked); `copy` (Alt-drag) leaves them and moves copies, which start unlocked. With moveArt, screen print marks go with their recorded owner artboard even outside its bounds, subject to lockedAndHidden → {index (the first), indices: the artboards moved or the copies, moved: the art moved or the copies}",
|
||||
has_doc,
|
||||
artboard_move
|
||||
),
|
||||
@@ -685,13 +685,8 @@ fn artboard_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !copy {
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
}
|
||||
// Each artboard's art, an object counted once (artboards can overlap).
|
||||
let mut arts: Vec<(usize, Vec<NodeId>)> = vec![];
|
||||
for &i in &indices {
|
||||
let art = super::panelcmds::artboard_art(s, i, move_art, locked_art, !copy)?;
|
||||
let art = art.into_iter().filter(|id| !arts.iter().any(|(_, a)| a.contains(id))).collect();
|
||||
arts.push((i, art));
|
||||
}
|
||||
// Each artboard takes its art once and its own eligible screen print marks group.
|
||||
let arts = super::panelcmds::artboards_art(s, &indices, move_art, locked_art, !copy)?;
|
||||
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() };
|
||||
let (index, moved) = s.edit(if copy { "Duplicate Artboard" } else { "Move Artboard" }, |d, _| {
|
||||
|
||||
@@ -39,7 +39,7 @@ 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); 40] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 41] = [
|
||||
("edit.copy", "artboard"),
|
||||
("edit.cut", "artboard"),
|
||||
("file.new", "created"),
|
||||
@@ -72,6 +72,7 @@ const REPLAY_ONLY: [(&str, &str); 40] = [
|
||||
("artboard.distributeSpacing", "activeArtboard"),
|
||||
("addon.type.fontSheet", "activeArtboard"),
|
||||
("addon.document.floodFillArtboards", "activeArtboard"),
|
||||
("addon.color.screenMarks", "activeArtboard"),
|
||||
("edit.copy", "selectedArtboards"),
|
||||
("edit.copy", "art"),
|
||||
("edit.cut", "selectedArtboards"),
|
||||
|
||||
@@ -1573,7 +1573,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.fontSheet|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.cleanup.releaseAll|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`)",
|
||||
"{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.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.color.screenMarks|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.cleanup.releaseAll|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",
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
//! filter, into the colours themselves (`addon.color.filter`); below, under Inks, it opens Duotone's
|
||||
//! dialog and Print Ink Fixes' (`addon.color.printFixes`). The submenu applies the add-on's live
|
||||
//! effects, Duotone and Vector Halftone among them (Effect › Color Effects has them too), opens
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and
|
||||
//! Randomize Fill Colors ([`random_fill`]) and opens the panel.
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]), Create
|
||||
//! Screen Print Marks ([`screen_marks`]) and Randomize Fill Colors ([`random_fill`]) and opens the
|
||||
//! panel.
|
||||
|
||||
pub mod legend;
|
||||
pub mod nearest;
|
||||
pub mod random_fill;
|
||||
pub mod screen_marks;
|
||||
|
||||
use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders};
|
||||
use craft::menu::Node;
|
||||
@@ -113,6 +115,7 @@ pub fn menu() -> Vec<Node> {
|
||||
cmd(print_fixes()),
|
||||
c("Find Nearest Swatch…", nearest::COMMAND),
|
||||
c("Create Swatch Legend…", legend::COMMAND),
|
||||
c("Create Screen Print Marks…", screen_marks::COMMAND),
|
||||
Sep,
|
||||
// Each selected object's stroke takes its own fill, or the other way (#5530).
|
||||
cp("Apply Fill to Stroke", "addon.color.fillToStroke", json!({})),
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Create Screen Print Marks in the interface (Object › Plug-ins › Color Effects › Create Screen
|
||||
//! Print Marks…): a dialog for where the registration targets go, their size, stroke weight, inset
|
||||
//! and ink, the spot ink and file lines with their type size and place, and whether every artboard
|
||||
//! gets marks. It previews on the canvas and runs `addon.color.screenMarks` on OK.
|
||||
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::{self, Spec};
|
||||
use crate::canvas::rulers::{general_lengths, stroke_lengths, type_lengths};
|
||||
|
||||
/// The command.
|
||||
pub const COMMAND: &str = "addon.color.screenMarks";
|
||||
/// The target positions: (the command's name, the dialog's label), in the command's order.
|
||||
pub const POSITIONS: [(&str, &str); 8] = [
|
||||
("topLeft", "Top Left"),
|
||||
("top", "Top Center"),
|
||||
("topRight", "Top Right"),
|
||||
("left", "Left Center"),
|
||||
("right", "Right Center"),
|
||||
("bottomLeft", "Bottom Left"),
|
||||
("bottom", "Bottom Center"),
|
||||
("bottomRight", "Bottom Right"),
|
||||
];
|
||||
/// The positions ticked when the dialog opens: the command's default.
|
||||
const TICKED: [&str; 4] = ["top", "bottom", "left", "right"];
|
||||
|
||||
/// How the dialog's values reach the command.
|
||||
pub(crate) static SPEC: Spec = Spec { command: COMMAND, params, found: None, pin_opening_artboard: false };
|
||||
|
||||
/// The positions ticked in `fields`, in the command's order.
|
||||
fn ticked(fields: &DialogFields) -> Vec<&'static str> {
|
||||
POSITIONS.iter().filter(|(key, _)| fields.bool(key).unwrap_or(false)).map(|(key, _)| *key).collect()
|
||||
}
|
||||
|
||||
/// Whether `fields` ask for anything to be drawn: a target, the file line, or the spot ink line of a document
|
||||
/// that has spot inks (`spots`).
|
||||
fn draws(fields: &DialogFields, spots: bool) -> bool {
|
||||
!ticked(fields).is_empty() || (spots && fields.bool("inks").unwrap_or(false)) || fields.bool("info").unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The command's params from the dialog's fields.
|
||||
pub(crate) fn params(fields: &DialogFields) -> Value {
|
||||
json!({
|
||||
"positions": ticked(fields),
|
||||
"size": fields.number("size").unwrap_or(36.0),
|
||||
"weight": fields.number("weight").unwrap_or(1.0),
|
||||
"inset": fields.number("inset").unwrap_or(18.0),
|
||||
"ink": fields.text("ink").unwrap_or(REGISTRATION),
|
||||
"inks": fields.bool("inks").unwrap_or(false),
|
||||
"info": fields.bool("info").unwrap_or(false),
|
||||
"textSize": fields.number("textSize").unwrap_or(9.0),
|
||||
"textPlace": fields.text("textPlace").unwrap_or("bottom"),
|
||||
"textAlign": fields.text("textAlign").unwrap_or("left"),
|
||||
"allArtboards": fields.bool("allArtboards").unwrap_or(false),
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens Create Screen Print Marks' dialog on the command's defaults. The ink list is [Registration] and the
|
||||
/// document's spot swatches, read once, when it opens.
|
||||
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let mut inks = vec![REGISTRATION.to_string()];
|
||||
if let Some(st) = app.session.active() {
|
||||
inks.extend(
|
||||
st.doc
|
||||
.swatches_iter()
|
||||
.filter(|w| w.spot && w.name != REGISTRATION && w.tint_of().is_none() && w.paint.color().is_some())
|
||||
.map(|w| w.name.clone()),
|
||||
);
|
||||
}
|
||||
let mut fields = DialogFields::from_pairs([
|
||||
("size", FieldValue::Number(36.0)),
|
||||
("weight", FieldValue::Number(1.0)),
|
||||
("inset", FieldValue::Number(18.0)),
|
||||
("ink", FieldValue::Text(REGISTRATION.into())),
|
||||
("inks", FieldValue::Bool(false)),
|
||||
("info", FieldValue::Bool(false)),
|
||||
("textSize", FieldValue::Number(9.0)),
|
||||
("textPlace", FieldValue::Text("bottom".into())),
|
||||
("textAlign", FieldValue::Text("left".into())),
|
||||
("allArtboards", FieldValue::Bool(false)),
|
||||
]);
|
||||
for (key, _) in POSITIONS {
|
||||
fields.set(key, FieldValue::Bool(TICKED.contains(&key)));
|
||||
}
|
||||
let (lengths, strokes, types) = (general_lengths(app), stroke_lengths(app), type_lengths(app));
|
||||
dialogs::open(app, &SPEC, fields, move |fields| {
|
||||
let ink_choices = inks.iter().map(|name| (name.clone(), name.clone().into())).collect();
|
||||
let places = vec![("bottom".to_string(), tl!("Bottom").into()), ("top".to_string(), tl!("Top").into())];
|
||||
let aligns = vec![("left".to_string(), tl!("Left").into()), ("right".to_string(), tl!("Right").into())];
|
||||
let mut rows = vec![Param::section(tl!("Targets:"))];
|
||||
rows.extend(POSITIONS.iter().map(|&(key, label)| Param::new(key, tl!(label), ParamKind::bool(TICKED.contains(&key)))));
|
||||
rows.extend([
|
||||
Param::number("size", tl!("Size:"), 36.0, 1.0, 2).length(lengths).bounds(Some(4.0), Some(1000.0)),
|
||||
Param::number("weight", tl!("Weight:"), 1.0, 0.1, 2).length(strokes).bounds(Some(0.1), Some(20.0)),
|
||||
Param::number("inset", tl!("Inset:"), 18.0, 1.0, 2).length(lengths).bounds(Some(-1000.0), Some(1000.0)),
|
||||
Param::new("ink", tl!("Ink:"), ParamKind::choice(ink_choices, Some(REGISTRATION.into()))),
|
||||
Param::section(tl!("Text:")),
|
||||
Param::new("inks", tl!("Spot Ink Names"), ParamKind::bool(false)),
|
||||
Param::new("info", tl!("File Name and Date"), ParamKind::bool(false)),
|
||||
Param::number("textSize", tl!("Type Size:"), 9.0, 1.0, 1).length(types).bounds(Some(4.0), Some(72.0)),
|
||||
Param::new("textPlace", tl!("Place:"), ParamKind::choice(places, Some("bottom".into()))),
|
||||
Param::new("textAlign", tl!("Align:"), ParamKind::choice(aligns, Some("left".into()))),
|
||||
Param::new("allArtboards", tl!("All Artboards"), ParamKind::bool(false)),
|
||||
]);
|
||||
let ok = draws(fields, inks.len() > 1);
|
||||
ParamDialog::new(COMMAND, tl!("Create Screen Print Marks"), rows)
|
||||
.ok_enabled(ok)
|
||||
.ok_reason(tl!("Tick a target or a line of text.").into())
|
||||
.values(Bind::bound(fields))
|
||||
.previews(true)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,145 @@
|
||||
use craft::behavior::Mixed;
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::addons::dialogs::tests as host;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
/// The marks group of the active document's marks layer: its targets' rings' widths and its type lines.
|
||||
fn marks(app: &VectorcraftApp) -> Option<(Vec<f64>, Vec<String>)> {
|
||||
let doc = &app.session.active()?.doc;
|
||||
let layer = doc.layers.iter().find(|l| l.name.as_deref() == Some("Screen Print Marks"))?;
|
||||
let group: &Node = layer.children()?.first()?;
|
||||
let kids = group.children()?;
|
||||
let rings = kids
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref() == Some("Registration Target"))
|
||||
.map(|t| t.children().unwrap()[0].geometric_bounds().unwrap().width())
|
||||
.collect();
|
||||
let lines = kids
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.plain_text()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Some((rings, lines))
|
||||
}
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
|
||||
app.run("swatch.new", json!({"name": "Plate Red", "color": "#cc1122", "spot": true})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// Keyboard and checkbox edits reach the preview; Cancel restores the drawing, while OK with Preview off applies the
|
||||
/// same values in one undo step.
|
||||
#[test]
|
||||
fn keyboard_and_checkbox_edits_reach_the_preview_ok_and_cancel() {
|
||||
for commit in [false, true] {
|
||||
let app = app();
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
|
||||
panel.room(egui::vec2(800.0, 1000.0));
|
||||
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
|
||||
panel.frame();
|
||||
assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on");
|
||||
assert!(panel.app().session.in_interaction(), "the opening marks are previewed");
|
||||
assert_eq!(marks(&panel.app()).map(|(rings, _)| rings.len()), Some(4), "four targets on opening");
|
||||
if commit {
|
||||
panel.click_role("Preview", Role::CHECK_BOX);
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
}
|
||||
panel.click_role("Left Center", Role::CHECK_BOX);
|
||||
panel.click_role("Right Center", Role::CHECK_BOX);
|
||||
panel.click_role("Spot Ink Names", Role::CHECK_BOX);
|
||||
panel.click_role("Size", Role::SPIN_BUTTON);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text("40 pt");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
panel.frame();
|
||||
let edited = |app: &VectorcraftApp| {
|
||||
let (rings, lines) = marks(app).expect("the marks layer");
|
||||
assert_eq!(rings.len(), 2, "the unticked sides draw no target");
|
||||
assert!(rings.iter().all(|w| (w - 20.0).abs() < 1e-6), "the typed size reaches the targets: {rings:?}");
|
||||
assert_eq!(lines, ["Plate Red"], "the spot ink line");
|
||||
};
|
||||
if commit {
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone");
|
||||
panel.click("OK");
|
||||
panel.frame();
|
||||
edited(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
panel.app().run("edit.undo", json!({})).unwrap();
|
||||
} else {
|
||||
edited(&panel.app());
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step");
|
||||
panel.click("Cancel");
|
||||
panel.frame();
|
||||
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
assert!(!panel.app().session.in_interaction());
|
||||
assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing");
|
||||
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// With no target ticked and no line, OK is off; a spot ink picked in the dialog strokes the targets.
|
||||
#[test]
|
||||
fn ok_needs_something_to_draw_and_the_ink_list_offers_the_spot_swatches() {
|
||||
let mut app = crate::testing::windowed(app());
|
||||
host::open_item(&mut app, "Color Effects", "Create Screen Print Marks…");
|
||||
let id = host::dialog_id(&app);
|
||||
for key in ["top", "bottom", "left", "right"] {
|
||||
host::set(&app, id, key, json!(false));
|
||||
}
|
||||
host::frame(&mut app);
|
||||
assert!(!host::confirm(&app, id), "nothing to draw: OK is off");
|
||||
host::set(&app, id, "topLeft", json!(true));
|
||||
host::set(&app, id, "ink", json!("Plate Red"));
|
||||
host::frame(&mut app);
|
||||
assert!(host::confirm(&app, id));
|
||||
host::frame(&mut app);
|
||||
assert!(!app.any_dialog_open());
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let layer = &doc.layers[0];
|
||||
assert!(layer.locked, "the marks layer is locked at the bottom");
|
||||
let target = &layer.children().unwrap()[0].children().unwrap()[0];
|
||||
let ring = &target.children().unwrap()[0];
|
||||
let linked = match ring.appearance.stroke_paint() {
|
||||
vectorcraft_color::Paint::Solid { swatch, .. } => swatch,
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(linked.as_deref(), Some("Plate Red"));
|
||||
}
|
||||
|
||||
/// The ticked positions go in the command's order; every other value goes as the dialog holds it.
|
||||
#[test]
|
||||
fn params_lists_the_ticked_positions_in_order() {
|
||||
let fields = DialogFields::from_pairs([
|
||||
("bottomRight", FieldValue::Bool(true)),
|
||||
("topLeft", FieldValue::Bool(true)),
|
||||
("top", FieldValue::Bool(false)),
|
||||
("textPlace", FieldValue::Text("top".into())),
|
||||
("info", FieldValue::Bool(true)),
|
||||
]);
|
||||
let p = super::params(&fields);
|
||||
assert_eq!(p["positions"], json!(["topLeft", "bottomRight"]));
|
||||
assert_eq!(p["textPlace"], json!("top"));
|
||||
assert_eq!(p["info"], json!(true));
|
||||
assert_eq!(p["ink"], json!("[Registration]"));
|
||||
assert!(p.get("time").is_none(), "the date is the time of the run");
|
||||
}
|
||||
|
||||
/// Spot Ink Names alone draws something only in a document with spot inks.
|
||||
#[test]
|
||||
fn the_spot_ink_line_alone_needs_spot_inks() {
|
||||
let fields = DialogFields::from_pairs([("inks", FieldValue::Bool(true))]);
|
||||
assert!(!super::draws(&fields, false));
|
||||
assert!(super::draws(&fields, true));
|
||||
}
|
||||
@@ -185,6 +185,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
|
||||
typetools::numbers::COMMAND => typetools::numbers::open,
|
||||
color::legend::COMMAND => color::legend::open,
|
||||
color::nearest::COMMAND => color::nearest::open,
|
||||
color::screen_marks::COMMAND => color::screen_marks::open,
|
||||
color::random_fill::COMMAND => color::random_fill::open,
|
||||
select::COMMAND => select::open,
|
||||
select::points_only::COMMAND => select::points_only::open,
|
||||
|
||||
@@ -1574,7 +1574,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.fontSheet|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.cleanup.releaseAll|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`)",
|
||||
"{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.fontSheet|addon.type.numbers|addon.color.swatchLegend|addon.color.screenMarks|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.cleanup.releaseAll|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",
|
||||
|
||||
+56
-1
@@ -12261,6 +12261,8 @@ pastes objects back into the layers and sublayers they came from: in the same do
|
||||
else by the names of the layer and the layers around it (the topmost chain that matches the most names, a shown and
|
||||
unlocked one first). A missing sublayer is made inside its layer, and a missing top-level layer on top, in the paste's
|
||||
undo step. When a matched layer, or a layer around it, is hidden or locked, the paste fails and nothing is pasted.
|
||||
Screen print marks copied with their artboard (`addon.color.screenMarks`) go back into the Screen Print Marks layer
|
||||
even while it is hidden or locked.
|
||||
Drawing modes (`view.drawMode`) apply
|
||||
too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put the objects inside the
|
||||
object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind,
|
||||
@@ -12340,7 +12342,9 @@ artboard size fields while the tool is in use.
|
||||
`artboard.setProps {artboards: [{index, name?, color?, guideLabel?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several
|
||||
artboards in one undo step, each with its own fields; the other params apply to all of them. The art that moves or
|
||||
scales with each artboard is the art inside it before any of them changes, and an object inside several of them goes
|
||||
with the first one listed that moves or scales its art. An empty list and a list that names an artboard twice are
|
||||
with the first one listed that moves or scales its art. An artboard whose new `x` or `y` at the same size moves its art (`moveArt`) takes its own
|
||||
screen print marks group wherever it lies, and leaves another artboard's group lying on it to that artboard
|
||||
([Create Screen Print Marks](#create-screen-print-marks)). An empty list and a list that names an artboard twice are
|
||||
refused.
|
||||
|
||||
With several artboards selected with the Artboard tool, the desktop app gives a new size to each of them in one such
|
||||
@@ -19186,6 +19190,57 @@ images and patterns keep their colours. → `{changed, swatches: [the document s
|
||||
{"name":"run_command","arguments":{"command":"addon.color.applyNearestSwatch","params":{"library":"document","stroke":false}}}
|
||||
```
|
||||
|
||||
### Create Screen Print Marks
|
||||
|
||||
`addon.color.screenMarks {positions?, size?, weight?, inset?, ink?, inks?, info?, time?, textSize?, textPlace?,
|
||||
textAlign?, artboard?, allArtboards?}` (Object › Plug-ins › Color Effects › Create Screen Print Marks…) draws marks for
|
||||
screen printing inside an artboard as document art, so they print, separate and export with the rest of the art:
|
||||
|
||||
- Registration targets, each a circle half the target's width with a cross the target's width through it, stroked and
|
||||
unfilled. `positions` lists where they go: any of `topLeft`, `top`, `topRight`, `left`, `right`, `bottomLeft`,
|
||||
`bottom`, `bottomRight`, each at most once (default: `top`, `bottom`, `left` and `right`; `[]` draws none). `size`
|
||||
is the target's width in pt, 4…1000 (36); `weight` is the stroke weight, 0.1…20 (1); `inset` is the distance from
|
||||
the artboard's edge to the target's outer edge, −1000…1000 (18), and a negative inset puts the targets outside the
|
||||
artboard.
|
||||
- `ink` is the targets' stroke: `"[Registration]"` (the default), which prints on every plate, or the name of a spot
|
||||
swatch, linked to it.
|
||||
- `inks: true` adds a line that names the document's spot inks in panel order, each name filled with its own ink. Tint
|
||||
swatches, process colors and [Registration] are left out, and with no spot ink the line is left out. A line names
|
||||
at most 256 inks.
|
||||
- `info: true` adds a line with the file name (the title of a document never saved) and the date and time in UTC
|
||||
(`2026-03-04 05:06 UTC`), filled with `ink`. `time` is Unix seconds (default: now); `null`, or no clock (the web),
|
||||
leaves the date out.
|
||||
- `textSize` is the lines' type size, 4…72 pt (9). `textPlace` is `"top"` or `"bottom"` (the default) and
|
||||
`textAlign` is `"left"` (the default) or `"right"`: the lines sit `inset` in from that edge and side, the spot ink
|
||||
line above the file line, and start past a target ticked in that corner. When a line would cross the `top` or
|
||||
`bottom` target on its side, the lines move in past that target. They stay where they are when moving would cross
|
||||
another target or leave the artboard.
|
||||
|
||||
The marks of each artboard are one group, on the top-level marks layer the command made, which it finds by a tag in
|
||||
the layer's data and not by its name. The command makes that layer, named "Screen Print Marks", at the bottom of the
|
||||
stack, locked, when the document has none. Another layer with that name is not used, and the marks layer keeps its
|
||||
role when renamed. A marks layer moved, unlocked or hidden stays as it is.
|
||||
`artboard` is an artboard's index (default: the active artboard; the journal records it as `activeArtboard` for a replay, and recorded actions leave it
|
||||
out) and `allArtboards: true` marks every artboard;
|
||||
giving both is an error. Running the command again replaces that artboard's group and leaves the other artboards'
|
||||
groups alone. A group copied with an artboard duplicated, Alt-dragged or pasted in the same document belongs to the copy.
|
||||
Another artboard's group lying on an artboard that is duplicated, Alt-dragged, copied or cut goes with its own artboard:
|
||||
it is copied with that artboard when that one is copied too, and otherwise stays where it is. Deleting an artboard makes its group ordinary art on the marks layer, so a new artboard never takes it over;
|
||||
it is copied like other art. With art enabled, moves (`artboard.move`, and `artboard.setProps` with `moveArt` and a
|
||||
new `x` or `y` at the same size) and cuts also take marks by their recorded owner (marks lying on another locked artboard stay, as other art does), even when
|
||||
the marks lie outside every artboard, subject to `lockedAndHidden`. When the marks layer was
|
||||
deleted, or the document pasted into has none, pasting an artboard with its marks makes a new marks layer named "Screen Print Marks" at the top level, and the command uses that layer. Marks
|
||||
outside the artboard (a negative `inset`) appear in an export or a print clipped to the artboard only as far as its
|
||||
bleed reaches. It is one undo step, and none when the marks come out the same (`changed: false`). The selection is
|
||||
kept. An unknown position or one named twice, a number out of range, an `ink` that is not [Registration] or a spot
|
||||
swatch, a value of the wrong type (`null` included, except for `time`), nothing to draw (no position, no file line, and no spot ink line or no spot ink to
|
||||
name), and marks that would reach more than 4,000,000 pt from the origin are errors that leave the document unchanged. The dialog previews on the canvas, and its OK is off while nothing is ticked.
|
||||
→ `{changed, layer, ids: [group id…], inks: [spot ink name…]}`
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"addon.color.screenMarks","params":{"positions":["topLeft","topRight","bottomLeft","bottomRight"],"inks":true,"info":true}}}
|
||||
```
|
||||
|
||||
## Arrange Tools add-on
|
||||
|
||||
Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are
|
||||
|
||||
@@ -3354,6 +3354,12 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov
|
||||
|
||||
A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Plug-ins › Color Effects › Create Swatch Legend… (`addon.color.swatchLegend`) opens a dialog (columns, chip size, gap, values, selected swatches only, with a preview) and draws a chip per colour swatch (the selected ones, else all) filled with and linked to its swatch, labelled with its name and values (HEX, RGB, CMYK, Lab or Grayscale; by default its own model; spot swatches marked), black on light chips and white on dark ones, in a grid of chosen columns, chip size and spacing, as one selected group in one undo step (#4919). Tests: `cmd::addons::color::legend::tests` (engine), `addons::color::legend::tests::create_swatch_legend_opens_its_dialog_previews_and_runs_on_ok` (ui-egui).
|
||||
|
||||
## Create Screen Print Marks (2026-11-29)
|
||||
|
||||
A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) opens a dialog (the eight target positions, size, stroke weight, inset, ink, the spot ink and file lines with their type size, place and alignment, all artboards, with a preview) and draws registration targets (a circle half the target's width with a cross through it) inside the artboard in [Registration] or a spot ink, with an optional line naming the document's spot inks, each in its own ink, and an optional line with the file name and the date and time in UTC. The marks are document art: one group per artboard on a locked "Screen Print Marks" layer made at the bottom of the stack, so they print, separate and export with the rest of the art, where Create Trim Marks draws trim marks only and the PDF export's printer's marks exist only in the exported file. The lines move in past a top or bottom target they would cross. They stay where they are when moving would cross another target or leave the artboard. Marks copied with a duplicated artboard belong to the copy, and another artboard's marks lying on a copied artboard stay with their own artboard. Moving an artboard with its art, by Move Artboard or a new position, takes its own marks, and deleting it makes its marks ordinary art. A paste that makes the deleted marks layer again makes it the marks layer. Running it again replaces that artboard's marks; one undo step, none when the marks come out the same. Remaining: saved presets of the dialog's settings. Tests: `cmd::addons::color::screen_marks::tests` (engine), `addons::color::screen_marks::tests` (ui-egui).
|
||||
|
||||
With art enabled, artboard moves and cuts take eligible screen print marks by their recorded owner, including marks outside every artboard. Tests: `overlapping_artboard_copies_keep_one_marks_group_per_owner`, `off_board_marks_follow_artboard_copies_and_cuts_by_owner`, `moving_an_artboard_uses_marks_ownership_instead_of_containment` in `cmd::addons::color::screen_marks::tests`.
|
||||
|
||||
## Stroke Weight Up and Down shortcuts (2026-11-06)
|
||||
|
||||
Cmd/Ctrl+Alt+. (`stroke.weightUp`) and Cmd/Ctrl+Alt+, (`stroke.weightDown`) raise and lower the weight of each selected stroke from its own weight, with the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) names: a quarter unit of Units › Stroke at a time up to one unit, whole units above it, no lower than a quarter unit and no higher than 1000 pt. Type steps its stroked characters; objects without a stroke are left alone; with nothing selected the weight of the next object drawn steps. Each press is one undo step (#5797). Evidence: `tests::strokeux::stroke_weight_up_and_down_step_each_selected_stroke`, `stroke_weight_up_with_nothing_selected_sets_up_new_art`, `cmd::stroke::tests::weight_steps_follow_units_and_stop_at_their_bounds`. Scores unchanged.
|
||||
|
||||
Reference in new issue
Block a user