From a71de2dd7a14fdc6e98669f23875f95a86a11d46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:16:36 -0800 Subject: [PATCH] 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}");