mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Color Effects: Create Screen Print Marks draws registration targets and ink lines
Object › Plug-ins › Color Effects › Create Screen Print Marks… (`addon.color.screenMarks`) 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 (a circle half the target's width with a cross through it) go at any of the four corners and four side centers, with a set size, stroke weight and inset, stroked in [Registration] or a spot swatch. - An optional line names the document's spot inks, each name filled with its own ink (tints and [Registration] left out), and an optional line gives the file name and the date and time in UTC, at the top or bottom, left or right, starting past a corner target. - The marks of each artboard are one group on a "Screen Print Marks" layer, made locked at the bottom of the stack. Running it again replaces that artboard's group and keeps the other artboards' groups and the selection. One undo step, none when the marks come out the same. - Unknown or repeated positions, values out of range or of the wrong type, an ink that is not [Registration] or a spot swatch, nothing to draw, and marks past the canvas edge are errors that leave the document unchanged. - The dialog previews on the canvas; its OK is off while nothing would be drawn. Plug-ins may call the command. - Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
aea9cd7a32
commit
dbbd39963c
10 files changed
+994
-5
No files matched your search
@@ -4,13 +4,15 @@
|
||||
//! 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. 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, and Apply
|
||||
//! Fill to Stroke and Apply Stroke to Fill ([`copy_paint`]) copy each object's own paint across. Its
|
||||
//! panel and its submenu, Object › Plug-ins › Color Effects, are the UI's.
|
||||
|
||||
pub mod legend;
|
||||
mod nearest;
|
||||
mod print_fixes;
|
||||
pub mod screen_marks;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -95,6 +97,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
.into_iter()
|
||||
.chain(legend::specs())
|
||||
.chain(screen_marks::specs())
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
//! 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), artboard?: index (default: the active artboard), allArtboards?: false} 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. 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 | Some(Value::Null) => 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 | Some(Value::Null) => 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`.
|
||||
fn line(&self, runs: &[(String, Paint)], at: Point, from_bottom: bool) -> (TextObject, f64) {
|
||||
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, b.height())
|
||||
}
|
||||
|
||||
/// 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 gap = self.style.size * 0.25;
|
||||
let mut placed = Vec::with_capacity(self.lines.len());
|
||||
if self.top {
|
||||
let mut y = r.y0 + self.inset;
|
||||
for runs in &self.lines {
|
||||
let (t, h) = self.line(runs, Point::new(x, y), false);
|
||||
y += h + gap;
|
||||
placed.push(t);
|
||||
}
|
||||
} else {
|
||||
let mut y = r.y1 - self.inset;
|
||||
for runs in self.lines.iter().rev() {
|
||||
let (t, h) = self.line(runs, Point::new(x, y), true);
|
||||
y -= h + gap;
|
||||
placed.insert(0, t);
|
||||
}
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
/// `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();
|
||||
let artboard = index_opt(p, "artboard", C)?;
|
||||
if all && artboard.is_some() {
|
||||
return Err(bad(C, "give `artboard` or `allArtboards`, not both"));
|
||||
}
|
||||
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 = match artboard {
|
||||
Some(i) => i,
|
||||
None => active_artboard(st).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();
|
||||
let reach = marks.weight;
|
||||
let beyond = |b: Rect| [b.x0 - reach, b.y0 - reach, b.x1 + reach, b.y1 + reach].iter().any(|v| !v.is_finite() || v.abs() > MAX_COORD);
|
||||
if drawn.iter().any(|g| g.geometric_bounds().is_some_and(beyond)) {
|
||||
return Err(bad(C, format!("the marks would reach past the edge of the canvas (±{MAX_COORD} pt)")));
|
||||
}
|
||||
if let Some((layer, kids)) = &layer {
|
||||
let old = |board: u32| kids.iter().filter(|k| tag(k) == Some(board.to_string().as_str())).collect::<Vec<_>>();
|
||||
let same = boards.iter().zip(&drawn).all(|((_, board), new)| matches!(old(*board).as_slice(), [one] if without_ids(one) == *new));
|
||||
if same {
|
||||
let ids: Vec<u64> = boards.iter().filter_map(|(_, board)| old(*board).first().map(|g| g.id.0)).collect();
|
||||
return Ok(json!({ "changed": false, "layer": layer.0, "ids": ids, "inks": names }));
|
||||
}
|
||||
}
|
||||
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 board_tag = board.to_string();
|
||||
let kids = d.children(Some(layer)).cloned().unwrap_or_default();
|
||||
let old: Vec<NodeId> = kids.iter().filter(|k| tag(k) == Some(board_tag.as_str())).map(|k| k.id).collect();
|
||||
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,297 @@
|
||||
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 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 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 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": [], "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());
|
||||
}
|
||||
@@ -28,6 +28,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"addon.color.fillToStroke",
|
||||
"addon.color.filter",
|
||||
"addon.color.nearestSwatch",
|
||||
"addon.color.screenMarks",
|
||||
"addon.color.select",
|
||||
"addon.color.strokeToFill",
|
||||
"addon.color.swatchLegend",
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
//! 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`]) and Create Swatch Legend ([`legend`]) and
|
||||
//! opens the panel.
|
||||
//! Print Ink Fixes, Find Nearest Swatch ([`nearest`]), Create Swatch Legend ([`legend`]) and Create
|
||||
//! Screen Print Marks ([`screen_marks`]) and opens the panel.
|
||||
|
||||
pub mod legend;
|
||||
pub mod nearest;
|
||||
pub mod screen_marks;
|
||||
|
||||
use craft::imaging::ui::adjust::{AdjustContext, AdjustField, AdjustSliders};
|
||||
use craft::menu::Node;
|
||||
@@ -112,6 +113,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 };
|
||||
|
||||
/// 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));
|
||||
}
|
||||
@@ -107,6 +107,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
|
||||
typetools::COMMAND => typetools::open,
|
||||
color::legend::COMMAND => color::legend::open,
|
||||
color::nearest::COMMAND => color::nearest::open,
|
||||
color::screen_marks::COMMAND => color::screen_marks::open,
|
||||
select::COMMAND => select::open,
|
||||
_ => return super::arrange::open(app, id),
|
||||
};
|
||||
|
||||
+38
@@ -17526,6 +17526,44 @@ 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.
|
||||
|
||||
The marks of each artboard are one group, on the top-level layer "Screen Print Marks". When the document has no such
|
||||
layer, the command makes it at the bottom of the stack, locked. A layer moved, unlocked or hidden stays as it is.
|
||||
`artboard` is an artboard's index (default: the active artboard) 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. 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, 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
|
||||
|
||||
@@ -3270,6 +3270,10 @@ 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. 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).
|
||||
|
||||
## 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