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]