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