Merge main into feat/recolor-edit-base-color-menus

This commit is contained in:
dotCooCoo
2026-11-15 10:53:54 -08:00
166 changed files with 8416 additions and 447 deletions
+3
View File
@@ -8,6 +8,7 @@ mod contour;
mod cutting;
mod document;
mod image;
mod packaging;
mod pathtools;
mod pen;
mod select;
@@ -15,6 +16,7 @@ mod shapes;
mod typetools;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
use super::CommandSpec;
@@ -27,6 +29,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(cutting::specs());
v.extend(document::specs());
v.extend(image::specs());
v.extend(packaging::specs());
v.extend(pathtools::specs());
v.extend(pen::specs());
v.extend(select::specs());
+18
View File
@@ -0,0 +1,18 @@
//! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
mod roles;
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
roles::specs()
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,454 @@
//! Fold line roles (`addon.packaging.setRole`, `addon.packaging.roles`,
//! `addon.packaging.setRoleSwatch`). A path, compound path or live shape has a role when its top
//! stroke is painted with the swatch the document's role table gives that role, at any tint. The
//! table lives in [`Document::unknown`] under [`ROLES_KEY`], `{cut, crease, partialCut,
//! perforation}` each naming a swatch; a role it leaves out, or names with something other than a
//! string, takes its default swatch, named after the role.
use serde_json::{Map, Value, json};
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::super::super::overprint::edit_counted;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{Result, Session};
/// Document unknown key: the role table, `{role id: swatch name}`.
pub(crate) const ROLES_KEY: &str = "packagingRoles";
const SET_ROLE: &str = "addon.packaging.setRole";
const ROLES: &str = "addon.packaging.roles";
const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// What a fold line does when the blank is cut and folded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Role {
/// Separates the material.
Cut,
/// A fold.
Crease,
/// A fold cut part way through the board.
PartialCut,
/// A fold along a line of cuts.
Perforation,
}
impl Role {
pub(crate) const ALL: [Role; 4] = [Role::Cut, Role::Crease, Role::PartialCut, Role::Perforation];
/// The role's id in params and in the role table.
pub(crate) fn id(self) -> &'static str {
match self {
Role::Cut => "cut",
Role::Crease => "crease",
Role::PartialCut => "partialCut",
Role::Perforation => "perforation",
}
}
/// The role's name, which is also its default swatch's name.
pub(crate) fn name(self) -> &'static str {
match self {
Role::Cut => "Cut",
Role::Crease => "Crease",
Role::PartialCut => "Partial Cut",
Role::Perforation => "Perforation",
}
}
pub(crate) fn from_id(id: &str) -> Option<Role> {
Role::ALL.into_iter().find(|r| r.id() == id)
}
/// The color a missing role swatch is made with (VectorCraft's own values): Cut 100% magenta,
/// Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan.
fn color(self) -> Color {
match self {
Role::Cut => Color::cmyk(0.0, 1.0, 0.0, 0.0),
Role::Crease => Color::cmyk(1.0, 0.0, 0.0, 0.0),
Role::PartialCut => Color::cmyk(0.0, 0.0, 1.0, 0.0),
Role::Perforation => Color::cmyk(0.5, 0.5, 0.0, 0.0),
}
}
fn index(self) -> usize {
Role::ALL.iter().position(|r| *r == self).unwrap_or(0)
}
}
/// The swatch each role is carried by, in [`Role::ALL`] order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct RoleTable([String; 4]);
impl RoleTable {
/// The document's role table, with each missing or damaged entry at its default. When a damaged
/// table names one swatch for two roles, the later role takes its default name instead, or
/// "Crease 2" and so on when an earlier role has that.
pub(crate) fn of(d: &Document) -> RoleTable {
let stored = d.unknown.get(ROLES_KEY).and_then(Value::as_object);
let mut names: Vec<String> = Vec::with_capacity(Role::ALL.len());
for r in Role::ALL {
let name = match stored.and_then(|m| m.get(r.id())).and_then(Value::as_str) {
Some(name) if !name.is_empty() && !names.iter().any(|n| n == name) => name.to_string(),
_ => {
let base = r.name();
std::iter::once(base.to_string())
.chain((2..).map(|i| format!("{base} {i}")))
.find(|n| !names.contains(n))
.unwrap_or_else(|| base.to_string())
}
};
names.push(name);
}
RoleTable(Role::ALL.map(|r| names.get(r.index()).cloned().unwrap_or_else(|| r.name().to_string())))
}
/// The swatch of `role`.
pub(crate) fn swatch(&self, role: Role) -> &str {
self.0.get(role.index()).map_or("", String::as_str)
}
/// The role swatch `name` carries.
pub(crate) fn role_of_swatch(&self, name: &str) -> Option<Role> {
Role::ALL.into_iter().find(|r| self.swatch(*r) == name)
}
/// The role of object `n`: the role of the swatch its top stroke is painted with.
pub(crate) fn role_of(&self, n: &Node) -> Option<Role> {
if !can_carry(n) {
return None;
}
match &n.appearance.stroke()?.paint {
Paint::Solid { swatch: Some(name), .. } => self.role_of_swatch(name),
_ => None,
}
}
fn to_value(&self) -> Value {
Value::Object(Role::ALL.into_iter().map(|r| (r.id().to_string(), json!(self.swatch(r)))).collect::<Map<_, _>>())
}
}
/// Swatch `from` of `d` is now named `to`, and `global` says whether it is still a global color.
/// A role it carried keeps it under the new name, as the strokes linked to it do; when it stopped
/// being global, which unlinks those strokes, the role moves to a new name that `setRole` makes a
/// swatch for. Another role that named `to` without such a swatch moves to a new name too, so no
/// two roles share a swatch.
pub(crate) fn role_swatch_edited(d: &mut Document, from: &str, to: &str, global: bool) {
let before = RoleTable::of(d);
let mut table = before.clone();
for r in Role::ALL {
let name = table.swatch(r).to_string();
let moved = if name == from && global {
Some(to.to_string())
} else if name == from || (name == to && from != to) {
Some(free_role_name(d, &table, r))
} else {
None
};
if let (Some(new), Some(slot)) = (moved, table.0.get_mut(r.index())) {
*slot = new;
}
}
if table != before {
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
}
}
/// Swatches `merged` of `d` were merged into swatch `kept`, and `linked` says whether their strokes
/// now link to it (it is a global color). When `kept` carries no role, it takes the role of the
/// first merged swatch that carried one, so the lines of that role keep it; a merged swatch's other
/// role keeps its name, which the next `setRole` makes a swatch for.
pub(crate) fn role_swatches_merged(d: &mut Document, merged: &[String], kept: &str, linked: bool) {
let mut table = RoleTable::of(d);
if !linked || table.role_of_swatch(kept).is_some() {
return;
}
let Some(role) = merged.iter().find_map(|m| table.role_of_swatch(m)) else { return };
if let Some(slot) = table.0.get_mut(role.index()) {
*slot = kept.to_string();
}
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
}
/// A name for `role`'s swatch that no swatch, color group or other role of `table` uses: the
/// role's name, else "Cut 2", "Cut 3"… The document holds finitely many names, so the search
/// always ends at a free one.
fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String {
let free = |n: &str| !d.swatch_name_taken(n) && Role::ALL.into_iter().all(|r| r == role || table.swatch(r) != n);
let base = role.name();
if free(base) {
return base.to_string();
}
(2usize..).map(|i| format!("{base} {i}")).find(|n| free(n)).unwrap_or_else(|| base.to_string())
}
/// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a
/// guide, or a compound path.
fn can_carry(n: &Node) -> bool {
match &n.kind {
NodeKind::Path { clipping, guide, .. } => !clipping && !guide,
NodeKind::Compound { .. } => true,
_ => false,
}
}
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
/// groups, each once, and
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
/// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or
/// are on a locked artboard are left out and counted as skipped.
fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec<NodeId>, usize) {
fn walk(n: &Node, out: &mut Vec<NodeId>, skipped: &mut usize) {
match &n.kind {
NodeKind::Group { children, .. } => {
for c in children {
// A group's clipping path draws no stroke: it is skipped.
if matches!(c.kind, NodeKind::Path { clipping: true, .. }) {
*skipped += 1;
} else {
walk(c, out, skipped);
}
}
}
_ if can_carry(n) => out.push(n.id),
_ => *skipped += 1,
}
}
let (mut out, mut skipped) = (vec![], 0);
// A path of a compound path is painted with the compound's appearance: the compound takes the
// role. `roots` come from `checked_ids_or_selection`, which keeps only outermost objects, so a
// group and its member are never both roots.
let mut seen = std::collections::HashSet::new();
let compound_of = |id: NodeId| d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
for n in roots.iter().map(|id| compound_of(*id).unwrap_or(*id)).filter(|id| seen.insert(*id)).filter_map(|id| d.node(id)) {
walk(n, &mut out, &mut skipped);
}
if editable {
// Named directly or not, a locked or hidden object, or one in a locked or hidden group or
// layer or on a locked artboard, stays as it is.
let ok = d.editable();
let before = out.len();
out.retain(|id| ok(*id));
skipped += before - out.len();
}
(out, skipped)
}
/// Every object of the document that can carry a role, through layers and groups.
fn document_targets(d: &Document) -> Vec<NodeId> {
fn walk(n: &Node, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ if can_carry(n) => out.push(n.id),
_ => {}
}
}
let mut out = vec![];
d.layers.iter().for_each(|l| walk(l, &mut out));
out
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.packaging.setRole",
"Make Fold Line",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
has_selection,
set_role
),
cmd!(
query "addon.packaging.roles",
"Fold Lines",
[],
None,
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
has_doc,
roles
),
cmd!(
"addon.packaging.setRoleSwatch",
"Role Swatches…",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{role: cut|crease|partialCut|perforation, swatch: a global or spot color swatch's name} make the swatch carry the role, in the document's role table, as one undo step (none when it already does). Objects stroked with the role's old swatch keep their color and no longer have the role. Refused: a missing swatch, a gradient or pattern swatch, a process color that is not global, a tint swatch, [None], [Registration], and a swatch another role has → {role, swatch, changed}",
has_doc,
set_role_swatch
),
]
}
/// The role `p` gives: `Some(None)` for `none` when `none` is allowed.
fn role_param(p: &Value, cmd: &str, none: bool) -> Result<Option<Role>> {
let id = text_param(p, "role", cmd)?.ok_or_else(|| bad(cmd, "missing `role`"))?;
match Role::from_id(id) {
Some(r) => Ok(Some(r)),
None if none && id == "none" => Ok(None),
None if none => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut, perforation or none"))),
None => Err(bad(cmd, format!("unknown role `{id}`: cut, crease, partialCut or perforation"))),
}
}
/// Why swatch `name` of `d` can't carry a role, if it can't.
fn unfit_swatch(d: &Document, name: &str) -> Option<String> {
if name == REGISTRATION || name == "[None]" {
return Some(format!("`{name}` can't carry a role"));
}
let Some(sw) = d.swatch(name) else { return Some(format!("no swatch `{name}`")) };
match &sw.paint {
Paint::Solid { swatch: Some(_), .. } => Some(format!("`{name}` is a tint swatch: pick its base or another global or spot color")),
Paint::Solid { .. } if sw.global => None,
Paint::Solid { .. } => Some(format!("`{name}` is a process color: pick a global or spot color")),
_ => Some(format!("`{name}` isn't a color swatch")),
}
}
/// `role`'s swatch in `d`, made as a global spot swatch in the document's color mode when `d`
/// lacks it → its paint at 100%. When a color group or a swatch that can't carry a role (a process
/// color that is not global, a tint, a gradient) has the swatch's name, the swatch is made under a
/// free name, which the role table then gives the role.
fn role_paint(d: &mut Document, role: Role) -> Result<Paint> {
let mut table = RoleTable::of(d);
let current = table.swatch(role);
let taken = match d.swatch(current) {
Some(_) => unfit_swatch(d, current).is_some(),
None => d.swatch_name_taken(current),
};
if taken {
let free = free_role_name(d, &table, role);
if let Some(slot) = table.0.get_mut(role.index()) {
*slot = free;
}
d.unknown.insert(ROLES_KEY.to_string(), table.to_value());
}
let name = table.swatch(role);
if d.swatch(name).is_none() {
let model = d.color_mode.model();
let color = role.color();
let color = if color.model() == model {
color
} else {
let cms = vectorcraft_color::cms::active();
cms.convert(&color, model, cms.settings().intent)
};
d.swatches.push(Swatch { name: name.to_string(), paint: Paint::solid(color), global: true, spot: true });
}
if let Some(why) = unfit_swatch(d, name) {
return Err(bad(SET_ROLE, format!("{why} (the {} role's swatch; addon.packaging.setRoleSwatch picks another)", role.name())));
}
d.tint_paint(name, 1.0).ok_or_else(|| bad(SET_ROLE, format!("`{name}` isn't a global or spot color")))
}
/// Gives object `id` of `d` `role`'s `paint` (`None`: takes its role away) → whether it changed.
fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Paint>, overprint: bool) -> bool {
let Some(n) = d.node_mut(id) else { return false };
let had = table.role_of(n);
let mut a = (*n.appearance).clone();
match paint {
Some(paint) => {
a.set_stroke(paint.clone());
if let Some(st) = a.stroke_mut() {
if st.width <= 0.0 {
st.width = 1.0;
}
// A hidden stroke would carry the role without drawing or printing the line.
st.visible = true;
st.overprint = overprint;
}
}
None => {
if had.is_none() {
return false;
}
if let Some(st) = a.stroke_mut() {
if let Paint::Solid { color, .. } = st.paint {
st.paint = Paint::solid(color);
}
st.overprint = false;
}
}
}
if a == *n.appearance {
return false;
}
n.appearance = vectorcraft_doc::Shared::new(a);
true
}
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
let role = role_param(p, SET_ROLE, true)?;
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
if ids.is_empty() {
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
}
let label = role.map_or("Remove Fold Line Role", |_| "Make Fold Line");
let mut changed = 0;
edit_counted(s, label, |d| {
let before = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned());
let paint = role.map(|r| role_paint(d, r)).transpose()?;
// A role swatch made again (its strokes may still name it) is a change of its own.
let made = (d.swatches.len(), d.unknown.get(ROLES_KEY).cloned()) != before;
let table = RoleTable::of(d);
changed = ids.iter().filter(|id| give_role(d, &table, **id, paint.as_ref(), overprint)).count();
Ok(changed + usize::from(made))
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
}
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, ROLES)?;
let d = &s.doc()?.doc;
let (scope, ids) = match (given, roots.is_empty()) {
(true, _) => ("ids", role_targets(d, &roots, false).0),
(false, false) => ("selection", role_targets(d, &roots, false).0),
(false, true) => ("document", document_targets(d)),
};
let table = RoleTable::of(d);
let mut counts = [0usize; 4];
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
if let Some(c) = counts.get_mut(r.index()) {
*c += 1;
}
}
let rows: Vec<Value> = Role::ALL
.into_iter()
.zip(counts)
.map(|(r, count)| {
let swatch = table.swatch(r);
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
})
.collect();
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
}
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
let Some(role) = role_param(p, SET_ROLE_SWATCH, false)? else { return Err(bad(SET_ROLE_SWATCH, "missing `role`")) };
let name = text_param(p, "swatch", SET_ROLE_SWATCH)?.ok_or_else(|| bad(SET_ROLE_SWATCH, "missing `swatch`"))?;
let d = &s.doc()?.doc;
if let Some(why) = unfit_swatch(d, name) {
return Err(bad(SET_ROLE_SWATCH, why));
}
let mut table = RoleTable::of(d);
if let Some(other) = Role::ALL.into_iter().find(|r| *r != role && table.swatch(*r) == name) {
return Err(bad(SET_ROLE_SWATCH, format!("`{name}` already carries the {} role", other.name())));
}
if let Some(slot) = table.0.get_mut(role.index()) {
*slot = name.to_string();
}
let value = table.to_value();
let changed = RoleTable::of(d) != table;
if changed {
s.edit("Role Swatches", |d, _| {
d.unknown.insert(ROLES_KEY.to_string(), value);
Ok(())
})?;
}
Ok(json!({ "role": role.id(), "swatch": name, "changed": changed }))
}
@@ -0,0 +1,540 @@
//! Tests for Packaging Tools: fold line roles, their swatches and the role table.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, Node, NodeKind};
use crate::*;
fn session(mode: &str) -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400, "colorMode": mode})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn rect(s: &mut Session, x: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap())
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn set_role(s: &mut Session, p: Value) -> Value {
s.execute("addon.packaging.setRole", &p).unwrap()
}
fn err(s: &mut Session, cmd: &str, p: Value) -> String {
s.execute(cmd, &p).unwrap_err().to_string()
}
fn b64(v: &Value) -> Vec<u8> {
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
}
/// The `roles` query's counts, in role order.
fn counts(s: &mut Session, p: Value) -> Vec<u64> {
let r = s.execute("addon.packaging.roles", &p).unwrap();
r["roles"].as_array().unwrap().iter().map(|r| r["count"].as_u64().unwrap()).collect()
}
#[test]
fn set_role_makes_the_spot_swatch_and_links_the_top_stroke() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
let before = steps(&s);
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)));
assert_eq!(steps(&s), before + 1, "one undo step");
let d = &s.doc().unwrap().doc;
let sw = d.swatch("Cut").unwrap();
assert!(sw.global && sw.spot, "{sw:?}");
assert_eq!(sw.paint, Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), "100% magenta in a CMYK document");
let st = node(&s, a).appearance.stroke().cloned().unwrap();
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), tint, .. } if n == "Cut" && *tint == 1.0), "{:?}", st.paint);
assert!(st.overprint, "role strokes overprint by default");
// Again: nothing changes, and no undo step is recorded.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!(r["changed"].as_u64(), Some(0));
assert_eq!(steps(&s), before + 1);
// Undo takes the swatch away with the role.
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
}
#[test]
fn each_role_gets_its_own_swatch_color_in_the_document_s_mode() {
let mut s = session("rgb");
for (i, role) in ["cut", "crease", "partialCut", "perforation"].into_iter().enumerate() {
let id = rect(&mut s, 20.0 + 60.0 * i as f64);
set_role(&mut s, json!({"role": role, "ids": [id.0]}));
}
let d = &s.doc().unwrap().doc;
let colors: Vec<Color> = ["Cut", "Crease", "Partial Cut", "Perforation"].iter().map(|n| d.swatch(n).unwrap().paint.color().unwrap()).collect();
assert!(colors.iter().all(|c| matches!(c, Color::Rgb { .. })), "an RGB document's swatches are RGB: {colors:?}");
assert_eq!(colors.iter().map(|c| c.to_hex()).collect::<BTreeSet<_>>().len(), 4, "four colors: {colors:?}");
}
#[test]
fn a_path_without_a_stroke_gets_one_and_overprint_can_be_left_off() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.edit("strip", |d, _| {
let n = d.node_mut(a).unwrap();
n.appearance.items.retain(AppearanceItem::is_fill);
Ok(())
})
.unwrap();
assert!(node(&s, a).appearance.stroke().is_none());
set_role(&mut s, json!({"role": "crease", "ids": [a.0], "overprint": false}));
let st = node(&s, a).appearance.stroke().cloned().unwrap();
assert_eq!(st.width, 1.0, "a 1 pt stroke");
assert!(!st.overprint);
assert!(matches!(&st.paint, Paint::Solid { swatch: Some(n), .. } if n == "Crease"));
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0], "overprint": "yes"})).contains("overprint"));
}
#[test]
fn none_takes_the_role_away_and_keeps_the_color() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
let shown = node(&s, a).appearance.stroke().unwrap().paint.color().unwrap();
let before = steps(&s);
let r = set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
assert_eq!(r["changed"].as_u64(), Some(1), "the plain rectangle has no role to take away");
assert_eq!(steps(&s), before + 1);
let st = node(&s, a).appearance.stroke().cloned().unwrap();
assert_eq!(st.paint, Paint::solid(shown));
assert!(!st.overprint);
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 0, 0, 0]);
// Nothing left with a role: no undo step.
set_role(&mut s, json!({"role": "none", "ids": [a.0, b.0]}));
assert_eq!(steps(&s), before + 1);
}
#[test]
fn bad_roles_and_targets_are_refused() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "fold", "ids": [a.0]})).contains("unknown role"));
assert!(err(&mut s, "addon.packaging.setRole", json!({"ids": [a.0]})).contains("role"));
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": 3, "ids": [a.0]})).contains("role"));
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("addon.packaging.setRole", &json!({"role": "cut"})).is_err(), "nothing selected");
let t = id_of(&s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Lid", "size": 20})).unwrap());
let before = steps(&s);
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [t.0]})).contains("select a path"));
assert_eq!(steps(&s), before);
assert!(s.doc().unwrap().doc.swatch("Cut").is_none(), "a refused run makes no swatch");
// Text beside a path is skipped and counted.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, t.0]}));
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)));
}
#[test]
fn groups_are_walked_and_their_locked_and_hidden_members_left_out() {
let mut s = session("cmyk");
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.edit("lock", |d, _| {
d.node_mut(b).unwrap().locked = true;
d.node_mut(c).unwrap().visible = false;
Ok(())
})
.unwrap();
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0]}));
assert_eq!(r["ids"], json!([a.0]));
assert_eq!(r["skipped"].as_u64(), Some(2), "the locked and the hidden member");
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [0, 1, 0, 0]);
// Named directly, a locked or hidden path is left out too.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0, c.0]}));
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([a.0]), Some(2)));
let before = steps(&s);
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [b.0]})).contains("locked"));
assert_eq!(steps(&s), before);
assert_eq!(counts(&mut s, json!({"ids": [b.0, c.0]})), [0, 0, 0, 0]);
}
#[test]
fn a_clip_group_s_clipping_path_is_skipped_and_counted() {
let mut s = session("cmyk");
let (art, mask) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
let r = set_role(&mut s, json!({"role": "cut", "ids": [g.0]}));
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([art.0]), Some(1)), "the clipping path is left out and counted");
}
#[test]
fn a_group_and_its_member_count_once_and_locked_lines_count_in_every_scope() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let r = set_role(&mut s, json!({"role": "crease", "ids": [g.0, a.0]}));
assert_eq!(r["ids"], json!([a.0, b.0]), "each path once");
assert_eq!(counts(&mut s, json!({"ids": [g.0, a.0]})), [0, 2, 0, 0]);
set_role(&mut s, json!({"role": "cut", "ids": [b.0]}));
s.edit("lock", |d, _| {
d.node_mut(b).unwrap().locked = true;
Ok(())
})
.unwrap();
// A locked line keeps its role and is counted, whether its group is selected or not.
assert_eq!(counts(&mut s, json!({"ids": [g.0]})), [1, 1, 0, 0]);
s.execute("select.none", &json!({})).unwrap();
assert_eq!(counts(&mut s, json!({})), [1, 1, 0, 0]);
}
#[test]
fn a_process_swatch_named_like_a_role_swatch_keeps_its_name() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.new", &json!({"name": "Cut", "color": "#ff0000"})).unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot), "the role swatch is made beside it");
assert!(d.swatch("Cut").is_some_and(|w| !w.global), "the process swatch is left as it was");
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
}
#[test]
fn the_free_role_swatch_name_is_searched_past_ten_thousand() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
let taken = std::iter::once("Cut".to_string()).chain((2..10_000).map(|i| format!("Cut {i}"))).chain(["Cut 10004".to_string()]);
let process = |name: String| vectorcraft_color::Swatch { name, paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), global: false, spot: false };
Arc::make_mut(&mut s.doc_mut().unwrap().doc).swatches.extend(taken.map(process));
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 10000"));
assert!(d.swatch("Cut 10000").is_some_and(|w| w.spot), "the role swatch is made under the first free name");
assert!(d.swatch("Cut 10004").is_some_and(|w| !w.global), "a taken name is left as it was");
}
#[test]
fn a_merged_role_swatch_hands_its_role_to_the_kept_swatch() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
s.execute("swatch.merge", &json!({"names": ["Die", "Cut"]})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the cut line is still a cut line");
// A kept swatch that already carries a role keeps it; the merged role's lines take it.
s.execute("swatch.merge", &json!({"names": ["Crease", "Die"]})).unwrap();
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
assert_eq!((&table["cut"], &table["crease"]), (&json!("Die"), &json!("Crease")), "{table}");
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [0, 2, 0, 0]);
// The next Make Cut Line makes the Cut role's swatch again.
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert!(s.doc().unwrap().doc.swatch("Die").is_some_and(|w| w.spot));
assert_eq!(counts(&mut s, json!({"ids": [a.0, b.0]})), [1, 1, 0, 0]);
}
#[test]
fn a_global_process_swatch_can_carry_a_role() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "global": true})).unwrap();
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "partialCut", "swatch": "Die"})).unwrap();
set_role(&mut s, json!({"role": "partialCut", "ids": [a.0]}));
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 1, 0]);
}
#[test]
fn roles_counts_the_selection_or_the_whole_document() {
let mut s = session("cmyk");
let (a, b, c) = (rect(&mut s, 20.0), rect(&mut s, 100.0), rect(&mut s, 180.0));
set_role(&mut s, json!({"role": "cut", "ids": [a.0, b.0]}));
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
s.execute("select.set", &json!({"ids": [a.0, c.0]})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("selection"), Some(2)));
assert_eq!(counts(&mut s, json!({})), [1, 0, 1, 0]);
s.execute("select.none", &json!({})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["scope"].as_str(), r["selected"].as_u64()), (Some("document"), Some(0)));
assert_eq!(counts(&mut s, json!({})), [2, 0, 1, 0]);
let rows = r["roles"].as_array().unwrap();
assert_eq!(rows[0], json!({"role": "cut", "name": "Cut", "swatch": "Cut", "exists": true, "count": 2}));
assert_eq!(rows[1]["exists"], json!(false), "no Crease swatch yet");
}
#[test]
fn role_swatches_maps_a_role_to_another_swatch() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
let before = steps(&s);
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
assert_eq!(r["changed"], json!(true));
assert_eq!(steps(&s), before + 1);
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
// The old swatch's objects keep their color and lose the role.
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0]);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert!(matches!(&node(&s, a).appearance.stroke().unwrap().paint, Paint::Solid { swatch: Some(n), .. } if n == "Die"));
// The same mapping again changes nothing.
let steps_now = steps(&s);
let r = s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
assert_eq!((r["changed"].clone(), steps(&s)), (json!(false), steps_now));
}
#[test]
fn a_renamed_role_swatch_keeps_its_role() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "crease", "ids": [a.0]}));
s.execute("swatch.edit", &json!({"name": "Crease", "newName": "Score"})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["crease"], json!("Score"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
// A swatch that carries no role leaves the table alone.
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "Red Ink"})).unwrap();
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
assert_eq!(table, json!({"cut": "Cut", "crease": "Score", "partialCut": "Partial Cut", "perforation": "Perforation"}));
// Undo puts the old name back in the table with the swatch.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.unknown.get("packagingRoles").is_none());
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 1, 0, 0]);
}
#[test]
fn a_role_swatch_renamed_to_another_role_s_name_leaves_each_role_its_own_swatch() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
// No Crease swatch exists yet, so the name is free for the Cut swatch.
s.execute("swatch.edit", &json!({"name": "Cut", "newName": "Crease"})).unwrap();
let table = s.doc().unwrap().doc.unknown.get("packagingRoles").cloned().unwrap();
assert_eq!((&table["cut"], &table["crease"]), (&json!("Crease"), &json!("Crease 2")), "{table}");
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0], "the line is still a cut line");
}
#[test]
fn a_role_swatch_that_stops_being_global_hands_its_role_to_a_new_swatch() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "perforation", "ids": [a.0]}));
s.execute("swatch.edit", &json!({"name": "Perforation", "spot": false, "global": false})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["perforation"], json!("Perforation 2"));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [0, 0, 0, 0], "the unlinked stroke has no role");
set_role(&mut s, json!({"role": "perforation", "ids": [b.0]}));
assert!(s.doc().unwrap().doc.swatch("Perforation 2").is_some_and(|w| w.spot));
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 0, 0, 1]);
}
#[test]
fn a_color_group_named_like_a_role_swatch_keeps_its_name() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.newGroup", &json!({"name": "Cut", "colors": ["#ff0000"]})).unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let d = &s.doc().unwrap().doc;
assert_eq!(d.unknown.get("packagingRoles").unwrap()["cut"], json!("Cut 2"));
assert!(d.swatch("Cut 2").is_some_and(|w| w.spot) && d.swatch("Cut").is_none());
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
}
#[test]
fn set_role_makes_a_deleted_role_swatch_again_for_strokes_that_still_name_it() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
s.execute("swatch.delete", &json!({"name": "Cut", "unlink": false})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Cut").is_none());
let before = steps(&s);
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!(r["changed"].as_u64(), Some(0), "the stroke already names the swatch");
assert!(s.doc().unwrap().doc.swatch("Cut").is_some_and(|w| w.spot), "the swatch is back");
assert_eq!(steps(&s), before + 1, "as one undo step");
}
#[test]
fn a_hidden_stroke_is_shown_when_it_takes_a_role() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.edit("hide", |d, _| {
if let Some(AppearanceItem::Stroke(st)) = d.node_mut(a).unwrap().appearance.items.iter_mut().find(|i| !i.is_fill()) {
st.visible = false;
}
Ok(())
})
.unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert!(node(&s, a).appearance.stroke().unwrap().visible);
}
#[test]
fn role_swatches_refuses_swatches_that_cannot_carry_a_role() {
let mut s = session("cmyk");
let ramp = json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}]});
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp})).unwrap();
s.execute("swatch.new", &json!({"name": "Plain", "color": "#336699"})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink Tint", "swatch": "Ink", "tint": 0.5})).unwrap();
s.execute("swatch.new", &json!({"name": "Crease", "color": {"model": "cmyk", "c": 1, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
let before = steps(&s);
for (swatch, says) in [
("Nope", "no swatch"),
("Ramp", "isn't a color swatch"),
("Plain", "process color"),
("Ink Tint", "tint swatch"),
("[None]", "can't carry a role"),
("[Registration]", "can't carry a role"),
("Crease", "already carries the Crease role"),
] {
let e = err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": swatch}));
assert!(e.contains(says), "{swatch}: {e}");
}
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "none", "swatch": "Ink"})).contains("unknown role"));
assert!(err(&mut s, "addon.packaging.setRoleSwatch", json!({"role": "cut"})).contains("swatch"));
assert_eq!(steps(&s), before, "no refusal records an undo step");
}
#[test]
fn a_damaged_role_table_reads_as_the_defaults() {
let mut s = session("cmyk");
s.edit("damage", |d, _| {
d.unknown.insert("packagingRoles".into(), json!({"cut": 5, "crease": "", "partialCut": null, "extra": "x"}));
Ok(())
})
.unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
assert_eq!(swatches, ["Cut", "Crease", "Partial Cut", "Perforation"]);
s.edit("not an object", |d, _| {
d.unknown.insert("packagingRoles".into(), json!("Cut"));
Ok(())
})
.unwrap();
let a = rect(&mut s, 20.0);
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
assert_eq!(counts(&mut s, json!({"ids": [a.0]})), [1, 0, 0, 0]);
// One swatch named for two roles: the later role takes its own default.
s.edit("duplicate", |d, _| {
d.unknown.insert("packagingRoles".into(), json!({"cut": "Crease", "crease": "Crease", "partialCut": "Cut"}));
Ok(())
})
.unwrap();
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
let swatches: Vec<&str> = r["roles"].as_array().unwrap().iter().map(|r| r["swatch"].as_str().unwrap()).collect();
assert_eq!(swatches, ["Crease", "Crease 2", "Cut", "Perforation"]);
let b = rect(&mut s, 100.0);
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
assert_eq!(counts(&mut s, json!({"ids": [b.0]})), [0, 1, 0, 0], "the crease line is a crease line");
}
#[test]
fn native_save_and_open_keep_the_role_table_and_the_roles() {
let mut s = session("cmyk");
let a = rect(&mut s, 20.0);
s.execute("swatch.new", &json!({"name": "Die", "color": {"model": "cmyk", "c": 0, "m": 0.8, "y": 0.2, "k": 0}, "spot": true})).unwrap();
s.execute("addon.packaging.setRoleSwatch", &json!({"role": "cut", "swatch": "Die"})).unwrap();
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(s.doc().unwrap().doc.unknown.get("packagingRoles").unwrap()["cut"], json!("Die"));
s.execute("select.none", &json!({})).unwrap();
assert_eq!(counts(&mut s, json!({})), [1, 0, 0, 0]);
}
/// A document with one rectangle of each of Cut and Crease.
fn two_roles() -> Session {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 100.0));
set_role(&mut s, json!({"role": "cut", "ids": [a.0]}));
set_role(&mut s, json!({"role": "crease", "ids": [b.0]}));
s
}
fn export(s: &mut Session, format: &str) -> String {
String::from_utf8_lossy(&b64(&s.execute("document.export", &json!({"format": format})).unwrap())).into_owned()
}
#[test]
fn pdf_prints_each_role_on_its_swatch_s_separation_and_overprints_it() {
let mut s = two_roles();
let c = rect(&mut s, 180.0);
set_role(&mut s, json!({"role": "partialCut", "ids": [c.0]}));
let bytes = vectorcraft_pdf::export(
&s.doc().unwrap().doc,
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
)
.unwrap();
let pdf = String::from_utf8_lossy(&bytes);
assert!(pdf.contains("/Separation/Cut"), "the Cut line prints on the Cut plate");
assert!(pdf.contains("/Separation/Crease"));
assert!(pdf.contains("/Separation/Partial#20Cut"), "a name with a space");
assert!(pdf.contains("/OP true"), "the role strokes overprint");
// Without overprint, nothing in the file overprints.
let mut plain = session("cmyk");
let (a, b) = (rect(&mut plain, 20.0), rect(&mut plain, 100.0));
set_role(&mut plain, json!({"role": "cut", "ids": [a.0], "overprint": false}));
set_role(&mut plain, json!({"role": "crease", "ids": [b.0], "overprint": false}));
let bytes = vectorcraft_pdf::export(
&plain.doc().unwrap().doc,
&vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() },
)
.unwrap();
assert!(!String::from_utf8_lossy(&bytes).contains("/OP true"));
assert!(!export(&mut s, "pdf").is_empty());
}
#[test]
fn svg_dxf_and_hpgl_keep_the_default_role_swatches_apart() {
let mut s = two_roles();
let svg = export(&mut s, "svg");
let strokes: BTreeSet<&str> = svg.split("stroke=\"").skip(1).filter_map(|t| t.split('"').next()).filter(|c| c.starts_with('#')).collect();
let strokes = if strokes.is_empty() {
svg.split("stroke:").skip(1).filter_map(|t| t.split([';', '"', '}']).next()).filter(|c| c.starts_with('#')).collect()
} else {
strokes
};
assert_eq!(strokes.len(), 2, "two stroke colors: {svg}");
let dxf = export(&mut s, "dxf");
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
// The rectangles' white fills come out as true colors too.
let colors: BTreeSet<&str> = lines.windows(2).filter(|w| w[0] == "420" && w[1] != "16777215").map(|w| w[1]).collect();
assert_eq!(colors.len(), 2, "two stroke true colors: {colors:?}");
let plot = s.execute("document.export", &json!({"format": "hpgl", "hpglVersion": "hpgl2"})).unwrap();
let plot = String::from_utf8_lossy(&b64(&plot)).into_owned();
assert!(plot.contains("SP1") && plot.contains("SP2"), "a pen per role swatch color: {plot}");
}
#[test]
fn compound_paths_carry_a_role() {
let mut s = session("cmyk");
let (a, b) = (rect(&mut s, 20.0), rect(&mut s, 30.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
assert!(matches!(node(&s, c).kind, NodeKind::Compound { .. }));
let r = set_role(&mut s, json!({"role": "cut", "ids": [c.0]}));
assert_eq!(r["ids"], json!([c.0]));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [1, 0, 0, 0]);
// A member named by id gives its compound the role.
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
}
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
+11 -1
View File
@@ -567,6 +567,16 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
let through: Vec<NodeId> = match p.get("through") {
None => vec![],
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
Some(v) => {
let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?;
ids.iter()
.map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids")))
.collect::<Result<_>>()?
}
};
let (eid, count, changed) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
@@ -575,7 +585,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
let targets = match scope {
LpScope::One => vec![eid],
LpScope::Connected => b::connected_edges(n, eid, &like),
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
LpScope::SamePaint => std::iter::once(eid)
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
.collect(),
+29 -1
View File
@@ -595,6 +595,8 @@ struct Relink {
styles: BTreeMap<u32, u32>,
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
colors: BTreeMap<String, Color>,
/// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]).
keep_styles: bool,
}
impl Relink {
@@ -674,7 +676,9 @@ impl Relink {
/// Relink a node tree (the mirror of [`node_refs`]).
fn node(&self, n: &mut Node) {
self.appearance(&mut n.appearance);
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
if !self.keep_styles {
n.extras_mut().graphic_style = n.extras().graphic_style.and_then(|id| self.styles.get(&id).copied());
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
self.node(Arc::make_mut(&mut m.art));
}
@@ -1109,6 +1113,30 @@ impl Clipboard {
self.import_used(d, &self.used(), choices, same_doc)
}
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
/// `choices` merge the color that swatch has in `d`, as pasting into `d` gives them (Paste
/// without Formatting sets its pie legend labels' contrast from the wedge colors before it
/// pastes). Nothing changes for the document the objects came from (`same_doc`).
pub(crate) fn show_merged_colors(&mut self, d: &Document, choices: &SwatchChoices, same_doc: bool) {
if same_doc {
return;
}
let used = self.used();
let colors: BTreeMap<String, Color> = self
.conflicts(d, &used)
.into_iter()
.filter(|(w, _)| choices.of(&w.name) == SwatchChoice::Merge)
.filter_map(|(w, _)| d.global_color(&w.name).map(|c| (w.name.clone(), c)))
.collect();
if colors.is_empty() {
return;
}
let relink = Relink { colors, keep_styles: true, ..Default::default() };
for n in &mut self.nodes {
relink.node(n);
}
}
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
/// compared and relinked with their names here, and each loop of definitions that use each
+8 -2
View File
@@ -227,12 +227,18 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) };
*p0 = end;
if pts.len() < 2 {
// No stroke to add: the brush alone changes, when it is not the path's already.
// No stroke to add: the brush alone changes, when it is not the path's already, and the
// path is selected or deselected as a longer continuation leaves it.
if let Some(name) = brush_name
&& s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name))
{
s.edit("Paintbrush", |d, _| {
s.edit("Paintbrush", |d, sel| {
set_brush(d, target, name);
if keep_selected {
sel.set([id]);
} else {
sel.remove(id);
}
Ok(())
})?;
}
+8 -2
View File
@@ -367,7 +367,8 @@ fn edit_effects(
/// [`edit_effects`] for several effects of one list (`indices`): `f` gets each target's list and
/// the positions of `indices` there, ascending; with `aligned`, a position a target doesn't share
/// is left out of it, and a target sharing none of them is left out.
/// is left out of it, and a target sharing none of them is left out. A position no target has is
/// an error with `none`, and nothing changes.
#[allow(clippy::too_many_arguments)]
fn edit_effects_at(
s: &mut Session,
@@ -396,7 +397,12 @@ fn edit_effects_at(
// Each target's list and the positions in it, in the order the targets first come up.
let mut targets: Vec<(NodeId, Option<usize>, Vec<usize>)> = vec![];
for &index in indices {
for (id, at, i) in effect_targets(s, p, item, index, cmd)? {
let found = effect_targets(s, p, item, index, cmd)?;
// An aligned effect of a design's art that no other object has is refused, as it is given alone.
if found.is_empty() {
return Err(EngineError::Other(none.into()));
}
for (id, at, i) in found {
match targets.iter_mut().find(|t| t.0 == id && t.1 == at) {
Some(t) => t.2.push(i),
None => targets.push((id, at, vec![i])),
+8 -5
View File
@@ -265,18 +265,21 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, or the
/// path filled with its run's stroke under a transform that is not a similarity, has one
/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves
/// the document as it is and stops at the first such path.
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
let gradient =
|st: &vectorcraft_doc::CharStyle| matches!(st.fill, Paint::Gradient(_)) || (st.has_stroke() && matches!(st.stroke, Paint::Gradient(_)));
if !t.runs.iter().any(|r| gradient(&r.style)) {
return false;
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let first = t.first_style();
let expands = |run: usize, outline: &BezPath| {
let style = t.runs.get(run).map_or(&first, |r| &r.style);
if !matches!(style.fill, Paint::Gradient(_)) {
if !gradient(style) {
return false;
}
let path = PathData::from_bezpath(outline);
@@ -284,8 +287,8 @@ fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
return false;
}
let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default());
vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
gradient_expands(d, &piece)
let stroke = vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
gradient_expands(d, &piece) || stroke.is_some_and(|s| gradient_expands(d, &s))
};
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
File diff suppressed because one or more lines are too long
+40 -15
View File
@@ -174,23 +174,48 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
/// blocks whose signature is `8BIM` are given.
pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
let mut r = Reader::new(resources);
std::iter::from_fn(move || {
if r.rest().is_empty() {
return None;
std::iter::from_fn(move || if r.rest().is_empty() { None } else { block(&mut r).ok() })
.filter(move |(ours, ..)| *ours || !signed)
.map(|(_, id, name, data)| (id, name, data))
}
/// The data of the first `8BIM` image resource block `id` of `resources`. `None` when there is
/// none before the blocks end or before a block that is cut short ahead of it. An error when
/// that block itself is cut short.
pub(super) fn resource(resources: &[u8], id: u16) -> Result<Option<&[u8]>, String> {
let mut r = Reader::new(resources);
while !r.rest().is_empty() {
match block(&mut r) {
Ok((true, i, _, data)) if i == id => return Ok(Some(data)),
Ok(_) => {}
Err(Some((true, i))) if i == id => return Err(TRUNCATED.into()),
Err(_) => return Ok(None),
}
let ours = r.take(4).ok()? == b"8BIM";
let id = r.u16().ok()?;
}
Ok(None)
}
/// An image resource block: whether its signature is `8BIM`, its id, its name (the bytes of its
/// Pascal string) and its data.
type Block<'a> = (bool, u16, &'a [u8], &'a [u8]);
/// The image resource block that `r` starts with. When it is cut short, the error gives whether
/// its signature is `8BIM` and its id, when those were read.
fn block<'a>(r: &mut Reader<'a>) -> Result<Block<'a>, Option<(bool, u16)>> {
let ours = r.take(4).map_err(|_| None)? == b"8BIM";
let id = r.u16().map_err(|_| None)?;
let mut rest = || -> Result<(&'a [u8], &'a [u8]), String> {
// A Pascal string padded to an even size, length byte included.
let len = usize::from(r.u8().ok()?);
let name = r.take(len).ok()?;
r.take((len + 1) % 2).ok()?;
let size = usize::try_from(r.u32().ok()?).ok()?;
let data = r.take(size).ok()?;
r.take(size % 2).ok()?;
Some((ours, id, name, data))
})
.filter(move |(ours, ..)| *ours || !signed)
.map(|(_, id, name, data)| (id, name, data))
let len = usize::from(r.u8()?);
let name = r.take(len)?;
r.take((len + 1) % 2)?;
let size = usize::try_from(r.u32()?).map_err(|_| TRUNCATED.to_string())?;
let data = r.take(size)?;
r.take(size % 2)?;
Ok((name, data))
};
let (name, data) = rest().map_err(|_| Some((ours, id)))?;
Ok((ours, id, name, data))
}
/// The resource naming the document's clipping path.
+4 -4
View File
@@ -18,7 +18,7 @@
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use super::psdread::{Reader, TRUNCATED, header, resources};
use super::psdread::{Reader, TRUNCATED, header, resource};
/// The image resource that holds the slices.
const SLICES: u16 = 1050;
@@ -51,12 +51,12 @@ struct Stored {
}
/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050
/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB
/// file, or its slices can't be read.
/// before the image resources end, or before a block that is cut short ahead of it). An error when
/// the file isn't a PSD or PSB file, resource 1050 is cut short, or its slices can't be read.
fn read(bytes: &[u8]) -> Result<Option<Stored>, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) };
let Some(data) = resource(h.resources, SLICES)? else { return Ok(None) };
Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) }))
}
@@ -38,3 +38,19 @@ fn export_pdf_converts_colours_writes_the_output_intent_and_real_text() {
let bad = s.execute("document.exportPdf", &json!({"output": {"conversion": "destination", "destination": "Missing"}}));
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
}
/// Over a saved preset whose Profiles setting is `none`, `"default"` leaves the setting unset,
/// while `null` keeps the preset's value; an unknown value is a bad parameter.
#[test]
fn profiles_default_unsets_a_presets_profiles_setting() {
use vectorcraft_pdf::{PdfPreset, PdfSettings, ProfileInclusion};
let mut settings = PdfSettings::default();
settings.output.profiles = Some(ProfileInclusion::None);
let saved = [PdfPreset { name: "No profiles".into(), description: String::new(), settings }];
let resolve = |output: Value| pdf::resolve("document.exportPdf", &json!({"preset": "No profiles", "output": output}), &saved);
assert_eq!(resolve(json!({"profiles": "default"})).unwrap().output.profiles, None);
assert_eq!(resolve(json!({"profiles": null})).unwrap().output.profiles, Some(ProfileInclusion::None));
assert_eq!(resolve(json!({"profiles": "all"})).unwrap().output.profiles, Some(ProfileInclusion::All));
let bad = resolve(json!({"profiles": "sometimes"}));
assert!(matches!(bad, Err(crate::EngineError::BadParams { .. })), "{bad:?}");
}
@@ -371,6 +371,29 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() {
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
}
#[test]
fn a_slices_resource_cut_short_warns_and_the_file_still_opens() {
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
// Image resource `id`, the last of the image resources, declares 10 bytes more than they hold.
let cut = |layers: bool, id: u16, data: &[u8]| {
let mut f = with_resource(&psd(layers), id, data);
let sig = [&b"8BIM"[..], &id.to_be_bytes()].concat();
let at = f.windows(6).rposition(|w| w == sig.as_slice()).unwrap() + 8;
f[at..at + 4].copy_from_slice(&(data.len() as u32 + 10).to_be_bytes());
f
};
for layers in [true, false] {
let (s, r) = open(&cut(layers, 1050, &good), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("cut short")), "{w:?}");
assert!(slices(&s).is_empty());
assert!(s.doc().unwrap().doc.art_bounds().is_some());
// Another resource cut short says nothing about slices.
let (s, r) = open(&cut(layers, 1051, &[0, 1]), json!({}));
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
}
}
#[test]
fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() {
let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);
+36
View File
@@ -1109,6 +1109,42 @@ fn aligned_effect_indices_past_the_end_of_a_graph_designs_art_are_refused() {
assert!(rows(&s, mark).effects.is_empty());
}
/// With a graph design's art given first and `aligned: true`, `effect.remove` and `effect.duplicate` with `indices` are an
/// error and change nothing when one of the art's effects is one no other object has, as with that index given alone.
#[test]
fn aligned_effect_indices_of_a_graph_designs_art_that_no_object_has_are_refused() {
let rows = |s: &Session, id: NodeId| (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
let (mut s, _, art, mark) = aligned_design_art();
// The art has a shadow and a roughen, the mark the shadow only.
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [mark.0], "item": null})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [mark.0], "item": null})).unwrap();
s.edit("Effects", |d, _| {
let effects = d.node(mark).unwrap().appearance.effects.clone();
d.node_mut(art).unwrap().appearance.effects = effects;
d.node_mut(mark).unwrap().appearance.effects.pop();
Ok(())
})
.unwrap();
let (art_was, mark_was) = (rows(&s, art), rows(&s, mark));
let steps = s.doc().unwrap().history.undo.len();
for cmd in ["effect.remove", "effect.duplicate"] {
assert!(s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "index": 1, "aligned": true})).is_err(), "{cmd}");
let e = s.execute(cmd, &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap_err();
assert!(e.to_string().contains("no effects at indices 0, 1"), "{cmd}: {e}");
assert_eq!((rows(&s, art), rows(&s, mark)), (art_was.clone(), mark_was.clone()), "{cmd}");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
}
// With the roughen on the mark too, both of its effects are removed.
s.edit("Roughen", |d, _| {
let roughen = d.node(art).unwrap().appearance.effects[1].clone();
d.node_mut(mark).unwrap().appearance.effects.push(roughen);
Ok(())
})
.unwrap();
s.execute("effect.remove", &json!({"ids": [art.0, mark.0], "item": null, "indices": [0, 1], "aligned": true})).unwrap();
assert!(rows(&s, mark).effects.is_empty());
}
/// A blur on a series group makes the whole group an image, which draws the design's art with the series' other art:
/// Expand Appearance does not put the art back beside the image.
#[test]
+16 -9
View File
@@ -555,9 +555,15 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
let of = super::appearance::reference_of(s, p, item, cmd)?;
let paint = if span {
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it.
let spanned: Vec<NodeId> = ids.iter().zip(item.per_target_of(s, of, &ids)).filter_map(|(id, it)| it.map(|_| *id)).collect();
placed_across(&s.doc()?.doc, &spanned, paint, p, fill)
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
// object's box is that of the row it edits.
let d = &s.doc()?.doc;
let mut spanned = Vec::with_capacity(ids.len());
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
}
placed_across(d, &spanned, paint, p, fill)
} else {
paint
};
@@ -730,14 +736,15 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String>
Ok(true)
}
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box its
/// stroke paints), at the gradient's angle and aspect: every target gets the same vector in
/// document coordinates, so the ramp runs on across them (#2127).
fn placed_across(d: &Document, ids: &[NodeId], paint: Paint, p: &Value, fill: bool) -> Paint {
/// `paint` placed once on the union of the bounds of `ids` (each one's fill box, or the box the
/// stroke it edits paints: the row given with it, `None` for the topmost), at the gradient's angle
/// and aspect: every target gets the same vector in document coordinates, so the ramp runs on
/// across them (#2127).
fn placed_across(d: &Document, ids: &[(NodeId, Option<usize>)], paint: Paint, p: &Value, fill: bool) -> Paint {
let union = ids
.iter()
.filter_map(|id| d.node(*id))
.filter_map(|n| item_paint_bounds(n, None, fill).or_else(|| n.geometric_bounds()))
.filter_map(|(id, index)| Some((d.node(*id)?, *index)))
.filter_map(|(n, index)| item_paint_bounds(n, index, fill).or_else(|| n.geometric_bounds()))
.filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))
.reduce(|a, b| a.union(b));
let (Some(union), Paint::Gradient(g)) = (union, &paint) else { return paint };
File diff suppressed because one or more lines are too long
@@ -40,6 +40,9 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.image.colorMask",
"addon.image.removeBackground",
"addon.image.removeColorMask",
"addon.packaging.roles",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
"addon.pathtools.addPoints",
"addon.pathtools.close",
"addon.pathtools.corner",
+6 -2
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swatch Options",
["Window", "Swatches"],
None,
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
"{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient} or {swatch}) or {pattern: name} replacing the swatch's colour; gradient or pattern with one of the same kind (stored as swatch.new stores it: a gradient keeps its aspect with or without start/end and holds no swatch link; a pattern is untransformed)} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). A fold line role the swatch carries (addon.packaging.roles) stays with it under its new name, and moves to a new swatch name when Global is turned off. Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}",
has_doc,
swatch_edit
),
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge Swatches",
["Window", "Swatches"],
None,
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step → {name, merged: [deleted names], relinked}",
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step. When the kept swatch is global and carries no fold line role (addon.packaging.roles), it takes the role of the first merged swatch that carried one → {name, merged: [deleted names], relinked}",
has_doc,
swatch_merge
),
@@ -937,6 +937,8 @@ fn swatch_edit(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let relinked = map_swatch_links(d, &mut |c, l, t| relink.apply(c, l, t));
// A fold line role carried by the swatch follows its new name, as the strokes do.
super::addons::role_swatch_edited(d, &name, &to, global);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
@@ -1139,6 +1141,8 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
take_swatches(d, merged, |_| true);
map_all_paints(d, &mut unplate);
let relinked = map_swatch_links(d, &mut relink);
// The lines of a merged role swatch link to the kept swatch, which takes that role.
super::addons::role_swatches_merged(d, merged, keep, link.is_some());
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
File diff suppressed because one or more lines are too long
+13 -2
View File
@@ -223,6 +223,8 @@ pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
("akiLeft", json!(v.aki_left)),
("akiRight", json!(v.aki_right)),
("tsume", json!(v.tsume)),
("diacriticHorizontal", json!(v.diacritic_horizontal)),
("diacriticVertical", json!(v.diacritic_vertical)),
("standardVerticalRoman", json!(v.standard_vertical_roman)),
("noBreak", json!(v.no_break)),
("digits", json!(v.digits)),
@@ -584,6 +586,13 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
if changed(key) && !(lo..=hi).contains(&st.tsume) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION;
let lo = -hi;
for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] {
if changed(key) && !(lo..=hi).contains(&value) {
return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}")));
}
}
let lines = vectorcraft_doc::text::WARICHU_LINES;
if changed("warichuLines") && !lines.contains(&st.warichu_lines) {
return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
@@ -1081,12 +1090,12 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
/// scales, leading, shifts, Insert Aki, Tsume, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
/// `src` of those skipped)
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
const RANGED: [&str; 22] = [
const RANGED: [&str; 24] = [
"size",
"h_scale",
"v_scale",
@@ -1095,6 +1104,8 @@ fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
"akiLeft",
"akiRight",
"tsume",
"diacriticHorizontal",
"diacriticVertical",
"tcyUpDown",
"tcyLeftRight",
"warichuLines",
+4 -1
View File
@@ -399,6 +399,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
json!({"akiRight": 1000.1}),
json!({"tsume": -0.1}),
json!({"tsume": 100.1}),
json!({"diacriticHorizontal": -1000.1}),
json!({"diacriticVertical": 1000.1}),
] {
let key = attrs.as_object().unwrap().keys().next().unwrap();
for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] {
@@ -422,7 +424,8 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() {
"baseline_shift": -1296.0,
"tcyUpDown": 1296.0, "tcyLeftRight": -1296.0,
"akiLeft": 0.0, "akiRight": 1000.0,
"tsume": 100.0
"tsume": 100.0,
"diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0
}}),
)
.unwrap();
+18 -14
View File
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Outlines",
["Type"],
Some("Cmd+Shift+O"),
"{} convert the selected text to groups of compound paths (one per glyph); the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
"{} convert the selected text to groups of compound paths (one per glyph); on type scaled unevenly, sheared or flattened, each glyph's stroke becomes a filled path over it, shaped as the canvas strokes it; the type object's own fills and strokes (not its characters') go on paths of its whole outline, below or above the glyphs as its Characters row places them; the group keeps the object's transparency, opacity mask and effects, once; a frame of threaded text leaves its thread with the text it shows; a dimension whose label is outlined becomes a plain group of its art → {ids}",
has_selection,
create_outlines
),
@@ -619,16 +619,25 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result<Value> {
/// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as
/// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced
/// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's
/// transform); `None` when the piece has no path.
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option<Node> {
/// transform), followed by a path (or compound path) filled with the run's stroke when the type's
/// transform is not a similarity; empty when the piece has no path.
fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Vec<Node> {
let path = PathData::from_bezpath(outline);
if path.is_empty() {
return None;
return vec![];
}
let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style());
let mut node = shape_node(d, path, None);
vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
Some(node)
let stroke = vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf);
let mut out = vec![node];
if let Some(s) = stroke
&& let Some(path) = s.path_data()
{
let mut filled = shape_node(d, path.clone(), None);
filled.appearance = s.appearance.clone();
out.push(filled);
}
out
}
fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
@@ -675,9 +684,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
children.push(Arc::new(d.reid(&art)));
break 'glyph;
}
if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) {
children.push(Arc::new(node));
}
children.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(Arc::new));
}
run_end.insert(g.run, children.len());
}
@@ -686,10 +693,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
// nothing there either).
let mut ruby: Vec<(usize, Arc<Node>)> = vec![];
for g in &lay.ruby {
let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue };
// After the glyphs of its run and of the runs before it.
let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0);
ruby.push((at, Arc::new(node)));
ruby.extend(type_piece(d, t, lay.bounds, g.run, &g.outline).into_iter().map(|node| (at, Arc::new(node))));
}
ruby.sort_by_key(|(at, _)| *at);
let mut ruby = ruby.into_iter().peekable();
@@ -711,9 +717,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
// Underline and strikethrough bars become paths of their run's paint too (#847).
for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) {
all.extend(bar.iter());
if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) {
children.push(Arc::new(node));
}
children.extend(type_piece(d, t, lay.bounds, run, &bar).into_iter().map(Arc::new));
}
// The object's own fills and strokes (not its characters') paint the whole outline:
// those below the Characters row under the characters, the others over them, with
@@ -1921,6 +1921,66 @@ fn tsume_is_a_character_attribute() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
}
/// Adjust Horizontal and Vertical Diacritic Position (Character panel, Middle Eastern options):
/// character attributes in thousandths of an em, 0 by default and saved only when not 0. Both
/// commands set them in one undo step, setting one leaves the other, a call that gives the values
/// the text already has records none, and a value that is not a number or lies outside -1000 to
/// 1000 is refused, naming the key, before anything changes; the native file and a character style
/// captured from the characters carry them.
#[test]
fn diacritic_positions_are_character_attributes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "بَب"})).unwrap()["id"].as_u64().unwrap();
let runs = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("text"),
};
let moved = |s: &Session| runs(s).iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect::<Vec<_>>();
let saved = serde_json::to_value(&runs(&s)[0].style).unwrap();
assert!(saved.get("diacriticHorizontal").is_none() && saved.get("diacriticVertical").is_none());
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"diacriticHorizontal": -150})).unwrap();
s.execute("text.setFormat", &json!({"diacriticVertical": 250})).unwrap();
assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 250.0)], "setting one leaves the other");
let undo = s.doc().unwrap().history.undo.len();
s.execute("text.setFormat", &json!({"diacriticHorizontal": -150, "diacriticVertical": 250})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step without a change");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(moved(&s), [("بَب".to_string(), -150.0, 0.0)], "one undo step");
s.execute("edit.redo", &json!({})).unwrap();
let mark = "بَ".len();
s.execute("text.setRangeStyle", &json!({"id": id, "start": "ب".len(), "end": mark, "diacriticVertical": -1000})).unwrap();
assert_eq!(moved(&s), [("ب".to_string(), -150.0, 250.0), ("\u{064E}".to_string(), -150.0, -1000.0), ("ب".to_string(), -150.0, 250.0)]);
let saved = serde_json::to_value(&runs(&s)[1].style).unwrap();
assert_eq!((saved["diacriticHorizontal"].clone(), saved["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0)));
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
let reopened: Vec<_> = t.runs.iter().map(|r| (r.text.clone(), r.style.diacritic_horizontal, r.style.diacritic_vertical)).collect();
assert_eq!(reopened, moved(&s));
let attrs = super::super::textstyles::char_attrs(&runs(&s)[1].style);
assert_eq!((attrs["diacriticHorizontal"].clone(), attrs["diacriticVertical"].clone()), (json!(-150.0), json!(-1000.0)));
let before = moved(&s);
let undo = s.doc().unwrap().history.undo.len();
for (cmd, p, want) in [
("text.setFormat", json!({"diacriticHorizontal": "50"}), "`diacriticHorizontal` must be a number"),
("text.setFormat", json!({"diacriticVertical": 1000.5}), "`diacriticVertical` must be from -1000 to 1000"),
("text.setRangeStyle", json!({"id": id, "diacriticVertical": true}), "`diacriticVertical` must be a number"),
(
"text.setRangeStyle",
json!({"id": id, "start": 0, "end": mark, "diacriticHorizontal": -1001}),
"`diacriticHorizontal` must be from -1000 to 1000",
),
] {
let e = s.execute(cmd, &p).unwrap_err();
assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}");
}
assert_eq!(moved(&s), before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step for a refused call");
}
/// Standard Vertical Roman Alignment (Character panel menu, East Asian options): a character
/// attribute, off by default and saved only when on. Documents written before it read as off; a
/// character style captured from the characters carries it.
+7
View File
@@ -1783,6 +1783,13 @@ fn strip_formatting(n: &mut vectorcraft_doc::Node) {
fn paste_plain(s: &mut Session, p: &Value) -> Result<Value> {
let saved = s.clipboard.nodes.clone();
// Pasted colors linked to a swatch merged with the document's show its color, so a pasted pie's legend labels take
// the contrast of the wedges as pasted. A `swatchConflict` the paste refuses is left to its error.
if let (Ok(choices), Ok(st)) = (super::clipboard::SwatchChoices::parse("edit.pasteWithoutFormatting", p), s.doc()) {
let same_doc = s.clipboard.source_doc == Some(st.uid);
let d = std::sync::Arc::clone(&st.doc);
s.clipboard.show_merged_colors(&d, &choices, same_doc);
}
for n in &mut s.clipboard.nodes {
strip_formatting(n);
}
+34
View File
@@ -1037,6 +1037,40 @@ fn brush_freehand_direct_call_has_one_undo_step() {
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Paintbrush"), "a stroke with a brush is a Paintbrush step");
}
/// A `brush.freehand` call that continues a path by one point changes only the path's brush, and
/// applies `keepSelected` as a longer continuation does: off, the path is deselected while the
/// rest of the selection stays; on, the path is selected. A call that leaves the brush as it is
/// changes neither the selection nor the undo history.
#[test]
fn brush_freehand_continued_by_one_point_follows_keep_selected() {
let mut s = session();
let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap();
let p = NodeId(r["id"].as_u64().unwrap());
let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
let extend = json!({"id": p.0, "end": "end"});
select(&mut s, &[p, a]);
let off = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots", "keepSelected": false});
assert_eq!(s.execute("brush.freehand", &off).unwrap()["id"], json!(p.0));
assert_eq!(brush_of(&s, p).as_deref(), Some("Dots"));
assert_eq!(selected(&s), [a], "Keep selected off: the path is deselected and the rest stays");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "one Undo takes back the brush");
assert_eq!(selected(&s), [p, a], "Undo gives back the earlier selection");
select(&mut s, &[a]);
let on = json!({"points": [[120, 10]], "extend": extend, "brush": "Dots"});
s.execute("brush.freehand", &on).unwrap();
assert_eq!(brush_of(&s, p).as_deref(), Some("Dots"));
assert_eq!(selected(&s), [p], "Keep selected on: the continued path is selected");
select(&mut s, &[a]);
let undo = s.doc().unwrap().history.undo.len();
s.execute("brush.freehand", &on).unwrap();
assert_eq!(selected(&s), [a], "the same brush again: the selection stays");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step");
}
/// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one
/// and a new filled pencil path while the stroke is None) instead of reporting it painted: the
/// document, the selection and the undo history stay as they were. Without a brush the path is
+370
View File
@@ -3908,6 +3908,266 @@ fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() {
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]);
}
/// A triple-click whose first click is released across an edge, in the face it then clicks twice,
/// matches that face's fill from before the first click: the release painted it too.
#[test]
fn live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
assert_eq!([a, b].map(|f| fill_of(&s, f)), [green.clone(), green.clone()], "the release across x = 50 fills both faces");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A triple-click whose third press lands in another face and is released in the face its first
/// two clicks painted still matches that face's fill from before the first click.
#[test]
fn live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::TripleClick, 55.0, 25.0), v).unwrap();
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A triple-click whose first click makes the Live Paint group and is released across an edge, in
/// the face it then clicks twice, matches the fill that face was made with.
#[test]
fn live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill() {
let mut s = session();
let ids: Vec<NodeId> = [0.0, 50.0, 200.0, 300.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect();
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
for (id, c) in ids.iter().zip([red, red, blue, red]) {
set_fill(&mut s, *id, c);
}
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
assert_eq!(faces[..2].iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone()], "the release fills both faces");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone(), Paint::solid(blue), green]);
}
/// When the first click makes the Live Paint group and is released in a face covered by a source
/// path with no fill in front of a filled one, the face was made with the filled source's fill, as
/// Make gives it, so the triple-click there matches that fill and not none.
#[test]
fn live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill() {
let mut s = session();
let red = Color::rgb(1.0, 0.0, 0.0);
let (a, b, d) = (rect(&mut s, 0.0, 0.0, 50.0, 50.0), rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
for id in [a, b, d] {
set_fill(&mut s, id, red);
}
let (c, e) = (rect(&mut s, 60.0, 10.0, 30.0, 30.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
s.edit("t", |doc, _| {
for id in [c, e] {
doc.node_mut(id).unwrap().appearance.set_fill(Paint::None);
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0, d.0, c.0, e.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 75.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
let faces = faces_at(&s, g, &[(75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the face under the unfilled path");
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [Paint::solid(red), Paint::None], "Make gave the far faces red and none");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 75.0, 25.0), v).unwrap();
}
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [green, Paint::None], "the triple-click matches the red the face was made with");
}
/// A triple-click whose first click adds paths to a selected Live Paint group and is released in a
/// face of that group matches the face's fill, not the edge around it.
#[test]
fn live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill() {
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [a] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 51.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone())]);
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(0.0, 0.0, 1.0));
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click merged the paths");
let faces = faces_at(&s, g, &[(25.0, 25.0), (225.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the group's face");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the face had");
}
/// When the first click merges two selected Live Paint groups, a face of the group in front takes
/// its source path's fill, so a triple-click there after a release across an edge matches that fill
/// and not the paint the face had before the merge.
#[test]
fn live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill() {
let mut s = session();
let back = live_squares(&mut s, &[0.0]);
let source = rect(&mut s, 100.0, 0.0, 50.0, 50.0);
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
let front = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let [f] = faces_at(&s, front, &[(125.0, 25.0)])[..] else { panic!("one face") };
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
paint_parts(&mut s, &[], &Paint::None, &[(f, blue.clone())]);
let (next, far) = (rect(&mut s, 150.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let [m] = faces_at(&s, merged, &[(125.0, 25.0)])[..] else { panic!("one face") };
assert_eq!(fill_of(&s, m), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "Merge gives the front group's face its source's fill");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 155.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 145.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(125.0, 25.0)).expect("the click merged the groups");
let faces = faces_at(&s, g, &[(125.0, 25.0), (325.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the front group's face");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 145.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the merge gave the face");
}
/// When the first click merges paths into a selected Live Paint group whose face has an unplaced
/// gradient, Merge fixes the gradient to the face's fit, so a triple-click there after a release
/// across an edge matches the fixed gradient: a far face whose source has that same fixed gradient
/// takes the bucket's paint.
#[test]
fn live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
paint_parts(&mut s, &[], &Paint::None, &[(f, gradient.clone())]);
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
s.execute("select.set", &json!({"ids": [g.0, next.0]})).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let [m] = faces_at(&s, merged, &[(25.0, 25.0)])[..] else { panic!("one face") };
let fixed = fill_of(&s, m);
assert_ne!(fixed, gradient, "Merge fixes the face's gradient to its fit");
s.execute("edit.undo", &json!({})).unwrap();
s.edit("t", |d, _| {
d.node_mut(far).unwrap().appearance.set_fill(fixed.clone());
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
let [far_face] = faces_at(&s, g, &[(225.0, 25.0)])[..] else { panic!("the far face") };
assert_eq!(fill_of(&s, far_face), fixed, "the far face keeps its source's fixed gradient");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, far_face), green, "the far face had the fixed gradient the merge gave the face");
}
/// When the first click merges a line that splits a painted face of the selected Live Paint group,
/// Merge keeps the face's paint in one part only and the other part takes its source path's fill;
/// a triple-click in that other part after a release across an edge matches the source's fill.
#[test]
fn live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill() {
let mut s = session();
let source = rect(&mut s, 0.0, 0.0, 50.0, 50.0);
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
paint_parts(&mut s, &[], &Paint::None, &[(f, Paint::solid(Color::rgb(0.0, 0.0, 1.0)))]);
let line = NodeId(s.execute("shape.line", &json!({"x1": 40, "y1": -10, "x2": 40, "y2": 60})).unwrap()["id"].as_u64().unwrap());
let next = rect(&mut s, 50.0, 0.0, 50.0, 50.0);
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
let (red_far, blue_far) = (rect(&mut s, 200.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
set_fill(&mut s, red_far, Color::rgb(1.0, 0.0, 0.0));
set_fill(&mut s, blue_far, Color::rgb(0.0, 0.0, 1.0));
let ids = json!({"ids": [g.0, line.0, next.0, red_far.0, blue_far.0]});
s.execute("select.set", &ids).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let parts = faces_at(&s, merged, &[(20.0, 25.0), (45.0, 25.0)]);
assert_eq!(
parts.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(),
[Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0))],
"Merge keeps the paint in the part that holds the face's inside point"
);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &ids).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
let far = faces_at(&s, g, &[(225.0, 25.0), (325.0, 25.0)]);
assert_eq!(far.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(), [green, Paint::solid(Color::rgb(0.0, 0.0, 1.0))]);
}
/// A triple-click whose first click makes the Live Paint group from the selected paths matches the
/// fill the face was made with.
#[test]
@@ -3978,6 +4238,116 @@ fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges(
assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black);
}
/// A double-click whose two clicks land on two joined edges paints every edge joined to them that
/// had their stroke: the edge the first click painted still joins the others.
#[test]
fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() {
// A square with a line across its middle, cut at x = 30 and x = 70 by two lines from the top: the
// middle line's three edges join end to end.
let mut s = session();
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
for anchors in [
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
] {
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
}
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
paint_parts(&mut s, &all, &red, &[]);
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
assert_eq!(middle.len(), 3, "the middle line's three edges");
paint_parts(&mut s, &middle, &black, &[]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
let shift = Mods { shift: true, ..Default::default() };
for (kind, x) in
[(PointerKind::Down, 50.0), (PointerKind::Up, 50.0), (PointerKind::Down, 85.0), (PointerKind::Up, 85.0), (PointerKind::DoubleClick, 85.0)]
{
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
// `through` takes edge ids, with scope "connected" only.
for p in [
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}),
json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}),
json!({"group": g.0, "point": [15, 50], "through": []}),
] {
assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}");
}
}
/// A double-click whose second press lands on the next joined edge and is released back on the
/// edge the first click painted (at the end of the line) matches that edge's stroke paint from
/// before the first click, and the edge the second press painted still joins the edge past it.
#[test]
fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges() {
let mut s = session();
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
for anchors in [
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
] {
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
}
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
paint_parts(&mut s, &all, &red, &[]);
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
assert_eq!(middle.len(), 3, "the middle line's three edges");
paint_parts(&mut s, &middle, &black, &[]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
let shift = Mods { shift: true, ..Default::default() };
for (kind, x) in
[(PointerKind::Down, 15.0), (PointerKind::Up, 15.0), (PointerKind::Down, 50.0), (PointerKind::Up, 15.0), (PointerKind::DoubleClick, 15.0)]
{
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
}
/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches
/// the fill the face had before the first click: the lent press counts as one that paints nothing.
#[test]
fn live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
let cmd = Mods { cmd: true, ..Default::default() };
for (kind, m) in [
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::Down, cmd),
(PointerKind::Up, cmd),
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::TripleClick, Mods::default()),
] {
s.pointer(&PointerEvent::new(kind, 25.0, 25.0).with_mods(m), v).unwrap();
}
assert_eq!(s.tool_id(), "livePaintBucket");
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope
/// that compares none, and a scope with a drag's points are refused; nothing changes.
#[test]
+71
View File
@@ -188,6 +188,77 @@ fn align_stroke_reaches_the_characters_stroke() {
assert!(aligns.contains(&StrokeAlign::Inside) && aligns.contains(&StrokeAlign::Outside), "{aligns:?}");
}
/// The bounds of type `t`'s glyph outlines in text space.
fn glyph_bounds(t: &TextObject) -> kurbo::Rect {
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let mut all = kurbo::BezPath::new();
for g in &lay.glyphs {
all.extend(g.outline.iter());
}
kurbo::Shape::bounding_box(&all)
}
/// Create Outlines on type scaled 300% across and 100% down: the canvas strokes the characters in
/// text space and then scales them, so the outlined stroke is filled art three times as thick
/// across upright stems as across level bars, not a live stroke of one mean weight.
#[test]
fn create_outlines_keeps_the_character_strokes_thickness_under_an_uneven_scale() {
let mut s = session();
let id = stroked_text(&mut s);
run(&mut s, "stroke.set", json!({"weight": 4, "join": "round", "cap": "round"}));
run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 300, "sy": 100}));
let t = text(&s, id);
let [a, b, c, d, ..] = t.xf.as_coeffs();
assert!((a - 3.0).abs() < 1e-9 && b.abs() < 1e-9 && c.abs() < 1e-9 && (d - 1.0).abs() < 1e-9, "{:?}", t.xf);
let w = t.runs[0].style.stroke_width;
let gb = glyph_bounds(&t);
run(&mut s, "select.set", json!({ "ids": [id.0] }));
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
let doc = &s.doc().unwrap().doc;
let group = doc.node(NodeId(g)).unwrap();
let mut strokes: Option<kurbo::Rect> = None;
for c in group.children().unwrap() {
assert!(c.appearance.stroke().is_none(), "no live stroke of one weight is left");
if c.appearance.fill_paint() == Paint::solid(Color::rgb8(255, 0, 0)) {
let cb = c.geometric_bounds().unwrap();
strokes = Some(strokes.map_or(cb, |s| s.union(cb)));
}
}
// Round joins and caps reach half the weight past the glyphs in text space, then scale.
let want = t.xf.transform_rect_bbox(gb.inflate(w / 2.0, w / 2.0));
let got = strokes.expect("filled character strokes");
assert!((got.width() - want.width()).abs() < 0.1 && (got.height() - want.height()).abs() < 0.1, "{got:?} for {want:?}");
assert!((got.height() - (gb.height() + w)).abs() < 0.1, "level bars keep the weight: {got:?}");
}
/// Under a uniform scale and a rotation the outlined characters keep a live stroke, its weight
/// and dashes scaled with them.
#[test]
fn create_outlines_keeps_a_live_character_stroke_under_a_uniform_scale_and_rotation() {
let mut s = session();
let id = stroked_text(&mut s);
run(&mut s, "stroke.set", json!({"weight": 4, "dash": [6, 2]}));
run(&mut s, "object.scale", json!({"ids": [id.0], "sx": 200, "sy": 200}));
run(&mut s, "object.rotate", json!({"angle": 30}));
let t = text(&s, id);
let k = t.xf.determinant().abs().sqrt();
assert!((k - 2.0).abs() < 1e-9, "{:?}", t.xf);
let st = t.runs[0].style.clone();
let dash = st.stroke_dash.as_ref().unwrap().pattern.clone();
let glyphs = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).glyphs.len();
run(&mut s, "select.set", json!({ "ids": [id.0] }));
let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap();
let doc = &s.doc().unwrap().doc;
let pieces = doc.node(NodeId(g)).unwrap().children().unwrap().to_vec();
assert_eq!(pieces.len(), glyphs, "one path for each glyph, no filled strokes");
for p in &pieces {
let ps = p.appearance.stroke().expect("a live stroke");
assert!((ps.width - st.stroke_width * k).abs() < 1e-6, "{} for {}", ps.width, st.stroke_width * k);
let got = &ps.dash.as_ref().unwrap().pattern;
assert!(got.iter().zip(&dash).all(|(g, d)| (g - d * k).abs() < 1e-6), "{got:?} for {dash:?}");
}
}
/// Copying type's appearance onto a path keeps its characters' stroke alignment (the Eyedropper's
/// own stroke attributes have none, on paths as on type).
#[test]
+62
View File
@@ -1034,6 +1034,68 @@ fn a_repainted_wedge_sets_its_label_color_when_pasted_without_formatting() {
assert_eq!(pasted, labels(&s, p), "copied as {before:?}");
}
/// Wedges linked to a global swatch that the destination document gives a dark color, merged on Paste without
/// Formatting, give their legend labels white characters, as a redraw does; added under a new name, they keep the
/// copied light color and black labels.
#[test]
fn wedges_merged_into_a_dark_swatch_give_white_labels_when_pasted_without_formatting() {
let csv = ",North,South\nP,1,1";
fn labels(s: &Session, id: NodeId) -> Vec<(String, Paint)> {
let mut out = vec![];
node(s, id).walk(&mut |n| {
if let NodeKind::Text(t) = &n.kind
&& ["North", "South"].contains(&t.plain_text().as_str())
{
out.push((t.plain_text(), t.first_style().fill.clone()));
}
});
out
}
let both = |c: Color| vec![("North".to_string(), Paint::solid(c)), ("South".to_string(), Paint::solid(c))];
for (conflict, expected) in [("merge", Color::WHITE), ("add", Color::BLACK)] {
let mut s = session();
let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap());
s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ffffff", "global": true})).unwrap();
let mut wedges = vec![];
node(&s, g).walk(&mut |m| {
if let NodeKind::Path { .. } = m.kind {
wedges.push(m.id.0);
}
});
s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Ink"})).unwrap();
s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap();
assert_eq!(labels(&s, g), both(Color::BLACK), "light wedges have black labels");
copy(&mut s, &[g]);
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap();
let p = ids_of(&s.execute("edit.pasteWithoutFormatting", &json!({"swatchConflict": conflict})).unwrap())[0];
let pasted = labels(&s, p);
assert_eq!(pasted, both(expected), "{conflict}");
s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap();
assert_eq!(pasted, labels(&s, p), "{conflict}: as a redraw sets them");
}
}
/// An object linked to a graphic style and to a swatch merged with the document's keeps its graphic style link when
/// pasted without formatting, and its color shows the document's swatch.
#[test]
fn a_merged_swatch_keeps_graphic_style_links_when_pasted_without_formatting() {
let mut s = session();
let r = swatched_rect(&mut s, "Ink", "#ffffff");
sel(&mut s, &[r]);
s.execute("graphicStyle.new", &json!({"name": "Sun"})).unwrap();
copy(&mut s, &[r]);
new_doc(&mut s);
s.execute("swatch.new", &json!({"name": "Ink", "color": "#000000", "global": true})).unwrap();
let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap();
assert_eq!(v["merged"], 1);
let p = ids_of(&v)[0];
let style = node(&s, p).extras().graphic_style.and_then(|id| doc(&s).graphic_style_by_id(id)).map(|g| g.name.clone());
assert_eq!(style.as_deref(), Some("Sun"));
assert_eq!(fill(&s, p), linked(hex("#000000"), "Ink", 1.0));
}
/// When one pie's wedge of a series is repainted and another pie's wedge of that series is not, each pasted legend label
/// takes the contrast of the wedge it is in.
#[test]
+22
View File
@@ -119,6 +119,28 @@ fn strokes_span_the_targets_too() {
assert!(ga.start.x < 0.0 && ga.end.x > 400.0, "the stroke's box, half its weight out: {ga:?}");
}
#[test]
fn a_lower_stroke_row_spans_the_box_that_row_paints() {
let mut s = session();
let a = rect(&mut s, 0.0, 50.0, 100.0, 100.0);
let b = rect(&mut s, 300.0, 50.0, 100.0, 100.0);
// [Fill, Stroke 40 pt, Stroke 1 pt] on both.
s.execute("appearance.addStroke", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("stroke.set", &json!({"ids": [a.0, b.0], "item": 1, "weight": 40})).unwrap();
for aligned in [false, true] {
s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "item": 1, "aligned": aligned, "gradient": black_to_white(), "span": "selection"}))
.unwrap();
for id in [a, b] {
let Paint::Gradient(g) = &s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_at(Some(1)).unwrap().paint else {
panic!("expected a gradient on stroke row 1")
};
// The 40 pt row reaches 20 pt past the union 0..400, not the 1 pt topmost stroke's 0.5 pt.
let geom = g.geom.expect("placed in document coordinates");
assert!(near(geom.start, Point::new(-20.0, 100.0)) && near(geom.end, Point::new(420.0, 100.0)), "aligned {aligned}, {id:?}: {geom:?}");
}
}
}
#[test]
fn the_new_art_default_stays_unplaced() {
let mut s = session();
+23
View File
@@ -717,6 +717,29 @@ fn type_reports_a_gradient_when_any_glyph_expands() {
assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient");
}
/// Type scaled unevenly outlines its characters' stroke as a filled path, so a gradient on that
/// stroke becomes a gradient fill: the query reports it, and Expand turns it into art.
#[test]
fn type_reports_a_stroke_gradient_its_uneven_scale_turns_into_a_fill() {
let mut s = session();
let t = run(&mut s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [t]}));
run(
&mut s,
"paint.setStroke",
json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [70, 100],
"stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}),
);
run(&mut s, "stroke.set", json!({"weight": 4}));
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!(info["gradient"], json!(false), "a live stroke's gradient is not a fill");
run(&mut s, "object.scale", json!({"ids": [t], "sx": 300, "sy": 100}));
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true)));
run(&mut s, "object.expand", json!({}));
assert_eq!(gradients_and_type(&s), (0, 0), "the filled strokes' gradients became art");
}
/// The same rule for type in the art of a symbol instance that Object expands. The symbol's art
/// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are
/// written with 0.002 pt runs (over a 0.2 pt vector).
+9
View File
@@ -255,6 +255,9 @@ impl Session {
}
// The Selection and Group Selection tools act on the instance whole.
self.select_whole_instance(id);
// The tool lent to does not see the press: it counts as a press elsewhere for the clicks a
// double-click or triple-click compares.
self.tool.press_elsewhere();
let lent = self.make_tool(id);
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
@@ -1086,6 +1089,12 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.hover_ended(cx));
}
/// A press on the canvas went to the view tools and not to the active tool
/// ([`vectorcraft_tools::Tool::press_elsewhere`]).
pub fn tool_press_elsewhere(&mut self) {
self.tool.press_elsewhere();
}
/// Whether the active tool's hover depends on what lies under a still pointer
/// ([`vectorcraft_tools::Tool::wants_rehover`]).
pub fn tool_wants_rehover(&self) -> bool {
+7
View File
@@ -993,6 +993,13 @@ fn structured_junk() {
("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})),
("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})),
("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})),
// Packaging Tools add-on.
("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})),
("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})),
("addon.packaging.setRole", json!({"role": "none", "overprint": null})),
("addon.packaging.roles", json!({"ids": [-1, 1e300]})),
("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})),
("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})),
// Smart Pen add-on.
("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})),
("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})),