Swatches: a library pattern painted with another pattern is matched by both

Adding a library pattern swatch reused a document pattern with the same
tile options and art even when that art paints with a pattern of the same
name and a different definition, so the library's inner pattern never came
in. A pattern whose art uses other resources is now matched by importing it
into a copy of the document, which compares those resources too.
This commit is contained in:
dotCooCoo
2026-11-16 21:51:12 -08:00
parent ad2572734c
commit 49184fc486
3 changed files with 90 additions and 4 deletions
+45 -3
View File
@@ -12,7 +12,7 @@ use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
use super::Result;
use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::clipboard::resources::{Imported, SwatchChoices};
use super::swatchlib::LibraryInfo;
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
@@ -89,10 +89,52 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> {
/// 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`.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<String> {
let imported = gather(lib, name).import_into(d, &SwatchChoices::default(), false)?;
Ok(imported_name(&imported, name))
}
/// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied.
fn gather(lib: &Document, name: &str) -> Clipboard {
let user = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::basic(pattern_paint(name), Paint::None, 0.0));
let imported = Clipboard::gather(lib, vec![user]).import_into(d, &SwatchChoices::default(), false)?;
Clipboard::gather(lib, vec![user])
}
/// The name pattern `name` has in the document `imported` went into.
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());
Ok(renamed.unwrap_or(name).to_string())
renamed.unwrap_or(name).to_string()
}
/// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding
/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as
/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted
/// with, is imported into a copy of `d`, so that those resources are compared too.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> {
let gathered = gather(lib, name);
let only_pattern = gathered.patterns.len() == 1
&& gathered.symbols.is_empty()
&& gathered.swatches.is_empty()
&& gathered.graphic_styles.is_empty()
&& gathered.char_styles.is_empty()
&& gathered.para_styles.is_empty()
&& gathered.brushes.is_empty()
&& gathered.images.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)?;
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let copy = |n: &str| {
n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
};
if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) {
return None;
}
let mut probe = d.clone();
let imported = gathered.import_into(&mut probe, &SwatchChoices::default(), false).ok()?;
(imported.added == 0).then(|| imported_name(&imported, name))
}
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
+1 -1
View File
@@ -939,7 +939,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
let there = |w: &Swatch| match (&w.paint, &patterns) {
(Paint::Pattern { pattern, .. }, Some(src)) => {
patternlib::existing_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target))
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,
+44
View File
@@ -369,6 +369,50 @@ fn a_pattern_swatch_named_after_its_pattern_reuses_one_added_in_the_same_call()
assert_eq!(d.swatches_iter().filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Dots")).count(), 1, "{r}");
}
/// A library pattern painted with another pattern is not taken for a document pattern with the
/// same art when the pattern its art paints with differs: it comes in as a numbered copy with its
/// own inner pattern, and adding it again reuses that copy.
#[test]
fn a_pattern_painted_with_another_pattern_is_not_matched_by_the_inner_patterns_name() {
use std::sync::Arc;
use vectorcraft_doc::pattern::pattern_paint;
// `Inner` with a tile of `inner` points, `Dots` painted with it, and swatch `Tiles` painting `Dots`.
let make = |d: &mut vectorcraft_doc::Document, inner: f64| {
let dot = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 2.0, 2.0));
let dot = vectorcraft_doc::Node::path(d.alloc_id(), dot, vectorcraft_doc::Appearance::default_art());
let tile = vectorcraft_geom::Rect::new(0.0, 0.0, inner, inner);
d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Inner", vec![Arc::new(dot)]) });
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(pattern_paint("Inner"), 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("Dots", vec![Arc::new(square)]) });
d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Dots"), global: false, spot: false });
};
let mut s = session();
s.edit("Pattern", |d, _| {
make(d, 4.0);
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": "Dots.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
s.edit("Pattern", |d, _| {
make(d, 5.0);
Ok(())
})
.unwrap();
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles 2"]), &json!([])), "{r}");
let d = doc(&s);
let Some(Paint::Pattern { pattern, .. }) = d.swatch("Tiles 2").map(|w| &w.paint) else { panic!("no pattern swatch Tiles 2: {r}") };
let inner = d.pattern(pattern).and_then(|p| p.art.first()).map(|n| n.appearance.fill_paint());
let Some(Paint::Pattern { pattern: inner, .. }) = inner else { panic!("the added pattern is not painted with a pattern: {r}") };
assert_eq!(d.pattern(&inner).map(|p| p.tile), Some(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)), "the library's inner pattern");
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles 2"])), "{again}");
}
#[test]
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
let bytes = vectorcraft_testkit::ase::sample();