Merge pull request #8923 from dotCooCoo/fix/library-pattern-color-copies

Swatch libraries: repeated adds reuse numbered colors, and tints link to a color of their kind
This commit is contained in:
BFlat
2026-11-22 10:45:30 +07:00
committed by GitHub
7 changed files with 1644 additions and 55 deletions
+8 -8
View File
@@ -20,7 +20,6 @@ use serde_json::{Map, Value, json};
use vectorcraft_color::{Color, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId, TextStyleDef};
use super::clipboard::SwatchChoices;
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, color_value, has_doc, ids_param, index_opt, ok, point_param, str_param};
use crate::Clipboard;
@@ -713,7 +712,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Use Library Item",
[],
None,
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
has_doc,
use_item
),
@@ -1353,12 +1352,13 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
if clip.nodes.is_empty() {
return Err(damaged());
}
let choices = SwatchChoices::default();
// The pattern's name in the document, worked out on a copy: nothing to add is no edit.
let mut probe = (*s.doc()?.doc).clone();
let imported = clip.import_into(&mut probe, &choices, false)?;
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str());
let target = renamed.unwrap_or(&name).to_string();
// The pattern's name in the document, worked out on a copy: nothing to add is no edit. A global
// or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings
// a library pattern's colors.
let current = s.doc()?.doc.clone();
let (choices, probe, imported) = super::patternlib::probe_import(&current, &doc, &name, &clip)?;
drop(current);
let target = super::patternlib::imported_name(&imported, &name);
let paint = vectorcraft_doc::pattern::pattern_paint(&target);
// A pattern the document holds without a swatch (an imported SVG's) gets one.
let has_swatch =
+88 -20
View File
@@ -85,15 +85,29 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
library_doc(b.id).filter(|d| d.pattern(pattern).is_some())
}
/// Swatches as (the swatch's name in a library, its name in a document).
pub(crate) type SwatchNames = Vec<(String, String)>;
/// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art
/// painted with it does: the same pattern there already is used, and a name another pattern or
/// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out.
/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out,
/// and the swatches `d` had that the art took under another name than its own, in the same form.
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
/// to Swatches adds such a color, so that the pattern keeps the library's colors.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> {
/// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors
/// merge instead when that reuses a pattern of `d` that keeping them would add again
/// ([`probe_import`]).
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> {
let gathered = gather(lib, name);
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?;
// Without a color to merge or a pattern to reuse, the document is not copied.
let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) {
let (_, probed, imported) = probe_import(d, lib, name, &gathered)?;
*d = probed;
imported
} else {
gathered.import_into(d, &SwatchChoices::add_all(), false)?
};
let from = |to: &str| {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
renamed.unwrap_or(to).to_string()
@@ -103,7 +117,14 @@ pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(St
.filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. }))
.map(|w| (from(&w.name), w.name.clone()))
.collect();
Ok((imported_name(&imported, name), added))
let reused = imported
.renamed
.iter()
.filter(|r| r["kind"] == "swatch")
.filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string())))
.filter(|(_, to)| had.contains(to))
.collect();
Ok((imported_name(&imported, name), added, reused))
}
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
@@ -112,17 +133,29 @@ fn gather(lib: &Document, name: &str) -> Clipboard {
Clipboard::gather(lib, vec![user])
}
/// The names in `lib` of the swatches that pattern `name` of `lib` brings with its art.
pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::HashSet<String> {
gather(lib, name).swatches.into_iter().map(|w| w.name).collect()
}
/// The names in `lib` of pattern `name` and of the patterns its art brings.
pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet<String> {
gather(lib, name).patterns.into_iter().map(|p| p.name).collect()
}
/// The name pattern `name` has in the document `imported` went into.
fn imported_name(imported: &Imported, name: &str) -> String {
pub(crate) fn imported_name(imported: &Imported, name: &str) -> String {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str());
renamed.unwrap_or(name).to_string()
}
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as
/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted
/// with, is imported into a copy of `d`, so that those resources are compared too.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
/// anything to `d` → its name in `d`, and the swatches of `d` that the art takes under another
/// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is
/// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it
/// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those
/// resources are compared too.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> {
let gathered = gather(lib, name);
let only_pattern = gathered.patterns.len() == 1
&& gathered.symbols.is_empty()
@@ -131,23 +164,58 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio
&& gathered.char_styles.is_empty()
&& gathered.para_styles.is_empty()
&& gathered.brushes.is_empty()
&& gathered.images.is_empty();
&& gathered.images.is_empty()
&& gathered.graph_designs.is_empty();
if only_pattern {
return existing_pattern(d, lib, name);
return existing_pattern(d, lib, name).map(|target| (target, vec![]));
}
// Importing reuses only a pattern under that name or a numbered copy of it with the same tile
// options and as many art objects; without one, the document is not copied.
let def = lib.pattern(name)?;
// Without a pattern to reuse, the document is not copied.
if !has_candidate(d, lib, name) {
return None;
}
let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?;
if imported.added != 0 {
return None;
}
let took = imported
.renamed
.iter()
.filter(|r| r["kind"] == "swatch")
.filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string())))
.filter(|(_, to)| d.swatches_iter().any(|w| w.name == *to))
.collect();
Some((imported_name(&imported, name), took))
}
/// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name
/// or a numbered copy of it with the same tile options and as many art objects.
pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool {
let Some(def) = lib.pattern(name) else { return false };
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let copy = |n: &str| {
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
};
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
return None;
d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def))
}
/// Import `gathered`, which paints with pattern `name` of `lib`, into a copy of `d` → the swatch
/// choices used, the copy and what the import did. A global or spot color whose name `d` gives
/// another color comes in under a free name (Add). Those colors merge instead when Add would add
/// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to
/// the document's own colors of those names, as pasting with Merge, or adding it from a library
/// before, leaves it.
pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> {
let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some();
let mut with_add = d.clone();
let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?;
if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) {
let mut merged = d.clone();
let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?;
if reused(&found) {
return Ok((SwatchChoices::default(), merged, found));
}
}
let mut probe = d.clone();
let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?;
(imported.added == 0).then(|| imported_name(&imported, name))
Ok((SwatchChoices::add_all(), with_add, added))
}
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
+469 -23
View File
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Swatches",
["Window", "Swatch Libraries"],
None,
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}",
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
has_doc,
add
),
@@ -1011,6 +1011,154 @@ fn free_in(taken: &mut HashSet<String>, base: &str) -> String {
name
}
/// [`free_in`] for a library swatch's copy: a numbered name also skips the names `reserved` says
/// the library's other swatches have, so that a later add finds the copy as this swatch's.
fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str) -> bool) -> String {
let name = if taken.contains(base) {
(2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n) && !reserved(n)).unwrap_or_else(|| base.to_string())
} else {
base.to_string()
};
taken.insert(name.clone());
name
}
/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered
/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own
/// swatches of those names, so that a color the art brings under a numbered name does not take one
/// of them. While the import runs, a placeholder swatch holds each such name the art does not
/// bring, and a copy of the library's color holds each one the art brings, which the art then
/// takes. The placeholders are removed before it returns, and so is a copy the art did not take;
/// a copy the art took is listed with the colors the import brought. Names of the patterns the
/// import brings are not held.
fn import_holding(
d: &mut vectorcraft_doc::Document,
src: &vectorcraft_doc::Document,
pattern: &str,
names: &HashMap<&str, &Swatch>,
) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> {
let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit()));
let taken = taken_names(d);
let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect();
free.sort_unstable();
let (mut held, mut copies): (Vec<Swatch>, Vec<Swatch>) = (vec![], vec![]);
if !free.is_empty() {
let brings = patternlib::brought_names(src, pattern);
let patterns = patternlib::brought_patterns(src, pattern);
for n in free.into_iter().filter(|n| !patterns.contains(*n)) {
if !brings.contains(n) {
held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false });
} else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) {
copies.push((*w).clone());
}
}
}
let start = d.swatches.len();
d.swatches.extend(held.iter().chain(&copies).cloned());
let imported = patternlib::import(d, src, pattern);
let used = |n: &str| {
imported
.as_ref()
.is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n))
};
let used: HashSet<String> = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect();
let mut i = 0;
d.swatches.retain(|w| {
i += 1;
let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint);
!(i > start && ours && !used.contains(&w.name))
});
let (target, mut colors, mut took) = imported?;
took.retain(|(from, _)| !used.contains(from));
colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n)));
Ok((target, colors, took))
}
/// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors
/// under the names `links` gives them, for each whose colors `links` names now. Those leave
/// `pending` and are returned.
fn settle<'a>(
d: &mut vectorcraft_doc::Document,
pending: &mut Vec<(String, &'a Swatch)>,
links: &HashMap<String, String>,
) -> Vec<(String, &'a Swatch)> {
let mut done = vec![];
pending.retain(|(name, w)| {
let all = all_linked(&w.paint, links);
if all {
done.push((name.clone(), *w));
}
!all
});
relink_in(d, &done, links);
done
}
/// Give the swatches of `d` that `list` names (document name, library swatch) the library swatch's
/// paint with its colors linked to the names `links` gives them, in one pass over the document's
/// swatches.
fn relink_in(d: &mut vectorcraft_doc::Document, list: &[(String, &Swatch)], links: &HashMap<String, String>) {
if list.is_empty() {
return;
}
let paints: HashMap<&str, Paint> = list.iter().map(|(name, w)| (name.as_str(), relinked(&w.paint, links))).collect();
for x in d.swatches_iter_mut() {
if let Some(paint) = paints.get(x.name.as_str()) {
x.paint = paint.clone();
}
}
}
/// Whether paint `a` shows what paint `b` shows: the same color, or the same gradient with the
/// colors its stops show, whichever swatches those colors link to.
fn shows(a: &Paint, b: &Paint) -> bool {
let unlinked = |p: &Paint| match p {
Paint::Gradient(g) => {
let mut g = g.clone();
g.swatch = None;
g.gradient.stops.iter_mut().for_each(|s| s.swatch = None);
Paint::Gradient(g)
}
other => other.clone(),
};
match (a.color(), b.color()) {
(Some(x), Some(y)) => x == y,
_ => unlinked(a) == unlinked(b),
}
}
/// The names of the swatches the colors of paint `p` link to: a tint's base color, or the colors
/// of a gradient's stops.
fn linked_names(p: &Paint) -> Vec<&str> {
match p {
Paint::Solid { swatch: Some(b), .. } => vec![b.as_str()],
Paint::Gradient(g) => g.gradient.stops.iter().filter_map(|s| s.swatch.as_deref()).collect(),
_ => vec![],
}
}
/// Paint `p` with each link to a swatch that `links` names changed to the name it maps to.
fn relinked(p: &Paint, links: &HashMap<String, String>) -> Paint {
let mut out = p.clone();
let swap = |name: &mut String| {
if let Some(to) = links.get(name.as_str()) {
*name = to.clone();
}
};
match &mut out {
Paint::Solid { swatch: Some(b), .. } => swap(b),
Paint::Gradient(g) => g.gradient.stops.iter_mut().filter_map(|s| s.swatch.as_mut()).for_each(swap),
_ => {}
}
out
}
/// Whether `links` names every swatch the colors of paint `p` link to, the built-in Registration
/// swatch aside (every document has it under its own name).
fn all_linked(p: &Paint, links: &HashMap<String, String>) -> bool {
linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n))
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.add";
let (info, lib) = library_param(s, p, C)?;
@@ -1030,34 +1178,207 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked
// up once so that a large palette takes linear time.
let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new();
// The document's numbered copies ("Ink 2") by the name they are numbered after, in order.
let mut copies: HashMap<&str, Vec<&Swatch>> = HashMap::new();
for w in d.swatches_iter() {
by_name.entry(w.name.as_str()).or_insert(w);
let std::collections::hash_map::Entry::Vacant(e) = by_name.entry(w.name.as_str()) else { continue };
e.insert(w);
if let Some((base, n)) = w.name.rsplit_once(' ')
&& !n.is_empty()
&& n.bytes().all(|b| b.is_ascii_digit())
{
copies.entry(base).or_default().push(w);
}
}
let there = |w: &Swatch| match (&w.paint, &patterns) {
(Paint::Pattern { pattern, .. }, Some(src)) => {
patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target))
}
_ => match by_name.get(w.name.as_str()) {
Some(x) => x.paint == w.paint,
None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint),
}
.then(|| w.name.clone()),
// The library's swatches by name (the first of a name wins), looked up once.
let mut lib_by_name: HashMap<&str, &Swatch> = HashMap::new();
for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) {
lib_by_name.entry(w.name.as_str()).or_insert(w);
}
let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect();
// A color whose name the document gives another color, or a color group, is the numbered copy
// of it that an earlier add or a pattern's art brought in, when that copy is the same color. A
// numbered copy whose name the library gives a swatch of the same paint stands for that swatch
// alone, as adding that swatch finds it under its own name. Paints are compared with their
// colors linked as `links` says ([`relinked`]).
let same_kind = |x: &Swatch, w: &Swatch| x.global == w.global && x.spot == w.spot;
// A color is the same swatch only as the same kind: a library global color is not the
// document's process color of the same name and paint, which a tint cannot link to.
let same_color_kind = |x: &Swatch, w: &Swatch| w.paint.color().is_none() || same_kind(x, w);
let numbered = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| {
let c = copies.get(w.name.as_str())?;
let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint && same_color_kind(x, l));
let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w));
found.map(|x| x.name.clone())
};
let unlinked = HashMap::new();
// Whether a library global or spot color that paint `p` links to has no place in `links`
// while the document gives its name another swatch, which such a link would find instead.
let misplaced = |p: &Paint, links: &HashMap<String, String>| {
linked_names(p)
.into_iter()
.any(|n| !links.contains_key(n) && by_name.contains_key(n) && lib_by_name.get(n).is_some_and(|b| b.global || b.spot))
};
let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect();
// The picked patterns the document already has, each probed once: library pattern name → its
// name in the document and the colors of the document its art takes under other names.
let mut present: HashMap<&str, Option<(String, patternlib::SwatchNames)>> = HashMap::new();
if let Some(src) = &patterns {
for (_, w) in &picked {
let Paint::Pattern { pattern, .. } = &w.paint else { continue };
present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern));
}
}
// Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors
// linked to swatches of the document → the library's global and spot colors to bring back,
// those this call picks included.
// `x` shows `w`'s paint with each color linked to: the name `links` gives it; its own name when
// that is the document's color of the library color's paint and kind; or, for a library color
// the document has under no name, that color's own name, which then comes in under it.
// Registration and colors the library does not have keep their names.
let fit = |x: &Swatch, w: &Swatch, links: &HashMap<String, String>| -> Option<Vec<String>> {
let (ours, theirs) = (linked_names(&w.paint), linked_names(&x.paint));
if ours.len() != theirs.len() {
return None;
}
let map: HashMap<String, String> = ours.iter().zip(&theirs).map(|(l, t)| (l.to_string(), t.to_string())).collect();
if relinked(&w.paint, &map) != x.paint {
return None;
}
let mut restore = vec![];
for (&l, &t) in ours.iter().zip(&theirs) {
let ok = match (links.get(l), lib_by_name.get(l).filter(|b| b.global || b.spot)) {
(Some(to), _) => to == t,
(None, None) => l == t,
(None, Some(b)) => match by_name.get(t) {
Some(y) => l == t && y.paint == b.paint && same_kind(y, b),
None if l == t && !group_names.contains(t) => {
restore.push(l.to_string());
true
}
None => false,
},
};
if !ok {
return None;
}
}
Some(restore)
};
// `paint` is `w`'s paint with the colors it links to as `links` has them in the document → the
// name of the document's swatch, and the library colors to bring back for it ([`fit`]).
let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| -> Option<(String, Vec<String>)> {
if let (Paint::Pattern { pattern, .. }, Some(_)) = (&w.paint, &patterns) {
let (target, _) = present.get(pattern.as_str())?.as_ref()?;
return library_pattern_swatch(d, w, target).map(|n| (n, vec![]));
}
if let Some(restore) = by_name.get(w.name.as_str()).filter(|x| same_color_kind(x, w)).and_then(|x| fit(x, w, links)) {
return Some((w.name.clone(), restore));
}
if misplaced(&w.paint, links) {
return None;
}
let found = match by_name.get(w.name.as_str()) {
Some(_) => numbered(w, paint, links),
None if group_names.contains(w.name.as_str()) => numbered(w, paint, links),
None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()),
};
// A numbered copy brings back the colors it links to that the document deleted, as a
// swatch of `w`'s own name does.
found.map(|n| {
let back = by_name.get(n.as_str()).and_then(|x| fit(x, w, links)).unwrap_or_default();
(n, back)
})
};
// The global or spot color of the document that library color `b` is: its own name, or the
// numbered copy of it that adding `b` would find. While no color or color group has its name,
// a numbered copy is looked for only when this call does not add `b` under its own name.
let base_in_doc = |b: &Swatch| match by_name.get(b.name.as_str()) {
Some(x) if x.paint == b.paint && same_kind(x, b) => Some(b.name.clone()),
Some(_) => numbered(b, &b.paint, &unlinked),
None if group_names.contains(b.name.as_str()) || !picked_names.contains(b.name.as_str()) => numbered(b, &b.paint, &unlinked),
None => None,
};
// The library's global and spot colors that the picked tints and gradients link to, with the
// name each has in the document: library name → document name. Each is looked up for itself,
// whether or not this call picks it, once.
let mut base_names: HashMap<String, String> = HashMap::new();
let mut looked_up: HashSet<&str> = HashSet::new();
for (_, w) in &picked {
for base in linked_names(&w.paint) {
if !looked_up.insert(base) {
continue;
}
if let Some(n) = lib_by_name.get(base).filter(|b| b.global || b.spot).and_then(|b| base_in_doc(b)) {
base_names.insert(base.to_string(), n);
}
}
}
// A color that the art of a picked pattern the document holds takes under another name (a
// numbered copy that the library also names) is the one the picked tints and gradients link
// to, as when the pattern came in, unless this call adds the color itself. The colors the art
// takes are those of an import into a copy of the document, which adds nothing.
if looked_up.iter().any(|n| !base_names.contains_key(*n)) {
for (_, w) in &picked {
let Paint::Pattern { pattern, .. } = &w.paint else { continue };
let Some(Some((_, took))) = present.get(pattern.as_str()) else { continue };
for (from, to) in took.iter().cloned() {
let fits = |b: &&Swatch| by_name.get(to.as_str()).is_some_and(|x| (x.global || x.spot) && x.paint == b.paint && same_kind(x, b));
if looked_up.contains(from.as_str()) && !picked_names.contains(from.as_str()) && lib_by_name.get(from.as_str()).is_some_and(fits) {
base_names.entry(from).or_insert(to);
}
}
}
}
// Library name → the name of the document's swatch.
let mut existing: Vec<(String, String)> = vec![];
let mut fresh = vec![];
// The library colors that the document's tints and gradients found here link to by name while
// the document has no swatch of that name (one deleted without unlinking them): they come back
// under their own names.
let mut restore: Vec<String> = vec![];
// Those that this call picks: they are added first, so that they keep their names, which the
// art of a pattern added before them could otherwise take.
let mut reserved: HashSet<String> = HashSet::new();
for &(group, w) in &picked {
match there(w) {
Some(name) => existing.push((w.name.clone(), name)),
// A tint or gradient is compared with its colors linked to the names they have here.
let paint = relinked(&w.paint, &base_names);
match there(w, &paint, &base_names) {
Some((name, back)) => {
existing.push((w.name.clone(), name));
for n in back {
if picked_names.contains(n.as_str()) {
reserved.insert(n);
} else if !restore.contains(&n) {
restore.push(n);
}
}
}
None => fresh.push((group, w)),
}
}
if !reserved.is_empty() {
let (first, rest): (Vec<_>, Vec<_>) = fresh.into_iter().partition(|(_, w)| reserved.contains(&w.name));
fresh = first;
fresh.extend(rest);
}
let undo_before = s.doc()?.history.undo.len();
// Library name → the name it got in the document.
let added: Vec<(String, String)> = if fresh.is_empty() {
// Library name → the name it got in the document. The colors the patterns brought that no
// library swatch of this call stands for are added too; they are listed after the others and
// are never the one `apply` paints with.
let mut brought_alone: Vec<(String, String)> = vec![];
// Library name → the name of the document's global or spot color for it, which the tints and
// gradients added here link to: one that is global or spot as the library color is.
let base_of = |l: &str, n: &str| {
let (Some(w), Some(x)) = (lib_by_name.get(l), by_name.get(n)) else { return false };
(x.global || x.spot) && same_kind(x, w)
};
let mut links: HashMap<String, String> = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect();
links.extend(base_names);
let added: Vec<(String, String)> = if fresh.is_empty() && restore.is_empty() {
vec![]
} else {
let (added, reused) = s.edit("Add to Swatches", |d, _| {
let (added, reused, brought) = s.edit("Add to Swatches", |d, _| {
let mut out = vec![];
// Library pattern swatches that stand for a swatch added earlier in this call.
let mut reused = vec![];
@@ -1069,13 +1390,81 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
// The swatches the patterns imported in this call brought with their art: (library
// name, document name).
let mut brought: Vec<(String, String)> = vec![];
// The colors to bring back come first, under their own names, which no swatch or color
// group of the document has; the tints and gradients added here link to them too.
for n in &restore {
let Some(b) = lib_by_name.get(n.as_str()) else { continue };
let name = free_in(&mut taken, &b.name);
d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() });
links.insert(n.clone(), name.clone());
brought.push((n.clone(), name));
}
// The swatches added here with a link `links` did not name yet: (document name, library
// swatch).
let mut pending: Vec<(String, &Swatch)> = vec![];
for (group, w) in fresh {
let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) {
// The pattern comes with its swatch; a pattern the document has without one
// gets one. The swatch a pattern that comes in brings is named after the pattern:
// it takes the library swatch's name and color group instead.
// The tints and gradients added so far link to their colors first, so that the
// pattern's art finds them. A color they wait for that the pattern's art brings
// is named by importing the pattern into a copy first.
let brings = if pending.is_empty() { Default::default() } else { patternlib::brought_names(src, pattern) };
let waited = |n: &&str| !links.contains_key(*n) && brings.contains(*n);
// A global or spot color the pattern brought, or took from the document under
// a numbered name: library name → document name. A color this call picks is
// added under its own name instead of the one the pattern took. A library global
// or spot color is only a document color of its paint and kind, as for `base_of`.
let colors_of = |d: &vectorcraft_doc::Document, colors: &[(String, String)], took: &[(String, String)]| {
let mut out: HashMap<String, String> = HashMap::new();
for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) {
let library = lib_by_name.get(from.as_str()).filter(|b| b.global || b.spot);
let fits = |x: &Swatch| (x.global || x.spot) && library.is_none_or(|b| x.paint == b.paint && same_kind(x, b));
if d.swatch(to).is_some_and(fits) {
out.entry(from.clone()).or_insert_with(|| to.clone());
}
}
out
};
// The names learned from the copy, which the import into the document confirms.
let mut learned = vec![];
if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) {
let mut probe = d.clone();
let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?;
for (from, to) in colors_of(&probe, &colors, &took) {
if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) {
e.insert(to);
learned.push(from);
}
}
}
let settled = settle(d, &mut pending, &links);
let had = taken_names(d);
let (target, colors) = patternlib::import(d, src, pattern)?;
let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?;
// Those colors are the ones the library's tints of them link to, unless the
// document already has one for them. A name the copy gave that the import
// into the document did not give is replaced, and the tints linked to it are
// linked again.
let mut found = colors_of(d, &colors, &took);
let mut changed = false;
for from in learned {
let real = found.remove(&from);
if real.as_ref() != links.get(&from) {
changed = true;
match real {
Some(to) => links.insert(from, to),
None => links.remove(&from),
};
}
}
for (from, to) in found {
links.entry(from).or_insert(to);
}
if changed {
relink_in(d, &settled, &links);
pending.extend(settled.into_iter().filter(|(_, w)| !all_linked(&w.paint, &links)));
}
brought.extend(colors);
if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) {
reused.push((w.name.clone(), name));
@@ -1101,8 +1490,29 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
(name.clone(), Swatch { name, paint, global: false, spot: false })
} else {
// A color a pattern added earlier in this call brought with its art is that
// swatch: it moves to the library swatch's place.
let at = brought.iter().position(|(from, _)| *from == w.name);
// swatch when it shows the library swatch's color: it moves to the library
// swatch's place, when its colors link where the library swatch's do: to the
// names `links` gives them, not elsewhere for a color this call has yet to add,
// and otherwise to a color of the library color's paint and process, global or spot kind,
// or under the same name when the library has no such swatch (Registration).
let fits = |x: &Paint| {
let (ours, theirs) = (linked_names(&w.paint), linked_names(x));
ours.len() == theirs.len()
&& ours.iter().zip(&theirs).all(|(l, t)| match links.get(*l) {
Some(to) => to == t,
None => {
!picked_names.contains(l)
&& match lib_by_name.get(*l) {
Some(b) => d.swatch(t).is_some_and(|x| x.paint == b.paint && same_kind(x, b)),
None => l == t,
}
}
})
};
let same = |to: &str| {
d.swatch(to).is_some_and(|x| shows(&x.paint, &w.paint) && x.global == w.global && x.spot == w.spot && fits(&x.paint))
};
let at = brought.iter().position(|(from, to)| *from == w.name && same(to));
let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| {
let i = d.swatches.iter().position(|x| x.name == n)?;
Some(d.swatches.remove(i))
@@ -1110,11 +1520,23 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
match moved {
Some(sw) => (sw.name.clone(), sw),
None => {
let name = free_in(&mut taken, &w.name);
(name.clone(), Swatch { name, ..(*w).clone() })
// A numbered copy skips the names of the library's other swatches,
// which a later add looks up as theirs.
let name = free_copy_in(&mut taken, &w.name, |n| lib_by_name.contains_key(n));
// A tint or gradient links to its colors under the names they have in
// the document; a color that comes in later in this call is linked
// when it has come in.
let paint = relinked(&w.paint, &links);
if !all_linked(&w.paint, &links) {
pending.push((name.clone(), w));
}
(name.clone(), Swatch { name, paint, ..(*w).clone() })
}
}
};
if sw.global || sw.spot {
links.insert(w.name.clone(), name.clone());
}
match group {
Some(g) => {
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
@@ -1135,13 +1557,37 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
out.push((w.name.clone(), name));
}
Ok((out, reused))
// A library global or spot color that a tint or gradient added here links to, which the
// document does not have and nothing in this call brought, comes in with it, as pasting
// art painted with the tint brings its color. It is listed with the colors patterns
// brought.
let mut wanted: Vec<&str> = vec![];
let mut seen: HashSet<&str> = HashSet::new();
for (_, w) in &pending {
for n in linked_names(&w.paint) {
if n != REGISTRATION && !links.contains_key(n) && seen.insert(n) {
wanted.push(n);
}
}
}
for n in wanted {
let Some(b) = lib_by_name.get(n).filter(|b| b.global || b.spot) else { continue };
let name = free_copy_in(&mut taken, &b.name, |x| lib_by_name.contains_key(x));
d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() });
links.insert(n.to_string(), name.clone());
brought.push((n.to_string(), name));
}
relink_in(d, &pending, &links);
Ok((out, reused, brought))
})?;
existing.extend(reused);
brought_alone = brought;
added
};
let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>();
let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)});
let mut added_names = names(&added);
added_names.extend(names(&brought_alone));
let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)});
if let (Some(cmd), Some((_, first))) = (apply, picked.first()) {
let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone());
s.execute(cmd, &json!({"swatch": name, "focus": focus}))?;
+86
View File
@@ -456,6 +456,92 @@ fn a_pattern_item_adds_the_swatch_of_a_pattern_the_document_holds_without_one()
assert!(!s.doc().unwrap().doc.swatches_iter().any(is_dots), "undone with the paint");
}
/// A pattern item whose art links to a global color that the document has under the same name in
/// another color keeps the item's color: the color comes in under a numbered name and the pattern
/// links to it. Used again, the pattern and that color are reused. A document whose pattern of
/// that name links to the document's own color (as pasting with Merge leaves it) reuses that one.
#[test]
fn a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color() {
let mut s = session();
let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
make_pattern(&mut s, &dot, "Dots");
let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]}));
run(&mut s, "select.set", json!({"ids": [a]}));
run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"}));
run(&mut s, "edit.copy", json!({}));
let names = |s: &Session, base: &str| -> Vec<String> {
let d = &s.doc().unwrap().doc;
d.swatches_iter().filter(|w| w.name.starts_with(base)).map(|w| w.name.clone()).collect()
};
let art_link = |s: &Session, pattern: &str| match s.doc().unwrap().doc.pattern(pattern).unwrap().art[0].appearance.fill_paint() {
vectorcraft_color::Paint::Solid { swatch, color, .. } => (swatch, color.to_hex()),
p => panic!("the pattern's art is not filled with a color: {p:?}"),
};
// A document whose Ink is red.
let red_ink = |s: &mut Session| {
run(s, "file.new", json!({"width": 300, "height": 300}));
run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let b = run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone();
run(s, "select.set", json!({"ids": [b]}));
};
red_ink(&mut s);
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"}));
assert_eq!(r["pattern"], "Dots", "{r}");
assert_eq!(art_link(&s, "Dots"), (Some("Ink 2".to_string()), "#0000ff".to_string()));
assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"]);
run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots", "to": "stroke"}));
assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused");
assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"], "the color is reused");
// Pasted with Merge, the pattern links to the document's red Ink.
red_ink(&mut s);
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
assert_eq!(art_link(&s, "Dots"), (Some("Ink".to_string()), "#ff0000".to_string()));
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"}));
assert_eq!(r["pattern"], "Dots", "{r}");
assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused");
assert_eq!(names(&s, "Ink"), ["Ink"]);
}
/// A pattern pasted with Merge whose art uses a tint of a global color is reused by its pattern
/// item after the tint swatch is deleted: the tint swatch comes back and no copy of the pattern is
/// added.
#[test]
fn a_merged_pattern_whose_tint_swatch_was_deleted_is_reused() {
let mut s = session();
let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]}));
make_pattern(&mut s, &dot, "Dots");
let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]}));
run(&mut s, "select.set", json!({"ids": [a]}));
run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 300, "height": 300}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
let tints: Vec<String> =
s.doc().unwrap().doc.swatches_iter().filter(|w| w.name != "Ink" && w.name.starts_with("Ink")).map(|w| w.name.clone()).collect();
assert_eq!(tints.len(), 1, "the tint swatch comes with the paste: {tints:?}");
run(&mut s, "swatch.delete", json!({"names": tints, "unlink": false}));
let b = run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [b]}));
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"}));
assert_eq!(r["pattern"], "Dots", "{r}");
assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused");
let restored = s.doc().unwrap().doc.swatch(&tints[0]).map(|w| w.paint.clone());
assert!(
matches!(&restored, Some(vectorcraft_color::Paint::Solid { swatch: Some(base), tint, .. }) if base == "Ink" && (*tint - 0.5).abs() < 1e-6),
"the tint swatch comes back as a tint of the document's Ink: {restored:?}"
);
}
/// Gradients and patterns go out to a library file and come back; read from a file, a gradient
/// with too few stops is dropped, one out of range is put in range, and a pattern whose data is
/// damaged or doesn't hold its pattern fails cleanly when used.
+972
View File
@@ -516,6 +516,978 @@ fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_a
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}");
}
/// A library with pattern swatch `Tiles`, whose pattern `Squares` is filled with global color
/// `Ink` (#0000ff), loaded into `s`, which is then left in a new document whose own global `Ink`
/// is #ff0000 → the library's id. The library document's square painted with `Tiles` is on the
/// clipboard.
fn squares_library_and_a_red_ink(s: &mut Session) -> Value {
use std::sync::Arc;
use vectorcraft_doc::pattern::pattern_paint;
run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
s.edit("Pattern", |d, _| {
let ink = Paint::Solid { color: Color::rgb8(0, 0, 0xff), swatch: Some("Ink".into()), tint: 1.0 };
let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0));
let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0));
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) });
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false });
Ok(())
})
.unwrap();
let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
let r = run(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(s, "select.set", json!({"ids": [r]}));
run(s, "edit.copy", json!({}));
run(s, "file.new", json!({"width": 100, "height": 100}));
run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
id
}
/// The names of the swatches of `s`'s document that are `base` or a numbered copy of it.
fn named_after(s: &Session, base: &str) -> Vec<String> {
let copy = |n: &str| n == base || n.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| r.bytes().all(|b| b.is_ascii_digit()));
doc(s).swatches_iter().filter(|w| copy(&w.name)).map(|w| w.name.clone()).collect()
}
/// A library color that the document has as a numbered copy of the same color ("Ink 2", brought by
/// the pattern added with it before) is that copy: adding the pattern and the color again adds
/// nothing.
#[test]
fn adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color() {
let mut s = session();
let id = squares_library_and_a_red_ink(&mut s);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]}));
assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", "Ink 2"])), "{again}");
assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]);
}
/// The colors a library pattern brings with its art are listed with the swatches added, the
/// numbered ones included, when the call adds the pattern swatch alone.
#[test]
fn the_colors_a_library_pattern_brings_are_listed_as_added() {
let mut s = session();
let id = squares_library_and_a_red_ink(&mut s);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]);
assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}");
}
/// A library pattern that is already in the document with its art linked to the document's own
/// color of that name (as pasting with Merge leaves it) is that pattern: adding its swatch adds no
/// numbered copy of the pattern or of the color.
#[test]
fn a_library_pattern_linked_to_the_documents_own_color_is_not_added_again() {
let mut s = session();
let id = squares_library_and_a_red_ink(&mut s);
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Squares"]);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Squares"], "{r}");
assert_eq!(named_after(&s, "Ink"), ["Ink"], "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}");
}
/// With `apply`, the color picked first is the one applied, even when a pattern added in the same
/// call brings a numbered copy of its name.
#[test]
fn apply_paints_with_the_picked_color_not_one_a_pattern_brought() {
let mut s = session();
let id = squares_library_and_a_red_ink(&mut s);
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
// The document's Ink is the library's color as a process color.
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"}));
assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"], "{r}");
// The picked global color is not the process one: it comes in numbered, and the pattern's art
// takes it.
assert_eq!(r["applied"], "Ink 2", "{r}");
assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}");
// A picked color the document already has is applied, not the pattern added after it.
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"}));
assert_eq!((&r["existing"], &r["applied"]), (&json!(["Ink"]), &json!("Ink")), "{r}");
}
/// A numbered copy that another swatch of the same name hides (the document finds the first of a
/// name) is not taken for a library color, even when it has that color.
#[test]
fn a_hidden_numbered_copy_is_not_taken_for_a_library_color() {
let mut s = session();
let id = squares_library_and_a_red_ink(&mut s);
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.newGroup", json!({"name": "Blues", "swatches": ["Ink 2"]}));
s.edit("Green", |d, _| {
let green = Paint::Solid { color: Color::rgb8(0, 0xff, 0), swatch: None, tint: 1.0 };
d.swatches.push(vectorcraft_color::Swatch { name: "Ink 2".into(), paint: green, global: true, spot: false });
Ok(())
})
.unwrap();
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
assert_eq!(r["existing"], json!([]), "{r}");
let name = r["added"][0].as_str().unwrap_or_default().to_string();
let blue = doc(&s).swatch(&name).and_then(|w| w.paint.color()).map(|c| c.to_hex());
assert_eq!(blue.as_deref(), Some("#0000ff"), "{r}");
}
/// The global color the swatch `name` of `s`'s document is a tint of.
fn tint_base(s: &Session, name: &str) -> Option<String> {
match doc(s).swatch(name).map(|w| &w.paint) {
Some(Paint::Solid { swatch, .. }) => swatch.clone(),
_ => None,
}
}
/// A library with global color `Ink` (#0000ff) and its tint `Ink half` loaded into `s`, which is
/// then left in a new document whose own global `Ink` is #ff0000 → the library's id.
fn tinted_ink_library_and_a_red_ink(s: &mut Session) -> Value {
run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(s, "file.new", json!({"width": 100, "height": 100}));
run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
id
}
/// A library tint added with its global color, which comes in under a numbered name, is a tint of
/// that numbered color, not of the document's own color of the library color's name.
#[test]
fn a_library_tint_follows_its_color_to_its_numbered_name() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
assert_eq!(r["added"], json!(["Ink 2", "Ink half"]), "{r}");
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 2", "Ink half"])), "{again}");
}
/// A library tint picked before its global color still follows the color to its numbered name.
#[test]
fn a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]}));
assert_eq!(r["added"], json!(["Ink half", "Ink 2"]), "{r}");
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half", "Ink 2"])), "{again}");
}
/// A library tint added without its global color finds the numbered copy an earlier add brought.
#[test]
fn a_library_tint_added_alone_finds_its_colors_numbered_copy() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!(r["added"], json!(["Ink half"]), "{r}");
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}");
}
/// A library tint added alone links to the numbered copy of its own color, not to another library
/// color's copy of the same paint.
#[test]
fn a_library_tint_added_alone_skips_another_library_colors_copy() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]}));
assert_eq!(r["added"], json!(["Ink 3"]), "{r}");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 3"), "{r}");
}
/// A library tint added alone finds its color's numbered copy when a color group of the document
/// has the color's name.
#[test]
fn a_library_tint_finds_its_colors_copy_beside_a_group_of_its_name() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
run(&mut s, "swatch.newGroup", json!({"name": "Ink", "colors": ["#123456"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
assert_eq!(r["added"], json!(["Ink 2"]), "{r}");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
}
/// A library pattern whose art uses a tint of a library color added earlier in the same call
/// does not bring a second copy of that tint, also when the call does not pick the color.
#[test]
fn a_pattern_after_its_tint_in_one_call_does_not_copy_the_tint() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
for names in [json!(["Ink", "Ink half", "Squares"]), json!(["Ink half", "Ink", "Squares"]), json!(["Ink half", "Squares"])] {
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {r}");
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}");
}
}
/// A library color added under a numbered name skips the names of the library's other swatches,
/// so adding it again finds that copy.
#[test]
fn a_library_colors_copy_skips_the_librarys_other_names() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
assert_eq!(r["added"], json!(["Ink 3"]), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 3"])), "{again}");
}
/// A library tint links to a global color even when the document has a process color of the same
/// name and paint, which the picked library color matches: the pattern's art brings the global one.
#[test]
fn a_library_tint_links_to_the_global_color_a_pattern_brought() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink", "Ink half", "Tiles"])] {
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
let base = tint_base(&s, "Ink half").unwrap_or_default();
assert!(doc(&s).swatch(&base).is_some_and(|w| w.global), "{names}: {r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}");
}
}
/// A library tint added with a pattern whose art brought the tint's global color under a numbered
/// name is a tint of that numbered color.
#[test]
fn a_library_tint_follows_the_color_a_pattern_brought() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Ink 2"))), "{r}");
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}");
}
/// A numbered copy of a color's name that the library also has as a swatch of its own stands for
/// that swatch alone, even when both library swatches have its color.
#[test]
fn a_numbered_copy_the_library_also_names_is_not_shared() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}");
}
/// A tint of the document whose global color was deleted without unlinking it is the library's
/// tint only with that color: adding the tint brings the color back under its name, listed as
/// added, and the tint links to it again.
#[test]
fn a_library_tint_whose_color_the_document_deleted_brings_the_color_back() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false}));
assert!(doc(&s).swatch("Ink").is_none());
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half"])), "{r}");
assert!(is_global(&s, "Ink", "#0000ff"), "{r}");
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}");
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}");
}
/// A numbered tint of the document whose global color was deleted without unlinking it is the
/// library's tint only with that color: adding the tint brings the color back under its name.
#[test]
fn a_numbered_tint_whose_color_the_document_deleted_brings_the_color_back() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "color": "#00ff00"}));
run(&mut s, "swatch.new", json!({"name": "Ink half 2", "swatch": "Ink", "tint": 50}));
run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half 2"])), "{r}");
assert!(is_global(&s, "Ink", "#0000ff"), "{r}");
assert_eq!(tint_base(&s, "Ink half 2").as_deref(), Some("Ink"), "{r}");
}
/// A deleted color that a document tint found here links to keeps its name when the call also
/// picks it, so a pattern added earlier in the call whose art brings another color of a taken
/// name does not take that name first.
#[test]
fn a_deleted_color_a_found_tint_links_to_keeps_its_name_beside_a_pattern() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50}));
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink 2 half", "Ink 2"]}));
assert!(r["existing"].as_array().is_some_and(|a| a.contains(&json!("Ink 2 half"))), "{r}");
assert_eq!(tint_base(&s, "Ink 2 half").as_deref(), Some("Ink 2"), "{r}");
assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}");
let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint();
let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") };
let green = swatch.clone().unwrap_or_default();
assert!(is_global(&s, &green, "#00ff00"), "{r}");
}
/// A library tint added with a pattern whose art took a numbered copy that the library also names
/// is found again on the next add: the tint links to the copy the art took, and adding the pattern
/// and the tint again adds nothing.
#[test]
fn a_library_tint_linked_to_the_copy_a_pattern_took_is_found_again() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
let base = tint_base(&s, "Ink half").unwrap_or_default();
assert!(is_global(&s, &base, "#0000ff"), "{r}");
// The pattern's art and the tint link to the same color.
let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint();
let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") };
assert_eq!(swatch.as_deref(), Some(base.as_str()), "{r}");
let swatches = doc(&s).swatches_iter().count();
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
assert_eq!(again["added"], json!([]), "{again}");
assert_eq!(doc(&s).swatches_iter().count(), swatches, "{again}");
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{again}");
assert_eq!(tint_base(&s, "Ink half"), Some(base), "{again}");
}
/// Without a pattern whose art takes it, a numbered copy that the library also names stands for
/// that library swatch alone: the document's tint linked to it is not the library's tint of the
/// color the copy is numbered after.
#[test]
fn a_tint_linked_to_a_copy_the_library_names_is_not_another_colors_tint() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink 2", "tint": 50}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!(r["existing"], json!([]), "{r}");
let added = r["added"][0].as_str().unwrap_or_default().to_string();
let base = tint_base(&s, &added).unwrap_or_default();
assert!(base != "Ink 2" && is_global(&s, &base, "#0000ff"), "{r}");
}
/// A numbered copy of a color's name that the library also has as a swatch of another color is
/// still the copy of the color: adding the color to a document that has such a copy (as a pattern
/// added by an earlier version left it) adds no other copy.
#[test]
fn a_numbered_copy_named_like_another_library_color_is_found() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{r}");
}
/// A library tint picked before its global color links to the color under the name it comes in
/// with, not to a numbered copy of the same color when the document has none of the color's name.
#[test]
fn a_library_tint_links_to_its_color_under_the_name_it_comes_in_with() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
for names in [json!(["Ink half", "Ink"]), json!(["Ink", "Ink half"])] {
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{names}: {r}");
run(&mut s, "swatch.delete", json!({"names": ["Ink half", "Ink"]}));
}
}
/// A library tint of a spot color links to the spot color a pattern's art brought, not to the
/// document's global process color of the same name and paint.
#[test]
fn a_library_spot_tint_links_to_the_spot_color_not_a_process_one() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] {
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
let base = tint_base(&s, "Ink half").unwrap_or_default();
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}");
}
}
/// The library's process color of a numbered name is not the document's global color of that name
/// and paint, so that global color is the numbered copy of the library's global color it is named
/// after.
#[test]
fn a_numbered_process_color_of_the_library_is_not_the_documents_global_copy() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff"}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 2 2"]), &json!(["Ink 2"])), "{r}");
}
/// A library tint added with a pattern whose art took the document's numbered copy of the tint's
/// color is a tint of that copy.
#[test]
fn a_library_tint_follows_the_numbered_color_a_pattern_took() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
for names in [json!(["Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] {
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
assert_eq!(named_after(&s, "Ink"), ["Ink 2"], "{names}: {r}");
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}");
}
}
/// A numbered copy that the library's own tint of that name is, once its color is linked as the
/// document has it, is not also taken for the library tint it is numbered after.
#[test]
fn a_numbered_tint_the_library_has_is_not_shared() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Half", "swatch": "Ink", "tint": 50}));
run(&mut s, "swatch.new", json!({"name": "Half 2", "swatch": "Ink", "tint": 50}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Half", "color": "#00ff00"}));
run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Half 2"]}));
assert_eq!(tint_base(&s, "Half 2").as_deref(), Some("Ink 2"));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Half", "Half 2"]}));
assert_eq!(r["existing"], json!(["Half 2"]), "{r}");
assert_eq!(r["added"].as_array().map(Vec::len), Some(1), "{r}");
}
/// The document's swatch `name` is a global color showing `hex`.
fn is_global(s: &Session, name: &str, hex: &str) -> bool {
doc(s).swatch(name).is_some_and(|w| w.global && w.paint.color().is_some_and(|c| c.to_hex() == hex))
}
/// A library inks library (global `Ink` #0000ff and its tint `Ink half`) loaded into `s`, which is
/// then left in a new document whose own `Ink` is the same blue as a process color → the id.
fn tinted_ink_library_and_a_process_ink(s: &mut Session) -> Value {
let id = tinted_ink_library_and_a_red_ink(s);
run(s, "swatch.delete", json!({"names": ["Ink"]}));
run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
id
}
/// A library global color is not the document's process color of the same name and paint: it
/// comes in numbered, its tint links to it, and adding the two again adds nothing.
#[test]
fn a_library_tint_of_a_color_the_document_has_as_process_is_added_once() {
let mut s = session();
let id = tinted_ink_library_and_a_process_ink(&mut s);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
let base = tint_base(&s, "Ink half").unwrap_or_default();
assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "{r}");
let before = (named_after(&s, "Ink"), named_after(&s, "Ink half"));
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]}));
assert_eq!(again["added"], json!([]), "{again}");
assert_eq!((named_after(&s, "Ink"), named_after(&s, "Ink half")), before, "{r} then {again}");
}
/// A library tint added without its global color, in a document whose swatch of the color's name
/// is another color or a process color, brings its color along and links to it, not to the
/// document's swatch; adding the tint again adds nothing.
#[test]
fn a_library_tint_added_alone_brings_its_color_beside_a_namesake() {
for process in [false, true] {
let mut s = session();
let id = if process { tinted_ink_library_and_a_process_ink(&mut s) } else { tinted_ink_library_and_a_red_ink(&mut s) };
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
let base = tint_base(&s, "Ink half").unwrap_or_default();
assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "process {process}: {r}");
assert_eq!(r["added"], json!(["Ink half", base]), "process {process}: {r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "process {process}: {again}");
}
}
/// A library tint of a spot color is not the document's tint of the same name and paint whose
/// color is a global process color: adding it alone brings the spot color and a tint of it.
#[test]
fn a_library_spot_tint_is_not_the_documents_tint_of_a_process_namesake() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
let tint = r["added"][0].as_str().unwrap_or_default().to_string();
let base = tint_base(&s, &tint).unwrap_or_default();
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!([tint])), "{again}");
}
/// A tint of a process namesake that a pattern's art brings is not taken for a picked library
/// tint of a spot color.
#[test]
fn a_library_spot_tint_is_not_a_process_tint_a_pattern_brought() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink half", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
let tints: Vec<String> = doc(&s).swatches_iter().filter(|w| w.name.starts_with("Ink half")).map(|w| w.name.clone()).collect();
if !tints.is_empty() {
run(&mut s, "swatch.delete", json!({"names": tints}));
}
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]}));
let picked = r["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink half"))).unwrap_or_default();
let base = tint_base(&s, picked).unwrap_or_default();
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}");
}
/// A library tint of a spot color added with a pattern whose art the document holds linked to its
/// process color of the spot color's name and paint (as pasting with Merge leaves it) links to a
/// spot color, not to that process color, in either pick order.
#[test]
fn a_library_spot_tint_is_not_linked_to_the_process_color_a_merged_pattern_takes() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
for names in [json!(["Ink half", "Tiles"]), json!(["Tiles", "Ink half"])] {
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
// The paste merged the spot color into the document's process color of its name.
assert_eq!(named_after(&s, "Ink"), ["Ink"], "{names}");
assert!(doc(&s).swatch("Ink").is_some_and(|w| w.global && !w.spot), "{names}");
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
let base = tint_base(&s, "Ink half").unwrap_or_default();
assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}");
}
}
/// A color a library pattern's art brings under a numbered name does not take a name the library
/// gives another swatch: adding that swatch next adds it under its own name, and adding the two
/// again adds nothing.
#[test]
fn a_color_a_pattern_brings_skips_the_librarys_numbered_names() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let brought =
first["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink"))).unwrap_or_default().to_string();
assert!(brought != "Ink 2" && is_global(&s, &brought, "#0000ff"), "{first}");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
assert_eq!(r["added"], json!(["Ink 2"]), "{r}");
assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", brought, "Ink 2"])), "{again}");
}
/// A pattern whose art brings both a color and the library's numbered color of the same name keeps
/// the numbered color under its own name, and the other color takes the next free one.
#[test]
fn a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone();
let green = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]}));
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [green]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, green]}));
run(&mut s, "select.set", json!({"ids": [blue, green]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}");
assert!(named_after(&s, "Ink").iter().any(|n| n != "Ink" && n != "Ink 2" && is_global(&s, n, "#0000ff")), "{r}");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]}));
assert_eq!(again["added"], json!([]), "{again}");
}
/// A library pattern with a numbered name comes in under that name when the document does not use
/// it.
#[test]
fn a_numbered_library_pattern_keeps_its_name() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Tiles 2"))), "{r}");
assert!(doc(&s).pattern("Tiles 2").is_some(), "{r}");
}
/// A color a library pattern's art brings does not change art of the document that is still
/// linked to a deleted color of a numbered name the library uses.
#[test]
fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#ffff00", "global": true}));
let box_id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [box_id]}));
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let fill = doc(&s).node(vectorcraft_doc::NodeId(box_id.as_u64().unwrap())).unwrap().appearance.fill_paint();
let Paint::Solid { swatch, .. } = &fill else { panic!("the box is filled with a color: {fill:?}") };
assert_eq!(swatch.as_deref(), Some("Ink 2"), "{r}");
assert!(doc(&s).swatch("Ink 2").is_none(), "{r}");
}
/// A library tint added without its global color to a document that has no swatch of the color's
/// name brings the color along under its own name.
#[test]
fn a_library_tint_added_alone_brings_its_missing_color() {
let mut s = session();
let id = tinted_ink_library_and_a_red_ink(&mut s);
run(&mut s, "swatch.delete", json!({"names": ["Ink"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]}));
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}");
assert!(is_global(&s, "Ink", "#0000ff"), "{r}");
}
/// A library tint added with a pattern the document already has (pasted with Merge, so it brings
/// no colors), through the pattern's own swatch or another library swatch of it, is added once,
/// however often the two are added.
#[test]
fn a_library_tint_with_a_pattern_the_document_has_is_added_once() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
s.edit("Dots", |d, _| {
let paint = vectorcraft_doc::pattern::pattern_paint("Squares");
d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false });
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink half"]}));
let before = named_after(&s, "Ink half");
for pattern in ["Squares", "Dots"] {
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": [pattern, "Ink half"]}));
assert_eq!(named_after(&s, "Ink half"), before, "{pattern}: {first} then {again}");
}
}
/// A library gradient whose stops link to a color and to the Registration swatch, picked before or
/// after a pattern whose art brings the color under a numbered name, is not added a second time.
#[test]
fn a_gradient_with_a_registration_stop_before_its_pattern_is_not_copied() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "[Registration]"}]});
run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
for names in [json!(["Fade", "Squares"]), json!(["Squares", "Fade"])] {
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
assert_eq!(named_after(&s, "Fade"), ["Fade"], "{names}: {r}");
}
}
/// A library tint follows its color when the call picks the color, even when a pattern added
/// before it took the document's numbered copy of that color, with the color itself or with the
/// tint in its art.
#[test]
fn a_library_tint_follows_its_picked_color_not_the_copy_a_pattern_took() {
for tint in [100, 50] {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": tint, "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let names = json!(["Tiles", "Ink half", "Ink"]);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
let picked = r["added"].as_array().and_then(|a| a.iter().find(|n| n.as_str().is_some_and(|n| n.starts_with("Ink half"))).cloned());
let picked = picked.and_then(|n| n.as_str().map(str::to_string)).unwrap_or_default();
assert_eq!(tint_base(&s, &picked).as_deref(), Some("Ink"), "tint {tint}: {r}");
let before = named_after(&s, "Ink half");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names}));
assert_eq!(named_after(&s, "Ink half"), before, "tint {tint}: {again}");
}
}
/// A library tint is not taken for the tint a pattern brought back in the library color's place
/// when that tint shows the document's own color (the pattern's art links to it, as pasting with
/// Merge leaves it): it comes in as a tint of the library color's numbered copy.
#[test]
fn a_library_tint_is_not_the_one_a_merged_pattern_brought() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "the pasted tint follows the document's Ink");
run(&mut s, "swatch.delete", json!({"names": ["Ink half"], "unlink": false}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Ink half"]}));
assert_eq!(doc(&s).patterns.len(), 1, "{r}");
let tint = r["added"][1].as_str().unwrap_or_default().to_string();
assert!(tint.starts_with("Ink half"), "{r}");
assert_eq!(tint_base(&s, &tint).as_deref(), Some("Ink 2"), "{r}");
}
/// A library gradient is not taken for the gradient a pattern brought back in its place when that
/// gradient's stops show the document's own color.
#[test]
fn a_library_gradient_is_not_the_one_a_merged_pattern_brought() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]});
run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
run(&mut s, "swatch.delete", json!({"names": ["Fade"], "unlink": false}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Fade"]}));
assert_eq!(doc(&s).patterns.len(), 1, "{r}");
let fade = r["added"][1].as_str().unwrap_or_default().to_string();
assert!(fade.starts_with("Fade"), "{r}");
let (first, link) = match doc(&s).swatch(&fade).map(|w| &w.paint) {
Some(Paint::Gradient(g)) => (g.gradient.stops.first().map(|stop| stop.color), g.gradient.stops.first().and_then(|stop| stop.swatch.clone())),
_ => (None, None),
};
assert_eq!(link.as_deref(), Some("Ink 2"), "the stop links to the library's color: {r}");
let blue = match doc(&s).swatch("Ink 2").map(|w| &w.paint) {
Some(Paint::Solid { color, .. }) => Some(*color),
_ => None,
};
assert!(blue.is_some() && first == blue, "{r}");
}
#[test]
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
let bytes = vectorcraft_testkit::ase::sample();
+20 -3
View File
@@ -5810,7 +5810,21 @@ From a document, such as a `.ai` or `.eps` swatch library, it reads the colors,
in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and
art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot
color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes
in under a numbered name ("Ink 2") and the pattern links to that. A document with
in under a numbered name ("Ink 2") and the pattern links to that. That numbered name skips the names the library
gives its other swatches. A library color whose name the document gives
another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color
again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name
is used as it is. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the
document as such a numbered copy, links to that copy, whether the color is picked before or after it, was added
earlier or came with a pattern's art. A library global color is not the document's process color of the same name and
paint: it comes in numbered. A global or spot color that a library tint or gradient links to and the document lacks
comes in with the tint or gradient, under a numbered name when the document gives its name another swatch. The
document's tint or gradient of the library one's name is that swatch when it links to the copy of the color that the
art of a pattern picked with it takes; a numbered copy that the library also names stands for that library swatch
otherwise. When the document's tint or gradient links to a color the document no longer has (deleted without
unlinking), that color comes back under its own name. A pattern is found again when it was pasted with Add or Merge for all of its colors; one pasted
with Merge for some colors and Add for others is added again as a copy. `added` lists the colors the pattern's art, a
tint or a gradient brings too. A document with
no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with
"`<file>` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The
Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files.
@@ -6023,8 +6037,11 @@ swatch, else `Gradient`; `library.use` paints the selection's fill or stroke wit
(else the default one, or the pattern swatch `swatch`) with the images, symbols, patterns, swatches, styles and brushes
its art uses, and a thumbnail of one swatch's worth of it; `library.use` adds the pattern and its swatch to the document (the
same pattern there is reused, and a name the document gives another pattern gets a number) and paints the selection's
fill or stroke with it, as one undo step, and returns the pattern's name in the document as `pattern`. `library.get`
lists them as `gradients: [{name, gradient}]` and `patterns: [{name, pattern, thumbnail}]`.
fill or stroke with it, as one undo step, and returns the pattern's name in the document as `pattern`. A global or spot
color the pattern's art links to keeps the item's color, as with `swatch.library.add`: when the document gives its name
another color, it comes in under a numbered name ("Ink 2"), or as the document's numbered copy of the same color, and
the pattern links to it. A pattern the document holds with its art linked to the document's own color of that name is
reused. `library.get` lists them as `gradients: [{name, gradient}]` and `patterns: [{name, pattern, thumbnail}]`.
Items can be put in user-named groups, which the panel shows as collapsible sections after the ungrouped items (its
search field filters every item by name; `library.get` lists them all to filter). `library.createGroup {library?,
+1 -1
View File
@@ -2241,7 +2241,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`).
In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning.
`.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`).
Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`).
Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`).
A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`).
A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`).
In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`).