diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 9fa5806c52..8fcbd68e8a 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -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}; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8dff9593e9..99b7b355f5 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -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 { ] .into_iter() .chain(legend::specs()) + .chain(screen_marks::specs()) .collect() } diff --git a/crates/engine/src/cmd/addons/color/screen_marks.rs b/crates/engine/src/cmd/addons/color/screen_marks.rs new file mode 100644 index 0000000000..f5f58b2571 --- /dev/null +++ b/crates/engine/src/cmd/addons/color/screen_marks.rs @@ -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 { + 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) -> Result { + 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> { + 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::>()? + } + 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 { + 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 { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).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>, + 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 = 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> = 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> { + 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 { + 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 { + 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 { + 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) { + // Groups moved off the marks layer keep their tag and count too. + let mut groups: Vec = 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 { + 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![]; + 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 = 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 = 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>> = 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 = 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> = 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 = 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; diff --git a/crates/engine/src/cmd/addons/color/screen_marks/tests.rs b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs new file mode 100644 index 0000000000..bb98d0786d --- /dev/null +++ b/crates/engine/src/cmd/addons/color/screen_marks/tests.rs @@ -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> { + 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 { + 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 { + 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::(); + 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::>(); + 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())); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e1f26a9256..dc0bf5c730 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -189,7 +189,7 @@ pub fn specs() -> Vec { "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 = 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 = 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 = 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 = 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, String), NodeId> = HashMap::new(); // Objects pasted into each parent so far (keeps their order in front and back pastes). let mut placed: BTreeMap, 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, names: Vec }, } -/// [`remembered_layer`] for each object's source layer, worked out once for each layer. -fn remembered_layers(d: &Document, sources: &[Option], same_doc: bool) -> Result>> { - 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], marks: &[bool], same_doc: bool) -> Result>> { + 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], 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 { +/// 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 { + // 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