From 0575c1604a04d3cd04625243eb5b73fe95818885 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:55:08 -0800 Subject: [PATCH 1/8] Swatch libraries: adding a pattern again reuses its numbered colors Since the change that brings a library pattern's global and spot colors under a numbered name ("Ink 2") when the document gives the name another color, adding the same pattern or color again added more copies, and Use Library Item still linked a pattern's art to the document's own color of that name. - A library color whose name the document gives another color is the document's numbered copy with the same color, so adding it again adds nothing. A numbered name that the same call also picks is not shared. - A pattern the document holds with its art linked to the document's own color of a name, as pasting with Merge leaves it, is reused instead of coming in again as "Squares 2". - `added` lists the colors a pattern brought, after the picked swatches. - A library tint added with its base color links to the base's name in the document, and a later add finds it there. - library.use brings a pattern's colors the same way. Docs: docs/mcp.md. --- crates/engine/src/cmd/clipboard/resources.rs | 5 +- crates/engine/src/cmd/library.rs | 32 +++- crates/engine/src/cmd/patternlib.rs | 56 ++++-- crates/engine/src/cmd/swatchlib.rs | 80 ++++++-- crates/engine/src/tests/library.rs | 86 +++++++++ crates/engine/src/tests/swatchlib.rs | 192 +++++++++++++++++++ docs/mcp.md | 11 +- 7 files changed, 426 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index c20c763495..4d1c3aa53a 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -623,8 +623,9 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } - /// Add for every conflict: each pasted swatch whose name the document gives another color - /// comes in renamed. + /// Add for every conflict, as a library pattern is added to a document: each global or spot + /// color of its art whose name the document gives another color comes in under a numbered + /// name, or as the document's numbered copy of that name with the same color. pub(crate) fn add_all() -> Self { Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } } diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4d562a76e7..6bbb4049e0 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -713,7 +713,7 @@ pub fn specs() -> Vec { "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 +1353,32 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { if clip.nodes.is_empty() { return Err(damaged()); } - let choices = SwatchChoices::default(); + // 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"), as + // Add to Swatches brings a library pattern's colors. + let mut choices = SwatchChoices::add_all(); // 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(); + let current = s.doc()?.doc.clone(); + let mut probe = (*current).clone(); + let mut imported = clip.import_into(&mut probe, &choices, false)?; + let pattern_of = |i: &super::clipboard::resources::Imported| { + i.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str()).unwrap_or(&name).to_string() + }; + // A pattern used before a color of its art kept the library's color has its art linked to the + // document's own color of that name: when merging those colors reuses a pattern of the document + // that keeping them would add again, they merge. + if current.pattern(&pattern_of(&imported)).is_none() + && imported.renamed.iter().any(|r| r["kind"] == "swatch") + && super::patternlib::has_candidate(¤t, &doc, &name) + { + let mut merged = (*current).clone(); + let found = clip.import_into(&mut merged, &SwatchChoices::default(), false)?; + if current.pattern(&pattern_of(&found)).is_some() { + (choices, probe, imported) = (SwatchChoices::default(), merged, found); + } + } + drop(current); + let target = pattern_of(&imported); 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 = diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 97351a27a2..84453f4268 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -90,10 +90,17 @@ pub fn swatch_source(w: &Swatch) -> Option> { /// 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. /// 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. +/// 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 +/// ([`merge_reuses`]). pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> { + let gathered = gather(lib, name); + let merge = !gathered.swatches.is_empty() + && has_candidate(d, lib, name) + && probe(d, &gathered, &SwatchChoices::add_all()).and_then(|with_add| merge_reuses(d, &gathered, name, &with_add)).is_some(); + let choices = if merge { SwatchChoices::default() } else { SwatchChoices::add_all() }; let had: std::collections::HashSet = d.swatches_iter().map(|w| w.name.clone()).collect(); - let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?; + let imported = gathered.import_into(d, &choices, 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() @@ -121,7 +128,8 @@ fn imported_name(imported: &Imported, name: &str) -> 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. +/// with, is imported into a copy of `d`, so that those resources are compared too, with the colors +/// of its art merged when [`merge_reuses`] says so. pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 @@ -131,23 +139,49 @@ 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); } - // 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 with_add = probe(d, &gathered, &SwatchChoices::add_all())?; + if with_add.added == 0 { + return Some(imported_name(&with_add, name)); + } + merge_reuses(d, &gathered, name, &with_add).filter(|m| m.added == 0).map(|m| imported_name(&m, name)) +} + +/// 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)) { + d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) +} + +/// What importing `gathered` into a copy of `d` with `choices` does. +fn probe(d: &Document, gathered: &Clipboard, choices: &SwatchChoices) -> Option { + let mut probe = d.clone(); + gathered.import_into(&mut probe, choices, false).ok() +} + +/// When importing `gathered` (pattern `name`) into `d` with Add (`with_add`) adds the pattern again +/// because a global or spot color of its art comes in numbered, while merging those colors reuses a +/// pattern of `d`, what merging does. 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. +fn merge_reuses(d: &Document, gathered: &Clipboard, name: &str, with_add: &Imported) -> Option { + let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); + if reused(with_add) || !with_add.renamed.iter().any(|r| r["kind"] == "swatch") { return None; } - 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)) + probe(d, gathered, &SwatchChoices::default()).filter(reused) } /// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index e4d89b9c13..bf564bcede 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "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, 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 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, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1030,34 +1030,69 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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: std::collections::HashMap<&str, Vec<&Swatch>> = std::collections::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) { + // A numbered copy whose name a picked library swatch has stands for that swatch alone. + let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // `paint` is `w`'s paint with a tint's base color under the name the base has in the document. + let there = |w: &Swatch, paint: &Paint| 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()), + Some(x) if x.paint == *paint => Some(w.name.clone()), + // A color whose name the document gives another color is the numbered copy of it that + // an earlier add or a pattern's art brought in, when that copy is the same color. + Some(_) => copies + .get(w.name.as_str()) + .and_then(|c| { + c.iter().find(|x| !picked_names.contains(x.name.as_str()) && x.paint == *paint && x.global == w.global && x.spot == w.spot) + }) + .map(|x| x.name.clone()), + None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()), + }, }; // Library name → the name of the document's swatch. let mut existing: Vec<(String, String)> = vec![]; let mut fresh = vec![]; for &(group, w) in &picked { - match there(w) { + // A tint of a color the document has under a numbered name is compared linked to that name. + let relinked = match &w.paint { + Paint::Solid { swatch: Some(base), .. } => existing.iter().find(|(l, n)| l == base && n != base).map(|(_, n)| { + let mut paint = w.paint.clone(); + if let Paint::Solid { swatch: Some(b), .. } = &mut paint { + *b = n.clone(); + } + paint + }), + _ => None, + }; + match there(w, relinked.as_ref().unwrap_or(&w.paint)) { Some(name) => existing.push((w.name.clone(), name)), None => fresh.push((group, w)), } } let undo_before = s.doc()?.history.undo.len(); - // Library name → the name it got in the document. + // 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 swatch for it, for the tints added here. + let mut links: std::collections::HashMap = existing.iter().cloned().collect(); let added: Vec<(String, String)> = if fresh.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![]; @@ -1101,8 +1136,11 @@ fn add(s: &mut Session, p: &Value) -> Result { (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. + let same = + |to: &str| d.swatch(to).is_some_and(|x| x.paint.color() == w.paint.color() && x.global == w.global && x.spot == w.spot); + 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)) @@ -1111,10 +1149,19 @@ fn add(s: &mut Session, p: &Value) -> Result { Some(sw) => (sw.name.clone(), sw), None => { let name = free_in(&mut taken, &w.name); - (name.clone(), Swatch { name, ..(*w).clone() }) + let mut sw = Swatch { name: name.clone(), ..(*w).clone() }; + // A tint links to its base color under the name the base has in the + // document. + if let Paint::Solid { swatch: Some(base), .. } = &mut sw.paint + && let Some(to) = links.get(base.as_str()) + { + *base = to.clone(); + } + (name, sw) } } }; + links.insert(w.name.clone(), name.clone()); match group { Some(g) => { let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i); @@ -1135,13 +1182,16 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } - Ok((out, reused)) + Ok((out, reused, brought)) })?; existing.extend(reused); + brought_alone = brought; added }; let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::>(); - 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}))?; diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index a75bc532bf..cf5fc3c269 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -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 { + 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 = + 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. diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 8036bf04c3..da044f78e6 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -516,6 +516,198 @@ 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 { + 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::>(), ["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::>(), ["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}"); + assert_eq!(r["applied"], "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 { + 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 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 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}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..bddbbe38e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5802,7 +5802,10 @@ 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. 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. `added` lists the colors the pattern's art brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`` 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. @@ -6015,7 +6018,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` +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 From 35e43f9cfef483d5840c8a8baa88d1ba4832ed14 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:57:17 -0800 Subject: [PATCH 2/8] Swatch libraries: library tints and gradients link to their colors in any order A library tint or gradient whose global or spot color comes in under a numbered name now links to that copy whichever order the swatches are picked in, when the color was added by an earlier call, and when a pattern's art brought the color or took the document's copy of it. Adding the same tints again finds the ones added before. - Each tint's or gradient's color is looked up for itself before anything is added, past a process swatch of the same paint and past a color group of that name. A numbered copy that the library's own swatch of that name is stays that swatch's, and a new copy skips the library's other names. - A tint links to a global or spot color of the same kind only, and to a color this call picks rather than to a copy a pattern took. - Links are set as soon as the color's name is known. A tint waiting for a color that a pattern's art brings learns its name from an import into a copy, so the pattern does not add a second tint. - A swatch a pattern brought takes a picked swatch's place only when its colors link where the picked one's do. - A stop linked to the Registration swatch counts as linked. - library.use, Add to Swatches and the reuse check share one import probe (patternlib::probe_import), and the probed copy is kept instead of importing a second time. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/clipboard/resources.rs | 5 +- crates/engine/src/cmd/library.rs | 30 +- crates/engine/src/cmd/patternlib.rs | 81 ++-- crates/engine/src/cmd/swatchlib.rs | 247 +++++++++-- crates/engine/src/tests/swatchlib.rs | 418 +++++++++++++++++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 2 +- 7 files changed, 686 insertions(+), 104 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 4d1c3aa53a..c20c763495 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -623,9 +623,8 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } - /// Add for every conflict, as a library pattern is added to a document: each global or spot - /// color of its art whose name the document gives another color comes in under a numbered - /// name, or as the document's numbered copy of that name with the same color. + /// Add for every conflict: each pasted swatch whose name the document gives another color + /// comes in renamed. pub(crate) fn add_all() -> Self { Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } } diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 6bbb4049e0..ecbfa760bb 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -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; @@ -1353,32 +1352,13 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { if clip.nodes.is_empty() { return Err(damaged()); } - // 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"), as - // Add to Swatches brings a library pattern's colors. - let mut choices = SwatchChoices::add_all(); - // The pattern's name in the document, worked out on a copy: nothing to add is no edit. + // 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 mut probe = (*current).clone(); - let mut imported = clip.import_into(&mut probe, &choices, false)?; - let pattern_of = |i: &super::clipboard::resources::Imported| { - i.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str()).unwrap_or(&name).to_string() - }; - // A pattern used before a color of its art kept the library's color has its art linked to the - // document's own color of that name: when merging those colors reuses a pattern of the document - // that keeping them would add again, they merge. - if current.pattern(&pattern_of(&imported)).is_none() - && imported.renamed.iter().any(|r| r["kind"] == "swatch") - && super::patternlib::has_candidate(¤t, &doc, &name) - { - let mut merged = (*current).clone(); - let found = clip.import_into(&mut merged, &SwatchChoices::default(), false)?; - if current.pattern(&pattern_of(&found)).is_some() { - (choices, probe, imported) = (SwatchChoices::default(), merged, found); - } - } + let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip)?; drop(current); - let target = pattern_of(&imported); + 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 = diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 84453f4268..28ec9a80af 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -85,22 +85,29 @@ pub fn swatch_source(w: &Swatch) -> Option> { 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. Those colors /// merge instead when that reuses a pattern of `d` that keeping them would add again -/// ([`merge_reuses`]). -pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> { +/// ([`probe_import`]). +pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> { let gathered = gather(lib, name); - let merge = !gathered.swatches.is_empty() - && has_candidate(d, lib, name) - && probe(d, &gathered, &SwatchChoices::add_all()).and_then(|with_add| merge_reuses(d, &gathered, name, &with_add)).is_some(); - let choices = if merge { SwatchChoices::default() } else { SwatchChoices::add_all() }; let had: std::collections::HashSet = d.swatches_iter().map(|w| w.name.clone()).collect(); - let imported = gathered.import_into(d, &choices, 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() @@ -110,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. @@ -119,8 +133,13 @@ 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 { + gather(lib, name).swatches.into_iter().map(|w| w.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() } @@ -128,8 +147,8 @@ fn imported_name(imported: &Imported, name: &str) -> 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, with the colors -/// of its art merged when [`merge_reuses`] says so. +/// 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 { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 @@ -148,11 +167,8 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio if !has_candidate(d, lib, name) { return None; } - let with_add = probe(d, &gathered, &SwatchChoices::add_all())?; - if with_add.added == 0 { - return Some(imported_name(&with_add, name)); - } - merge_reuses(d, &gathered, name, &with_add).filter(|m| m.added == 0).map(|m| imported_name(&m, name)) + let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?; + (imported.added == 0).then(|| imported_name(&imported, name)) } /// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name @@ -166,22 +182,25 @@ pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool { d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) } -/// What importing `gathered` into a copy of `d` with `choices` does. -fn probe(d: &Document, gathered: &Clipboard, choices: &SwatchChoices) -> Option { - let mut probe = d.clone(); - gathered.import_into(&mut probe, choices, false).ok() -} - -/// When importing `gathered` (pattern `name`) into `d` with Add (`with_add`) adds the pattern again -/// because a global or spot color of its art comes in numbered, while merging those colors reuses a -/// pattern of `d`, what merging does. 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. -fn merge_reuses(d: &Document, gathered: &Clipboard, name: &str, with_add: &Imported) -> Option { +/// 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(); - if reused(with_add) || !with_add.renamed.iter().any(|r| r["kind"] == "swatch") { - return None; + 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(); + if let Ok(found) = gathered.import_into(&mut merged, &SwatchChoices::default(), false) + && reused(&found) + { + return Ok((SwatchChoices::default(), merged, found)); + } } - probe(d, gathered, &SwatchChoices::default()).filter(reused) + 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 diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index bf564bcede..40b20e5c3a 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "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, 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 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, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], 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, 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 links to its color under the name that color has in the document. 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, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1011,6 +1011,89 @@ fn free_in(taken: &mut HashSet, 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, 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 +} + +/// 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, in one pass over +/// the document's swatches. +fn settle(d: &mut vectorcraft_doc::Document, pending: &mut Vec<(String, &Swatch)>, links: &std::collections::HashMap) { + let mut done: std::collections::HashMap = std::collections::HashMap::new(); + pending.retain(|(name, w)| { + let all = all_linked(&w.paint, links); + if all { + done.insert(name.clone(), relinked(&w.paint, links)); + } + !all + }); + if !done.is_empty() { + for x in d.swatches_iter_mut() { + if let Some(paint) = done.get(&x.name) { + 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: &std::collections::HashMap) -> 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: &std::collections::HashMap) -> bool { + linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n)) +} + fn add(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.add"; let (info, lib) = library_param(s, p, C)?; @@ -1042,42 +1125,69 @@ fn add(s: &mut Session, p: &Value) -> Result { copies.entry(base).or_default().push(w); } } - // A numbered copy whose name a picked library swatch has stands for that swatch alone. - let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); - // `paint` is `w`'s paint with a tint's base color under the name the base has in the document. - let there = |w: &Swatch, paint: &Paint| match (&w.paint, &patterns) { + // The library's swatches by name (the first of a name wins), looked up once. + let mut lib_by_name: std::collections::HashMap<&str, &Swatch> = std::collections::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; + let numbered = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap| { + 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); + let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w)); + found.map(|x| x.name.clone()) + }; + let unlinked = std::collections::HashMap::new(); + // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. + let there = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap| 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) if x.paint == *paint => Some(w.name.clone()), - // A color whose name the document gives another color is the numbered copy of it that - // an earlier add or a pattern's art brought in, when that copy is the same color. - Some(_) => copies - .get(w.name.as_str()) - .and_then(|c| { - c.iter().find(|x| !picked_names.contains(x.name.as_str()) && x.paint == *paint && x.global == w.global && x.spot == w.spot) - }) - .map(|x| x.name.clone()), + 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()), }, }; + let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // 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: std::collections::HashMap = std::collections::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); + } + } + } // Library name → the name of the document's swatch. let mut existing: Vec<(String, String)> = vec![]; let mut fresh = vec![]; for &(group, w) in &picked { - // A tint of a color the document has under a numbered name is compared linked to that name. - let relinked = match &w.paint { - Paint::Solid { swatch: Some(base), .. } => existing.iter().find(|(l, n)| l == base && n != base).map(|(_, n)| { - let mut paint = w.paint.clone(); - if let Paint::Solid { swatch: Some(b), .. } = &mut paint { - *b = n.clone(); - } - paint - }), - _ => None, - }; - match there(w, relinked.as_ref().unwrap_or(&w.paint)) { + // 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) => existing.push((w.name.clone(), name)), None => fresh.push((group, w)), } @@ -1087,8 +1197,14 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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 swatch for it, for the tints added here. - let mut links: std::collections::HashMap = existing.iter().cloned().collect(); + // 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: std::collections::HashMap = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); + links.extend(base_names); let added: Vec<(String, String)> = if fresh.is_empty() { vec![] } else { @@ -1104,13 +1220,40 @@ fn add(s: &mut Session, p: &Value) -> Result { // The swatches the patterns imported in this call brought with their art: (library // name, document name). let mut brought: Vec<(String, String)> = vec![]; + // 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); + if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { + let mut probe = d.clone(); + let (_, colors, took) = patternlib::import(&mut probe, src, pattern)?; + for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { + if probe.swatch(to).is_some_and(|x| x.global || x.spot) { + links.entry(from.clone()).or_insert_with(|| to.clone()); + } + } + } + settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors) = patternlib::import(d, src, pattern)?; + let (target, colors, took) = patternlib::import(d, src, pattern)?; + // A global or spot color the pattern brought, or took from the document under + // a numbered name, is the one the library's tints of it link to, unless the + // document already has one for it. A color this call picks is added under + // its own name instead of the one the pattern took. + for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { + if d.swatch(to).is_some_and(|x| x.global || x.spot) { + links.entry(from.clone()).or_insert_with(|| to.clone()); + } + } brought.extend(colors); if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { reused.push((w.name.clone(), name)); @@ -1137,9 +1280,20 @@ fn add(s: &mut Session, p: &Value) -> Result { } else { // A color a pattern added earlier in this call brought with its art is that // swatch when it shows the library swatch's color: it moves to the library - // swatch's place. - let same = - |to: &str| d.swatch(to).is_some_and(|x| x.paint.color() == w.paint.color() && x.global == w.global && x.spot == w.spot); + // swatch's place, when its colors link where the library swatch's do: to the + // names `links` gives them, and not elsewhere for a color this call has yet to + // add. + 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), + }) + }; + 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)?; @@ -1148,20 +1302,23 @@ fn add(s: &mut Session, p: &Value) -> Result { match moved { Some(sw) => (sw.name.clone(), sw), None => { - let name = free_in(&mut taken, &w.name); - let mut sw = Swatch { name: name.clone(), ..(*w).clone() }; - // A tint links to its base color under the name the base has in the - // document. - if let Paint::Solid { swatch: Some(base), .. } = &mut sw.paint - && let Some(to) = links.get(base.as_str()) - { - *base = to.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, sw) + (name.clone(), Swatch { name, paint, ..(*w).clone() }) } } }; - links.insert(w.name.clone(), name.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); @@ -1182,6 +1339,14 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } + let later: std::collections::HashMap = pending.into_iter().map(|(name, w)| (name, relinked(&w.paint, &links))).collect(); + if !later.is_empty() { + for x in d.swatches_iter_mut() { + if let Some(paint) = later.get(&x.name) { + x.paint = paint.clone(); + } + } + } Ok((out, reused, brought)) })?; existing.extend(reused); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index da044f78e6..875d9b5e28 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -660,6 +660,153 @@ fn a_library_tint_follows_its_color_to_its_numbered_name() { 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] @@ -676,6 +823,237 @@ fn a_numbered_copy_the_library_also_names_is_not_shared() { assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{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 after a pattern brought it under that name 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 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.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); + 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}"); + } +} + +/// A numbered copy that the library's own swatch of that name is (the same paint, whatever its +/// kind) is not also taken for the library color it is numbered after. +#[test] +fn a_numbered_copy_the_library_has_by_paint_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"})); + 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 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}"); +} + +/// Adding a library color the document has as a process color of the same paint, with its tint, +/// again adds no other copy of the tint. +#[test] +fn a_library_tint_of_a_color_the_document_has_as_process_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 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"})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + let before = named_after(&s, "Ink half"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!(named_after(&s, "Ink half"), before, "{r} then {again}"); +} + +/// 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 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(); + 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": ["Fade", "Squares"]})); + assert_eq!(named_after(&s, "Fade"), ["Fade"], "{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. @@ -708,6 +1086,46 @@ fn a_library_tint_is_not_the_one_a_merged_pattern_brought() { 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(); diff --git a/docs/mcp.md b/docs/mcp.md index bddbbe38e8..af535e4ff7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5805,7 +5805,9 @@ color the pattern's art links to keeps the library's color: when the document gi in under a numbered name ("Ink 2") and the pattern links to that. 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. `added` lists the colors the pattern's art brings too. A document with +is used as it is. A library tint or gradient links to its colors under the names those colors have in the document, +whether a color is picked before or after it, was added earlier or came with a pattern's art. `added` lists the colors +the pattern's art brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`` 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. @@ -6022,8 +6024,7 @@ fill or stroke with it, as one undo step, and returns the pattern's name in the 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}]`. +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?, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..3965f265bf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,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`). 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, and adding it again uses that numbered copy; a library tint links to 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_picked_before_its_color_follows_it_to_its_numbered_name`, `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`). From 9772495468fe65352fa37b46b047f8b6412f8223 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:42:17 -0800 Subject: [PATCH 3/8] Swatch libraries: check the color names a pattern copy gives When a library tint waits for a color that a pattern's art brings, swatch.library.add learns the color's name by importing the pattern into a copy of the document. The import into the document now confirms those names: when it gives a color another name, or none, the tints linked from the copy are linked again. - library.use and Add to Swatches report an error from the import that merges a pattern's colors instead of falling back to adding them. - The params text, docs/mcp.md and docs/target-app-parity.md say that a tint or gradient links to the numbered copy its global or spot color comes in under or already has, and name a gradient test. - The new code uses the HashMap import, and one helper relinks the added tints and gradients at both places that did it. --- crates/engine/src/cmd/patternlib.rs | 5 +- crates/engine/src/cmd/swatchlib.rs | 114 ++++++++++++++++++---------- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 4 files changed, 81 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 28ec9a80af..e8cffa24aa 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -194,9 +194,8 @@ pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: & 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(); - if let Ok(found) = gathered.import_into(&mut merged, &SwatchChoices::default(), false) - && reused(&found) - { + let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?; + if reused(&found) { return Ok((SwatchChoices::default(), merged, found)); } } diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 40b20e5c3a..c120f45038 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "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, 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 links to its color under the name that color has in the document. 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, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], 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, 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 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, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1024,22 +1024,36 @@ fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) } /// 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, in one pass over -/// the document's swatches. -fn settle(d: &mut vectorcraft_doc::Document, pending: &mut Vec<(String, &Swatch)>, links: &std::collections::HashMap) { - let mut done: std::collections::HashMap = std::collections::HashMap::new(); +/// 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, +) -> Vec<(String, &'a Swatch)> { + let mut done = vec![]; pending.retain(|(name, w)| { let all = all_linked(&w.paint, links); if all { - done.insert(name.clone(), relinked(&w.paint, links)); + done.push((name.clone(), *w)); } !all }); - if !done.is_empty() { - for x in d.swatches_iter_mut() { - if let Some(paint) = done.get(&x.name) { - x.paint = paint.clone(); - } + 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) { + 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(); } } } @@ -1073,7 +1087,7 @@ fn linked_names(p: &Paint) -> Vec<&str> { } /// Paint `p` with each link to a swatch that `links` names changed to the name it maps to. -fn relinked(p: &Paint, links: &std::collections::HashMap) -> Paint { +fn relinked(p: &Paint, links: &HashMap) -> Paint { let mut out = p.clone(); let swap = |name: &mut String| { if let Some(to) = links.get(name.as_str()) { @@ -1090,7 +1104,7 @@ fn relinked(p: &Paint, links: &std::collections::HashMap) -> Pai /// 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: &std::collections::HashMap) -> bool { +fn all_linked(p: &Paint, links: &HashMap) -> bool { linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n)) } @@ -1114,7 +1128,7 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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: std::collections::HashMap<&str, Vec<&Swatch>> = std::collections::HashMap::new(); + let mut copies: HashMap<&str, Vec<&Swatch>> = HashMap::new(); for w in d.swatches_iter() { let std::collections::hash_map::Entry::Vacant(e) = by_name.entry(w.name.as_str()) else { continue }; e.insert(w); @@ -1126,7 +1140,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } } // The library's swatches by name (the first of a name wins), looked up once. - let mut lib_by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new(); + 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); } @@ -1137,15 +1151,15 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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; - let numbered = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap| { + let numbered = |w: &Swatch, paint: &Paint, links: &HashMap| { 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); let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w)); found.map(|x| x.name.clone()) }; - let unlinked = std::collections::HashMap::new(); + let unlinked = HashMap::new(); // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. - let there = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap| match (&w.paint, &patterns) { + let there = |w: &Swatch, paint: &Paint, links: &HashMap| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } @@ -1169,7 +1183,7 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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: std::collections::HashMap = std::collections::HashMap::new(); + let mut base_names: HashMap = HashMap::new(); let mut looked_up: HashSet<&str> = HashSet::new(); for (_, w) in &picked { for base in linked_names(&w.paint) { @@ -1203,7 +1217,7 @@ fn add(s: &mut Session, p: &Value) -> Result { 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: std::collections::HashMap = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); + let mut links: HashMap = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); links.extend(base_names); let added: Vec<(String, String)> = if fresh.is_empty() { vec![] @@ -1233,27 +1247,56 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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. + let colors_of = |d: &vectorcraft_doc::Document, colors: &[(String, String)], took: &[(String, String)]| { + let mut out: HashMap = HashMap::new(); + for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { + if d.swatch(to).is_some_and(|x| x.global || x.spot) { + 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) = patternlib::import(&mut probe, src, pattern)?; - for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { - if probe.swatch(to).is_some_and(|x| x.global || x.spot) { - links.entry(from.clone()).or_insert_with(|| to.clone()); + 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); } } } - settle(d, &mut pending, &links); + let settled = settle(d, &mut pending, &links); let had = taken_names(d); let (target, colors, took) = patternlib::import(d, src, pattern)?; - // A global or spot color the pattern brought, or took from the document under - // a numbered name, is the one the library's tints of it link to, unless the - // document already has one for it. A color this call picks is added under - // its own name instead of the one the pattern took. - for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { - if d.swatch(to).is_some_and(|x| x.global || x.spot) { - links.entry(from.clone()).or_insert_with(|| to.clone()); + // 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)); @@ -1339,14 +1382,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } - let later: std::collections::HashMap = pending.into_iter().map(|(name, w)| (name, relinked(&w.paint, &links))).collect(); - if !later.is_empty() { - for x in d.swatches_iter_mut() { - if let Some(paint) = later.get(&x.name) { - x.paint = paint.clone(); - } - } - } + relink_in(d, &pending, &links); Ok((out, reused, brought)) })?; existing.extend(reused); diff --git a/docs/mcp.md b/docs/mcp.md index af535e4ff7..6eda2bc435 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5805,8 +5805,9 @@ color the pattern's art links to keeps the library's color: when the document gi in under a numbered name ("Ink 2") and the pattern links to that. 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 links to its colors under the names those colors have in the document, -whether a color is picked before or after it, was added earlier or came with a pattern's art. `added` lists the colors +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. `added` lists the colors the pattern's art brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3965f265bf..388bc655d1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,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`). 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, and adding it again uses that numbered copy; a library tint links to 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_picked_before_its_color_follows_it_to_its_numbered_name`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + 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, and adding it again uses that numbered copy; a library tint or gradient links to 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_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `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`). From 7f97df87d4f29e75aef1b9c86f1a44a56ef6c91e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 07:54:43 -0800 Subject: [PATCH 4/8] Swatch libraries: library tints link only to a color of their own kind swatch.library.add linked a library tint to the wrong color in two cases. When the document had a process color with the same name and paint as the tint's global color, the global color counted as already present and the tint linked to the process color. When a tint was added without its global color and the document had another swatch of that color's name, the tint linked to that swatch. - A library color counts as already in the document only when the document's color of that name is the same kind: process, global or spot. A global color whose name the document gives a process color now comes in under a numbered name, and its tints link to that copy. - A global or spot color that an added tint or gradient links to, and that the document does not have, now comes in with the tint or gradient. It keeps its own name when that name is free and gets a number otherwise. added lists it after the picked swatches. - A library tint is not the document's tint of the same name and paint when the document's swatch of the base's name is another color or kind. - A tint that a pattern brought is used for a picked library tint only when the color it links to is the library color's kind. --- crates/engine/src/cmd/swatchlib.rs | 50 ++++++++-- crates/engine/src/tests/swatchlib.rs | 143 +++++++++++++++++++++++---- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 4 files changed, 173 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index c120f45038..a2fa4bb0bb 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "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, 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 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, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], 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, 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 ), @@ -1151,20 +1151,31 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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| { 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); + 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| { + 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)) + }; // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. let there = |w: &Swatch, paint: &Paint, links: &HashMap| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } + _ if misplaced(&w.paint, links) => None, _ => match by_name.get(w.name.as_str()) { - Some(x) if x.paint == *paint => Some(w.name.clone()), + Some(x) if x.paint == *paint && same_color_kind(x, w) => Some(w.name.clone()), 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()), @@ -1324,14 +1335,21 @@ fn add(s: &mut Session, p: &Value) -> Result { // A color a pattern added earlier in this call brought with its art is that // 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, and not elsewhere for a color this call has yet to - // add. + // 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), + 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| { @@ -1382,6 +1400,26 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } + // 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)) })?; diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 875d9b5e28..9315eadb06 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -603,7 +603,15 @@ fn apply_paints_with_the_picked_color_not_one_a_pattern_brought() { 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}"); - assert_eq!(r["applied"], "Ink", "{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 @@ -886,10 +894,11 @@ fn a_library_spot_tint_links_to_the_spot_color_not_a_process_one() { } } -/// A numbered copy that the library's own swatch of that name is (the same paint, whatever its -/// kind) is not also taken for the library color it is numbered after. +/// 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_copy_the_library_has_by_paint_is_not_shared() { +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"})); @@ -899,7 +908,7 @@ fn a_numbered_copy_the_library_has_by_paint_is_not_shared() { 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}"); + 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 @@ -948,21 +957,115 @@ fn a_numbered_tint_the_library_has_is_not_shared() { assert_eq!(r["added"].as_array().map(Vec::len), Some(1), "{r}"); } -/// Adding a library color the document has as a process color of the same paint, with its tint, -/// again adds no other copy of the tint. +/// 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(); - run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + 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"})); - let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); - let before = named_after(&s, "Ink half"); - let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); - assert_eq!(named_after(&s, "Ink half"), before, "{r} then {again}"); + 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 = 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 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 @@ -1002,8 +1105,8 @@ fn a_library_tint_with_a_pattern_the_document_has_is_added_once() { } } -/// A library gradient whose stops link to a color and to the Registration swatch, picked before a -/// pattern whose art brings the color under a numbered name, is not added a second time. +/// 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(); @@ -1018,10 +1121,12 @@ fn a_gradient_with_a_registration_stop_before_its_pattern_is_not_copied() { 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(); - 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": ["Fade", "Squares"]})); - assert_eq!(named_after(&s, "Fade"), ["Fade"], "{r}"); + 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 diff --git a/docs/mcp.md b/docs/mcp.md index 6eda2bc435..0a31452419 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5807,8 +5807,10 @@ another color is the document's numbered copy of the same color when it has one, 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. `added` lists the colors -the pattern's art brings too. A document with +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. `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 "`` 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. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 388bc655d1..8a406b82b8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,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`). 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, and adding it again uses that numbered copy; a library tint or gradient links to 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_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + 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, 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`, `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`). From 79dd33e2283d8c3ee507671c4939b1055e88ff3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:30:26 -0800 Subject: [PATCH 5/8] Swatch libraries: a tint whose color was deleted brings it back A library tint or gradient counts as already in the document only when each color it links to is there. When the document's tint of that name links to a color the document no longer has (deleted without unlinking), the color comes back under its own name and is listed in `added`. A picked pattern the document already holds keeps the copy of a color its art takes (a numbered copy the library also names), and the picked tints and gradients of that color link to it, so adding the pattern and the tint again adds nothing. Without such a pattern, a numbered copy the library also names stands for that library swatch alone. docs/mcp.md also states that a pattern pasted with Merge for some colors and Add for others is added again as a copy. --- crates/engine/src/cmd/swatchlib.rs | 108 ++++++++++++++++++++++++--- crates/engine/src/tests/swatchlib.rs | 74 ++++++++++++++++++ docs/mcp.md | 9 ++- 3 files changed, 178 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index a2fa4bb0bb..48413d99a8 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1168,20 +1168,64 @@ fn add(s: &mut Session, p: &Value) -> Result { .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)) }; - // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. - let there = |w: &Swatch, paint: &Paint, links: &HashMap| match (&w.paint, &patterns) { - (Paint::Pattern { pattern, .. }, Some(src)) => { - patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) + let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // 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. + // `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| -> Option> { + let (ours, theirs) = (linked_names(&w.paint), linked_names(&x.paint)); + if ours.len() != theirs.len() { + return None; } - _ if misplaced(&w.paint, links) => None, - _ => match by_name.get(w.name.as_str()) { - Some(x) if x.paint == *paint && same_color_kind(x, w) => Some(w.name.clone()), + let map: HashMap = 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) => { + if !picked_names.contains(l) { + 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| -> Option<(String, Vec)> { + if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { + let target = patternlib::present_pattern(d, src, pattern)?; + 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()), - }, + }; + found.map(|n| (n, vec![])) }; - let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); // 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. @@ -1206,14 +1250,47 @@ fn add(s: &mut Session, p: &Value) -> Result { } } } + // 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 let Some(src) = &patterns + && looked_up.iter().any(|n| !base_names.contains_key(*n)) + { + for (_, w) in &picked { + let Paint::Pattern { pattern, .. } = &w.paint else { continue }; + if patternlib::present_pattern(d, src, pattern).is_none() { + continue; + } + let mut probe: vectorcraft_doc::Document = (**d).clone(); + let Ok((_, _, took)) = patternlib::import(&mut probe, src, pattern) else { continue }; + for (from, to) in took { + 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 = vec![]; for &(group, w) in &picked { // 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) => existing.push((w.name.clone(), name)), + Some((name, back)) => { + existing.push((w.name.clone(), name)); + for n in back { + if !restore.contains(&n) { + restore.push(n); + } + } + } None => fresh.push((group, w)), } } @@ -1230,7 +1307,7 @@ fn add(s: &mut Session, p: &Value) -> Result { }; let mut links: HashMap = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); links.extend(base_names); - let added: Vec<(String, String)> = if fresh.is_empty() { + let added: Vec<(String, String)> = if fresh.is_empty() && restore.is_empty() { vec![] } else { let (added, reused, brought) = s.edit("Add to Swatches", |d, _| { @@ -1245,6 +1322,15 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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![]; diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 9315eadb06..8e24403d60 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -831,6 +831,80 @@ fn a_numbered_copy_the_library_also_names_is_not_shared() { 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 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}"); + 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 after a pattern brought it under that name adds /// no other copy. diff --git a/docs/mcp.md b/docs/mcp.md index 0a31452419..0de5ad1692 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5809,8 +5809,13 @@ is used as it is. A library tint or gradient whose global or spot color comes in 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. `added` -lists the colors the pattern's art, a tint or a gradient brings too. A document with +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 "`` 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. From a71de2dd7a14fdc6e98669f23875f95a86a11d46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:16:36 -0800 Subject: [PATCH 6/8] Swatch libraries: a deleted color a found tint links to keeps its name A numbered copy of a library tint found in the document now brings back the deleted global or spot color it links to, as a tint of the library tint's own name does. A deleted color that the call also picks is added before the other new swatches, so a pattern added earlier in the call cannot give its name to another color and leave the found tint linked to the wrong one. A picked pattern the document already has is probed once: the probe gives both its name in the document and the colors its art takes, instead of a presence check, a second import into a copy and a third presence check. --- crates/engine/src/cmd/patternlib.rs | 25 +++++++++---- crates/engine/src/cmd/swatchlib.rs | 53 ++++++++++++++++++---------- crates/engine/src/tests/swatchlib.rs | 53 ++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index e8cffa24aa..88ec82e145 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -145,11 +145,12 @@ pub(crate) fn imported_name(imported: &Imported, name: &str) -> 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` as [`probe_import`] does, so that those resources are -/// compared too. -pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option { +/// 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() @@ -161,14 +162,24 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio && 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![])); } // 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()?; - (imported.added == 0).then(|| imported_name(&imported, name)) + 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 diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 48413d99a8..d0fbd1e0e0 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1169,8 +1169,18 @@ fn add(s: &mut Session, p: &Value) -> Result { .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. + // 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. @@ -1192,9 +1202,7 @@ fn add(s: &mut Session, p: &Value) -> Result { (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) => { - if !picked_names.contains(l) { - restore.push(l.to_string()); - } + restore.push(l.to_string()); true } None => false, @@ -1209,9 +1217,9 @@ fn add(s: &mut Session, p: &Value) -> Result { // `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| -> Option<(String, Vec)> { - if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { - let target = patternlib::present_pattern(d, src, pattern)?; - return library_pattern_swatch(d, w, &target).map(|n| (n, vec![])); + 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)); @@ -1224,7 +1232,12 @@ fn add(s: &mut Session, p: &Value) -> Result { 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()), }; - found.map(|n| (n, vec![])) + // 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, @@ -1254,17 +1267,11 @@ fn add(s: &mut Session, p: &Value) -> Result { // 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 let Some(src) = &patterns - && looked_up.iter().any(|n| !base_names.contains_key(*n)) - { + if looked_up.iter().any(|n| !base_names.contains_key(*n)) { for (_, w) in &picked { let Paint::Pattern { pattern, .. } = &w.paint else { continue }; - if patternlib::present_pattern(d, src, pattern).is_none() { - continue; - } - let mut probe: vectorcraft_doc::Document = (**d).clone(); - let Ok((_, _, took)) = patternlib::import(&mut probe, src, pattern) else { continue }; - for (from, to) in took { + 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); @@ -1279,6 +1286,9 @@ fn add(s: &mut Session, p: &Value) -> Result { // the document has no swatch of that name (one deleted without unlinking them): they come back // under their own names. let mut restore: Vec = 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 = HashSet::new(); for &(group, w) in &picked { // A tint or gradient is compared with its colors linked to the names they have here. let paint = relinked(&w.paint, &base_names); @@ -1286,7 +1296,9 @@ fn add(s: &mut Session, p: &Value) -> Result { Some((name, back)) => { existing.push((w.name.clone(), name)); for n in back { - if !restore.contains(&n) { + if picked_names.contains(n.as_str()) { + reserved.insert(n); + } else if !restore.contains(&n) { restore.push(n); } } @@ -1294,6 +1306,11 @@ fn add(s: &mut Session, p: &Value) -> Result { 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. The colors the patterns brought that no // library swatch of this call stands for are added too; they are listed after the others and diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 8e24403d60..fc450ebc95 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -852,6 +852,55 @@ fn a_library_tint_whose_color_the_document_deleted_brings_the_color_back() { 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. @@ -875,6 +924,10 @@ fn a_library_tint_linked_to_the_copy_a_pattern_took_is_found_again() { 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}"); From ff26d5e4a36d603675e72653740abd15b83ce200 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:38:19 -0800 Subject: [PATCH 7/8] Swatch libraries: colors a pattern brings skip the library's other names A global or spot color that a library pattern's art brings under a numbered name no longer takes a name the library gives another swatch. Before, adding a pattern whose art uses "Ink" to a document with another "Ink" brought the color as "Ink 2" even when the library has its own "Ink 2"; adding that library swatch next then came in as "Ink 2 2". The brought color now takes the next free name the library does not use ("Ink 3"), and every paint linked to it follows the new name, so adding the library's "Ink 2" next adds it under its own name and adding both again adds nothing. A color the pattern's art brings or takes is the color a library tint or gradient links to only when it has the library color's paint and its process, global or spot kind, as for the other lookups in the same add. The test a_numbered_copy_named_like_another_library_color_is_found now makes the blue "Ink 2" itself, as an earlier version's pattern add left it, since a pattern add no longer gives that name. --- crates/engine/src/cmd/swatchlib.rs | 41 +++++++++++++-- crates/engine/src/tests/swatchlib.rs | 78 ++++++++++++++++++++++++---- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 106 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index d0fbd1e0e0..7a5dc06c18 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "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, 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, 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}", + "{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 ), @@ -1023,6 +1023,30 @@ fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) name } +/// Rename each swatch of `d` that `colors` lists (library name, document name) under a numbered +/// name that `reserved` says the library gives another swatch, to a free numbered name of its own +/// ([`free_copy_in`]), and link every paint linked to it to the new name. A later add then finds +/// the library's swatch of that name under its own name. +fn rename_brought(d: &mut vectorcraft_doc::Document, colors: &mut patternlib::SwatchNames, reserved: impl Fn(&str) -> bool) { + let mut taken = taken_names(d); + for (from, to) in colors.iter_mut() { + if from == to || !reserved(to) { + continue; + } + let new = free_copy_in(&mut taken, from, &reserved); + let Some(w) = d.swatches_iter_mut().find(|w| w.name == *to) else { continue }; + w.name = new.clone(); + map_swatch_links(d, &mut |_, link, _| { + let hit = link.as_deref() == Some(to.as_str()); + if hit { + *link = Some(new.clone()); + } + hit + }); + *to = new; + } +} + /// 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. @@ -1363,11 +1387,14 @@ fn add(s: &mut Session, p: &Value) -> Result { 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. + // 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 = HashMap::new(); for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { - if d.swatch(to).is_some_and(|x| x.global || x.spot) { + 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()); } } @@ -1377,7 +1404,8 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); - let (_, colors, took) = patternlib::import(&mut probe, src, pattern)?; + let (_, mut colors, took) = patternlib::import(&mut probe, src, pattern)?; + rename_brought(&mut probe, &mut colors, |n| lib_by_name.contains_key(n)); 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); @@ -1387,7 +1415,10 @@ fn add(s: &mut Session, p: &Value) -> Result { } let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors, took) = patternlib::import(d, src, pattern)?; + let (target, mut colors, took) = patternlib::import(d, src, pattern)?; + // A color the art brought under a numbered name the library gives another + // swatch takes a free one instead. + rename_brought(d, &mut colors, |n| lib_by_name.contains_key(n)); // 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 diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index fc450ebc95..5a7615327a 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -959,25 +959,18 @@ fn a_tint_linked_to_a_copy_the_library_names_is_not_another_colors_tint() { } /// 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 after a pattern brought it under that name adds -/// no other copy. +/// 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 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 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.library.add", json!({"library": id, "names": ["Tiles"]})); - assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); + 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}"); } @@ -1183,6 +1176,69 @@ fn a_library_spot_tint_is_not_a_process_tint_a_pattern_brought() { 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 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] diff --git a/docs/mcp.md b/docs/mcp.md index 0de5ad1692..559dc0b3a0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5802,7 +5802,8 @@ 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 library color whose name the document gives +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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8a406b82b8..f2744f2bb6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,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`). 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, 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`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + 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`). From 6404b0cebfed434ccae6d1da78efe4fea7b1e025 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:31:08 -0800 Subject: [PATCH 8/8] Swatch libraries: hold the library's numbered names while a pattern comes in A color a library pattern's art brings now skips the library's numbered names while the pattern is imported, instead of being renamed after the import. The rename also rewrote every other paint in the document linked to the name the import first gave, such as art still linked to a deleted "Ink 2", so adding the pattern changed that art. Now the names are held with placeholder swatches during the import and removed afterwards, and links that were already in the document stay as they were. A pattern whose art brings both "Ink" and the library's "Ink 2" keeps the library's "Ink 2" under its own name when the document gives "Ink" another color, and the library's "Ink" takes the next free name. A library pattern with a numbered name, such as "Tiles 2", keeps that name when the document does not use it. --- crates/engine/src/cmd/patternlib.rs | 5 ++ crates/engine/src/cmd/swatchlib.rs | 75 ++++++++++++++++++---------- crates/engine/src/tests/swatchlib.rs | 74 +++++++++++++++++++++++++++ 3 files changed, 128 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 88ec82e145..64342b21dd 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -138,6 +138,11 @@ pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::Has 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 { + gather(lib, name).patterns.into_iter().map(|p| p.name).collect() +} + /// The name pattern `name` has in the document `imported` went into. 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()); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 7a5dc06c18..341a26a4b1 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1023,28 +1023,55 @@ fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) name } -/// Rename each swatch of `d` that `colors` lists (library name, document name) under a numbered -/// name that `reserved` says the library gives another swatch, to a free numbered name of its own -/// ([`free_copy_in`]), and link every paint linked to it to the new name. A later add then finds -/// the library's swatch of that name under its own name. -fn rename_brought(d: &mut vectorcraft_doc::Document, colors: &mut patternlib::SwatchNames, reserved: impl Fn(&str) -> bool) { - let mut taken = taken_names(d); - for (from, to) in colors.iter_mut() { - if from == to || !reserved(to) { - continue; - } - let new = free_copy_in(&mut taken, from, &reserved); - let Some(w) = d.swatches_iter_mut().find(|w| w.name == *to) else { continue }; - w.name = new.clone(); - map_swatch_links(d, &mut |_, link, _| { - let hit = link.as_deref() == Some(to.as_str()); - if hit { - *link = Some(new.clone()); +/// [`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, Vec) = (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()); } - hit - }); - *to = new; + } } + 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 = 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 @@ -1404,8 +1431,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); - let (_, mut colors, took) = patternlib::import(&mut probe, src, pattern)?; - rename_brought(&mut probe, &mut colors, |n| lib_by_name.contains_key(n)); + 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); @@ -1415,10 +1441,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, mut colors, took) = patternlib::import(d, src, pattern)?; - // A color the art brought under a numbered name the library gives another - // swatch takes a free one instead. - rename_brought(d, &mut colors, |n| lib_by_name.contains_key(n)); + 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 diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 5a7615327a..5d94eecc69 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -1239,6 +1239,80 @@ fn a_color_a_pattern_brings_skips_the_librarys_numbered_names() { 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]