diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f912fce7ae..0a98ddd9bc 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -579,6 +579,11 @@ 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. + pub(crate) fn add_all() -> Self { + Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } + } fn of(&self, name: &str) -> SwatchChoice { self.by_name.get(name).copied().unwrap_or(self.all) } diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index c53822868c..2cc57144fb 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -838,13 +838,13 @@ fn other_open_filters() -> impl Iterator impl Iterator { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label)) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index bbf6883834..f3161c229d 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() { } } +/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load +/// as a library, and it is the only filter of that label. +#[test] +fn the_swatch_library_filter_lists_ai_and_eps_files() { + let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect(); + for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] { + assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]); + } + assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}"); + // File › Open still opens a `.ai` as a document, not as a swatch library. + assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai")); +} + /// The extensions usage texts list for export: one per writable format, each picking that format /// (`.png` picks PNG; PNG-8 is asked for by `format`). #[test] diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..3754752939 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -413,6 +413,114 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the +/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with +/// `square` (a color operator), a color the palette doesn't list. +fn textures_library(square: &str) -> Vec { + let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"); + let gradient = + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\ + 1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}")); + ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f") +} + +/// `swatch.library.load` of `file` named `name` → its library id. +fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value { + let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name}); + s.execute("swatch.library.load", &p).unwrap()["library"].clone() +} + +/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its +/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's +/// tile and art in the document, in the library's color group, not the pattern's colors. +#[test] +fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let kinds: Vec<(&str, &str, Option<&str>)> = + lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect(); + assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}"); + assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}"); + // The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own. + let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap(); + let tiles = library.iter().find(|w| w.name == "Tiles").unwrap(); + assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some())); + assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none()); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap(); + assert_eq!(r["added"], json!(["Tiles"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let dots = doc.pattern("Dots").expect("the pattern comes with its swatch"); + assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0)); + assert_eq!(dots.art.len(), 1, "{:?}", dots.art); + let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too"); + let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect(); + assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}"); + // Added again, the swatch the document has is used. + let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}"); +} + +/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list +/// still comes in with that color in its art. +#[test] +fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + let doc = &s.doc().unwrap().doc; + let art = &doc.pattern("Dots").unwrap().art; + let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color()); + assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}"); + // Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is + // refused, writes nothing and leaves the library loaded. + let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id())); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string(); + assert!(e.contains("`textures` has pattern swatches"), "{e}"); + assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written"); + assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as +/// swatch libraries with a message, not listed as the default swatches or as an empty library. A +/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file +/// with no swatches loads as an empty library. +#[test] +fn swatch_library_documents_without_swatches_or_damaged_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.edit("Clear", |d, _| { + d.swatches.clear(); + d.swatch_groups.clear(); + Ok(()) + }) + .unwrap(); + let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string(); + assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)))); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("`art.ai` has no swatches of its own"), "{e}"); + let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"}); + assert!(s.execute("swatch.library.load", &damaged).is_err()); + let list = s.execute("swatch.library.list", &json!({})).unwrap(); + assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}"); + // A library file without swatches still loads, as an empty library. + let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap(); + assert_eq!(r["count"], json!(0), "{r}"); +} + /// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the /// library the styles of its list, in the list's order, not the default styles; the file opens with /// them too. diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index f69e4b889e..97351a27a2 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -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. @@ -87,12 +87,67 @@ pub fn swatch_source(w: &Swatch) -> Option> { /// 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`. -pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result { +/// 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. +pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> { + 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 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() + }; + let added = d + .swatches_iter() + .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)) +} + +/// 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 { + 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::add_all(), 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 diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index ed712d8509..f072a75bf3 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 → {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) 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}", has_doc, add ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Other Library…", ["Window", "Swatch Libraries"], None, - "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}", + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}", always, load ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Copy to User Defined", ["Window", "Swatch Libraries"], None, - "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", + "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", has_user_folder, copy_to_user ), @@ -109,6 +109,9 @@ pub struct Libraries { /// the file name instead. [`Libraries::rescan`] drops an entry whose file no longer holds those /// bytes, and keeps one whose file is missing so a file put back can be checked. saved_as: HashMap, + /// The documents loaded swatch libraries were read from, by library id, for those with pattern + /// swatches: the patterns live there ([`Libraries::pattern_doc`]). + pattern_docs: HashMap>, } /// A User Defined file this session wrote: the library's name, and [`vectorcraft_doc::links::hash_bytes`] @@ -149,6 +152,38 @@ impl LibraryFile for SwatchLibrary { /// The extensions of library files [`palette_io::read_bytes`] reads. pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"]; +/// The extensions the Swatch Libraries filter of Other Library… lists: the library files, and the +/// `.ai`, `.ait` and `.eps` (`.epsf`) documents whose swatches load as a library (`swatch.library.load`). +pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "ait", "eps", "epsf"]; + +impl Libraries { + /// Keep `doc`, the document loaded library `id` was read from, for its pattern swatches; `None` + /// forgets the one kept for `id`. + fn set_pattern_doc(&mut self, id: &str, doc: Option>) { + match doc { + Some(doc) => self.pattern_docs.insert(id.to_string(), doc), + None => self.pattern_docs.remove(id), + }; + } + + /// The document holding the patterns of loaded library `id`'s pattern swatches. + pub fn pattern_doc(&self, id: &str) -> Option> { + self.pattern_docs.get(id).cloned() + } + + /// The document holding the pattern of swatch `w`, when `w` is one of a loaded library's own + /// pattern swatches (a library panel draws them from it). Only the libraries that have pattern + /// swatches are looked at, each by the address ranges of its swatch lists. + pub fn pattern_source(&self, w: &Swatch) -> Option> { + let Paint::Pattern { pattern, .. } = &w.paint else { return None }; + let at = std::ptr::from_ref(w); + let holds = |v: &[Swatch]| v.as_ptr_range().contains(&at); + let own = |lib: &SwatchLibrary| holds(&lib.swatches) || lib.groups.iter().any(|g| holds(&g.swatches)); + let (_, doc) = self.pattern_docs.iter().find(|(id, _)| self.extra.iter().any(|e| e.info.id == **id && own(&e.lib)))?; + Some(doc.clone()).filter(|d| d.pattern(pattern).is_some()) + } +} + /// A library file the save commands write ([`Libraries::write`]). pub(crate) enum FileData { /// Text (`.vcswatches`, `.gpl`, CSS, `.vcstyles`), returned as `data`. @@ -646,6 +681,12 @@ pub fn library_swatches(s: &Session, key: &str) -> Option> { Some(library(s, key)?.1.iter().filter(own).cloned().collect()) } +/// The document holding the pattern of library swatch `w`: a built-in pattern library's or a loaded +/// library's own pattern swatch (a library panel draws them from it). +pub fn pattern_source(s: &Session, w: &Swatch) -> Option> { + patternlib::swatch_source(w).or_else(|| s.swatch_libraries.pattern_source(w)) +} + /// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "" or null). /// A `limitTo` that is not a string, such as `5`, names no library. pub(crate) fn limit_param(s: &Session, p: &Value, cmd: &str) -> Result> { @@ -694,13 +735,17 @@ fn list(s: &mut Session, _: &Value) -> Result { } /// The document's swatches `names` (swatches or colour groups; empty: all) as a library named -/// `name`, without None and patterns. -fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, cmd: &str) -> Result { +/// `name`, without None, and without pattern swatches unless `patterns`. +fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, patterns: bool, cmd: &str) -> Result { if let Some(n) = names.iter().find(|n| !d.swatch_name_taken(n)) { return Err(bad(cmd, format!("no swatch or colour group `{n}`"))); } let want = |n: &str| names.is_empty() || names.iter().any(|x| x == n); - let savable = |w: &&Swatch| matches!(w.paint, Paint::Solid { .. } | Paint::Gradient(_)); + let savable = |w: &&Swatch| match w.paint { + Paint::Solid { .. } | Paint::Gradient(_) => true, + Paint::Pattern { .. } => patterns, + _ => false, + }; let swatches = d.swatches.iter().filter(savable).filter(|w| want(&w.name)).cloned().collect(); let groups = d .swatch_groups @@ -724,7 +769,7 @@ fn save(s: &mut Session, p: &Value) -> Result { let names = names_param(p, C)?; let st = s.doc()?; let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string); - let lib = document_library(&st.doc, &names, name, C)?; + let lib = document_library(&st.doc, &names, name, false, C)?; let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?; let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) }; let mut out = json!({"format": format.id(), "count": lib.iter().filter(|w| format.holds(&w.paint)).count()}); @@ -734,21 +779,44 @@ fn save(s: &mut Session, p: &Value) -> Result { fn load(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.load"; + // The document a library with pattern swatches was read from, which holds their patterns. + let mut patterns = None; let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| { // A library file, or a document whose swatches become the library. if palette_io::sniff_bytes(bytes) { - palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)) - } else { - let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; - if loaded.preview_only { - return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); - } - document_library(&loaded.doc, &[], stem(file).to_string(), C) + return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)); } + let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; + if loaded.preview_only { + return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); + } + // A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches. + let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc); + let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; + if defaults || lib.is_empty() { + return Err(bad(C, format!("`{file}` has no swatches of its own"))); + } + if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) { + patterns = Some(Arc::new(loaded.doc)); + } + Ok(lib) })?; + if info.category == "loaded" { + s.swatch_libraries.set_pattern_doc(&info.id, patterns); + } Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } +/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new +/// document's are. +fn has_only_default_swatches(d: &vectorcraft_doc::Document) -> bool { + use vectorcraft_color::cms::Model; + [Model::Rgb, Model::Cmyk].into_iter().any(|model| { + let (swatches, groups) = default_swatches(model); + d.swatches[..] == swatches[..] && d.swatch_groups[..] == groups[..] + }) +} + fn get(s: &mut Session, p: &Value) -> Result { let (info, lib) = library_param(s, p, "swatch.library.get")?; let ungrouped = lib.swatches.iter().map(|w| swatch_json(w, None)); @@ -772,6 +840,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.copyToUser"; let (info, lib) = library_param(s, p, C)?; let (info, lib, copied) = match info.category { + "loaded" if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) => { + return Err(bad(C, format!("`{}` has pattern swatches, which a .vcswatches file can't hold", info.name))); + } "loaded" => { let native = |lib: &SwatchLibrary| palette_io::write(lib, PaletteFormat::Native).map_err(|e| bad(C, e)); s.swatch_libraries.copy_to_user(&info.id, PaletteFormat::Native.id(), native, C)? @@ -811,6 +882,22 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result Option { + let Paint::Pattern { pattern, xf } = &w.paint else { return None }; + let paint = Paint::Pattern { pattern: target.to_string(), xf: *xf }; + let named = |n: &str| { + w.name == *pattern + || n == w.name + || n.strip_prefix(w.name.as_str()) + .and_then(|r| r.strip_prefix(' ')) + .is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit())) + }; + d.swatches_iter().find(|x| x.paint == paint && named(&x.name)).map(|x| x.name.clone()) +} + /// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch). fn taken_names(d: &vectorcraft_doc::Document) -> HashSet { let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name)); @@ -840,8 +927,9 @@ fn add(s: &mut Session, p: &Value) -> Result { let focus = switch_or(p, "focus", true, C)?; let picked = picked(&lib, &names_param(p, C)?, C)?; // Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the - // same pattern) are reused, not added again. - let patterns = patternlib::library_doc(&info.id); + // same pattern) are reused, not added again. The patterns are in a built-in pattern library's + // document, or in the document a loaded library was read from. + let patterns = patternlib::library_doc(&info.id).or_else(|| s.swatch_libraries.pattern_doc(&info.id)); let d = &s.doc()?.doc; // 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. @@ -851,7 +939,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } let there = |w: &Swatch| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { - patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &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, @@ -873,32 +961,64 @@ fn add(s: &mut Session, p: &Value) -> Result { let added: Vec<(String, String)> = if fresh.is_empty() { vec![] } else { - s.edit("Add to Swatches", |d, _| { + let (added, reused) = 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![]; // Each library group goes into one document group: the group of that name the document // already had, or one made here. let before = d.swatch_groups.len(); let mut placed: Vec<(&str, usize)> = vec![]; let mut taken = taken_names(d); + // The swatches the patterns imported in this call brought with their art: (library + // name, document name). + let mut brought: Vec<(String, String)> = vec![]; for (group, w) in fresh { - if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { + 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. - let target = patternlib::import(d, src, pattern)?; - let name = match patternlib::pattern_swatch(d, &target) { - Some(name) => name, - None => { - let name = d.free_swatch_name(&target); - d.swatches.push(Swatch { name: name.clone(), paint: pattern_paint(&target), global: false, spot: false }); - name - } - }; - out.push((w.name.clone(), name)); + // 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. + let had = taken_names(d); + let (target, colors) = patternlib::import(d, src, pattern)?; + brought.extend(colors); + if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { + reused.push((w.name.clone(), name)); + taken = taken_names(d); + continue; + } + let made = patternlib::pattern_swatch(d, &target).filter(|n| !had.contains(n)); + if let Some(made) = &made { + d.swatches.retain(|x| x.name != *made); + } taken = taken_names(d); - continue; - } - let name = free_in(&mut taken, &w.name); - let sw = Swatch { name: name.clone(), ..(*w).clone() }; + let name = match made { + Some(made) if w.name == *pattern => made, + None if w.name == *pattern => d.free_swatch_name(&target), + _ => free_in(&mut taken, &w.name), + }; + taken.insert(name.clone()); + // The library swatch's placement of its pattern is kept. + let paint = match &w.paint { + Paint::Pattern { xf, .. } => Paint::Pattern { pattern: target, xf: *xf }, + _ => pattern_paint(&target), + }; + (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); + 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)) + }); + match moved { + Some(sw) => (sw.name.clone(), sw), + None => { + let name = free_in(&mut taken, &w.name); + (name.clone(), Swatch { name, ..(*w).clone() }) + } + } + }; match group { Some(g) => { let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i); @@ -919,8 +1039,10 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } - Ok(out) - })? + Ok((out, reused)) + })?; + existing.extend(reused); + 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)}); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index dbf32eba7c..fdcd554991 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -300,6 +300,191 @@ fn another_documents_swatches_load_as_a_library() { assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err()); } +/// Three pattern swatches of another document that paint one pattern, one of them turned, load as +/// three library swatches and come into a document as three swatches of one pattern, each with its +/// own name and placement. +#[test] +fn another_documents_pattern_swatches_of_one_pattern_add_as_separate_swatches() { + use std::sync::Arc; + let turned = vectorcraft_geom::Affine::rotate(0.5); + let mut s = session(); + s.edit("Pattern", |d, _| { + let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)); + let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art()); + 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(dot)]) }); + let swatch = |name: &str, xf| vectorcraft_color::Swatch { + name: name.into(), + paint: Paint::Pattern { pattern: "Dots".into(), xf }, + global: false, + spot: false, + }; + d.swatches.push(swatch("Tiles", vectorcraft_geom::Affine::IDENTITY)); + d.swatches.push(swatch("More tiles", vectorcraft_geom::Affine::IDENTITY)); + d.swatches.push(swatch("Turned tiles", turned)); + 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})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "More tiles", "Turned tiles"]})); + assert_eq!(r["added"], json!(["Tiles", "More tiles", "Turned tiles"]), "{r}"); + let d = doc(&s); + assert_eq!(d.patterns.iter().filter(|p| p.name.starts_with("Dots")).count(), 1, "one pattern"); + let xf = |name: &str| match d.swatch(name).map(|w| &w.paint) { + Some(Paint::Pattern { pattern, xf }) if pattern == "Dots" => Some(*xf), + _ => None, + }; + assert_eq!((xf("Tiles"), xf("Turned tiles")), (Some(vectorcraft_geom::Affine::IDENTITY), Some(turned))); + let again = run(&mut s, "swatch.library.add", json!({"library": id})); + assert_eq!(again["added"], json!([]), "{again}"); +} + +/// A library swatch named after its pattern, added in one call after another swatch of that pattern +/// with the same placement, stands for the swatch just added: it is listed as existing, not added +/// again. +#[test] +fn a_pattern_swatch_named_after_its_pattern_reuses_one_added_in_the_same_call() { + use std::sync::Arc; + let mut s = session(); + s.edit("Pattern", |d, _| { + let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)); + let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art()); + 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(dot)]) }); + for name in ["Tiles", "Dots"] { + let paint = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + d.swatches.push(vectorcraft_color::Swatch { name: name.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": "Dots.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", "Dots"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles"]), &json!(["Tiles"])), "{r}"); + let d = doc(&s); + 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}"); +} + +/// A global color that a library pattern's art links to, added in the same call after the pattern +/// swatch, is the swatch the pattern brought with it: it is added once, not again as a numbered +/// copy, and goes into the library swatch's color group. +#[test] +fn a_color_a_pattern_brings_is_not_added_twice_in_one_call() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#123456", "global": true})); + s.edit("Pattern", |d, _| { + let ink = Paint::Solid { color: Color::rgb8(0x12, 0x34, 0x56), 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 }); + // `Ink` goes into a color group of its own. + let i = d.swatches.iter().position(|w| w.name == "Ink").unwrap(); + let ink = d.swatches.remove(i); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Inks".into(), swatches: vec![ink] }); + 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(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Inks"]})); + let d = doc(&s); + let inks: Vec<&str> = d.swatches_iter().filter(|w| w.name.starts_with("Ink")).map(|w| w.name.as_str()).collect(); + assert_eq!(inks, ["Ink"], "{r}"); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink"]), &json!([])), "{r}"); + let group = d.swatch_groups.iter().find(|g| g.name == "Inks").map(|g| g.swatches.iter().map(|w| w.name.as_str()).collect::>()); + assert_eq!(group, Some(vec!["Ink"]), "{r}"); + assert!(d.swatches.iter().all(|w| w.name != "Ink"), "{r}"); +} + +/// A library pattern whose art links to a global color that the document has under the same name +/// in another color keeps the library's color: the color comes in under a free name ("Ink 2") and +/// the pattern links to it, as the color added in the same call does, and the document's own color +/// is left as it was. Adding the pattern again finds it. +#[test] +fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_another_color() { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + let mut s = session(); + run(&mut 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(&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": ["Tiles", "Ink"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles", "Ink 2"]), &json!([])), "{r}"); + let d = doc(&s); + let hex = |n: &str| d.swatch(n).and_then(|w| w.paint.color()).map(|c| c.to_hex()); + assert_eq!((hex("Ink"), hex("Ink 2")), (Some("#ff0000".to_string()), Some("#0000ff".to_string())), "{r}"); + let fill = d.pattern("Squares").unwrap().art[0].appearance.fill_paint(); + let Paint::Solid { color, swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") }; + assert_eq!((swatch.as_deref(), color.to_hex()), (Some("Ink 2"), "#0000ff".to_string()), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a7292f03ca..2d475cf2c7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6315,6 +6315,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no target object has an opacity mask: select one or give `id` no hi ha cap objecte de destinació amb màscara d’opacitat: seleccioneu-ne un o doneu `id` @msg no threaded text selected no hi ha cap text encadenat seleccionat @msg no user library folder here aquí no hi ha cap carpeta de biblioteca d’usuari +@msg `{file}` has no swatches of its own `{file}` no té mostres pròpies +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` té mostres de motius, que un fitxer .vcswatches no pot contenir @msg no user workspace `{from}` no hi ha l’espai de treball d’usuari `{from}` @msg node {_1} is not text el node {_1} no és text @msg node {_1} is on a locked artboard el node {_1} és en un tauler bloquejat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index e9b422caf5..39472c054b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8420,6 +8420,8 @@ breakText Glyphs Glyfy @msg `{f}` is the copy of a document open now `{f}` je kopie právě otevřeného dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` není formát, který lze zapisovat (viz document.formats) @msg `{id}` isn't a loaded library `{id}` není načtená knihovna +@msg `{file}` has no swatches of its own `{file}` nemá žádné vlastní vzorky +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` obsahuje vzorkové položky vzorníku, které soubor .vcswatches nepojme @msg `{key}` has no colours `{key}` neobsahuje žádné barvy @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` obsahuje více než {MAX_EDIT_WORDS} slov @msg `{key}` is a design name `{key}` je název návrhu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 914d1da89d..9a3f61f97f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1279,6 +1279,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{f}` is the copy of a document open now `{f}` er kopien af et dokument, der er åbent nu @msg `{id}` is no writable format (see document.formats) `{id}` er ikke et skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` er ikke et indlæst bibliotek +@msg `{file}` has no swatches of its own `{file}` har ingen egne farveprøver +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mønsterprøver, som en .vcswatches-fil ikke kan indeholde @msg `{key}` has no colours `{key}` har ingen farver @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` indeholder mere end {MAX_EDIT_WORDS} ord @msg `{key}` is a design name `{key}` er et designnavn diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 79f565baf7..a01e3071f5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8168,6 +8168,8 @@ breakText Glyphs Glyphen @msg `{f}` is the copy of a document open now `{f}` ist die Kopie eines gerade geöffneten Dokuments @msg `{id}` is no writable format (see document.formats) `{id}` ist kein beschreibbares Format (siehe document.formats) @msg `{id}` isn't a loaded library `{id}` ist keine geladene Bibliothek +@msg `{file}` has no swatches of its own `{file}` hat keine eigenen Farbfelder +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` enthält Musterfelder, die eine .vcswatches-Datei nicht aufnehmen kann @msg `{key}` has no colours `{key}` hat keine Farben @msg `{key}` is a design name `{key}` ist ein Designname @msg `{key}` is a design name or a list of them `{key}` ist ein Designname oder eine Liste davon diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e2f972c708..f2e97e5140 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5113,6 +5113,8 @@ digits Malayalam Μαλαγιάλαμ @msg no target object has an opacity mask: select one or give `id` κανένα αντικείμενο-στόχος δεν έχει μάσκα αδιαφάνειας: επιλέξτε ένα ή δώστε `id` @msg no threaded text selected δεν έχει επιλεγεί συνδεδεμένο κείμενο @msg no user library folder here δεν υπάρχει φάκελος βιβλιοθήκης χρήστη εδώ +@msg `{file}` has no swatches of its own το `{file}` δεν έχει δικά του δείγματα χρωμάτων +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold το `{_1}` έχει δείγματα μοτίβου, που ένα αρχείο .vcswatches δεν μπορεί να περιέχει @msg no user workspace `{from}` δεν υπάρχει χώρος εργασίας χρήστη `{from}` @msg node {_1} is not text ο κόμβος {_1} δεν είναι κείμενο @msg node {_1} is on a locked artboard ο κόμβος {_1} βρίσκεται σε κλειδωμένο πίνακα σχεδίασης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3b42c05008..f7a2acda25 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5159,6 +5159,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg no target object has an opacity mask: select one or give `id` ningún objeto de destino tiene máscara de opacidad: selecciona uno o indica `id` @msg no threaded text selected no hay texto enlazado seleccionado @msg no user library folder here aquí no hay ninguna carpeta de bibliotecas de usuario +@msg `{file}` has no swatches of its own `{file}` no tiene muestras propias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tiene muestras de motivo, que un archivo .vcswatches no puede contener @msg no user workspace `{from}` no existe el espacio de trabajo de usuario `{from}` @msg node {_1} is not text el nodo {_1} no es texto @msg node {_1} is on a locked artboard el nodo {_1} está en una mesa de trabajo bloqueada diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 9ddb41a011..a367bb5de3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5383,6 +5383,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no target object has an opacity mask: select one or give `id` millään kohdeobjektilla ei ole peittävyysmaskia: valitse sellainen tai anna `id` @msg no threaded text selected ketjutettua tekstiä ei ole valittu @msg no user library folder here täällä ei ole käyttäjäkirjastokansiota +@msg `{file}` has no swatches of its own tiedostossa `{file}` ei ole omia värimalleja +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold kirjastossa `{_1}` on kuviomalleja, joita .vcswatches-tiedosto ei voi sisältää @msg no user workspace `{from}` ei käyttäjän työtilaa `{from}` @msg node {_1} is not text solmu {_1} ei ole tekstiä @msg node {_1} is on a locked artboard solmu {_1} on lukitulla piirtoalustalla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index cd11fded76..8619ca5f5a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8280,6 +8280,8 @@ breakText Glyphs Glyphes @msg `{f}` is the copy of a document open now `{f}` est la copie d’un document actuellement ouvert @msg `{id}` is no writable format (see document.formats) `{id}` n’est pas un format inscriptible (voir document.formats) @msg `{id}` isn't a loaded library `{id}` n’est pas une bibliothèque chargée +@msg `{file}` has no swatches of its own `{file}` n’a pas de nuances propres +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` contient des nuances de motif, qu’un fichier .vcswatches ne peut pas contenir @msg `{key}` has no colours `{key}` ne contient aucune couleur @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contient plus de {MAX_EDIT_WORDS} mots @msg `{key}` is a design name `{key}` est un nom de motif diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 081d8d2048..1147ca07b1 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6242,6 +6242,8 @@ antiAlias Sharp शार्प @msg `{id}` is no writable format (see document.formats) `{id}` लिखने योग्य फ़ॉर्मैट नहीं है (document.formats देखें) @msg `{id}` is not a colour adjustment `{id}` एक रंग समायोजन नहीं है @msg `{id}` isn't a loaded library `{id}` एक लोड लाइब्रेरी नहीं है +@msg `{file}` has no swatches of its own `{file}` में अपने कोई स्वॉचेस नहीं हैं +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` में पैटर्न स्वॉचेस हैं, जिन्हें .vcswatches फ़ाइल नहीं रख सकती @msg `{k}.family` is required `{k}.family` की आवश्यकता है @msg `{k}` is a number 0..1 `{k}` एक नंबर 0..1 है। @msg `{k}` is true or false `{k}` true या false है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 331941e3fd..b55f86fc3c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8290,6 +8290,8 @@ breakText Glyphs Glifák @msg `{f}` is the copy of a document open now egy most megnyitott dokumentum másolata: `{f}` @msg `{id}` is no writable format (see document.formats) nem írható formátum: `{id}` (lásd: document.formats) @msg `{id}` isn't a loaded library nem betöltött könyvtár: `{id}` +@msg `{file}` has no swatches of its own nincsenek saját színminták: `{file}` +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold mintázatszínmintákat tartalmaz, amelyeket egy .vcswatches fájl nem tud tárolni: `{_1}` @msg `{key}` has no colours `{key}`: nincsenek benne színek @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`: több mint {MAX_EDIT_WORDS} szót tartalmaz @msg `{key}` is a design name `{key}`: diagramminta neve diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f11b6a4219..817eb15095 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8219,6 +8219,8 @@ breakText Glyphs Glifi @msg `{f}` is the copy of a document open now `{f}` è la copia di un documento aperto in questo momento @msg `{id}` is no writable format (see document.formats) `{id}` non è un formato scrivibile (vedi document.formats) @msg `{id}` isn't a loaded library `{id}` non è una libreria caricata +@msg `{file}` has no swatches of its own `{file}` non ha campioni propri +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` ha campioni motivo, che un file .vcswatches non può contenere @msg `{key}` has no colours `{key}` non ha colori @msg `{key}` is a design name `{key}` è il nome di un design @msg `{key}` is a design name or a list of them `{key}` è il nome di un design o un elenco di nomi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 5ae580fca7..0f9f9ca631 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7373,6 +7373,8 @@ axis Y Axis Y 軸 @msg `{f}` is the copy of a document open now `{f}` は現在開いているドキュメントのコピーです @msg `{id}` is no writable format (see document.formats) `{id}` は書き出せる形式ではありません (document.formats を参照) @msg `{id}` isn't a loaded library `{id}` は読み込まれているライブラリではありません +@msg `{file}` has no swatches of its own `{file}` には独自のスウォッチがありません +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` にはパターンスウォッチがあり、.vcswatches ファイルには保存できません @msg `{key}` has no colours `{key}` にカラーがありません @msg `{key}` is a design name `{key}` にはデザイン名を指定してください @msg `{key}` is a design name or a list of them `{key}` にはデザイン名またはそのリストを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 54900f9ba5..c617cc882d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -409,6 +409,8 @@ @msg `{f}` is the copy of a document open now `{f}` ახლა გახსნილი დოკუმენტის ასლია @msg `{id}` is no writable format (see document.formats) `{id}` ჩაწერადი ფორმატი არ არის (იხ. document.formats) @msg `{id}` isn't a loaded library `{id}` ჩატვირთული ბიბლიოთეკა არ არის +@msg `{file}` has no swatches of its own `{file}`-ს საკუთარი ფერის ნიმუშები არ აქვს +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`-ს აქვს პატერნის ნიმუშები, რომლებსაც .vcswatches ფაილი ვერ შეინახავს @msg `{key}` has no colours `{key}`: ფერები არ არის @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS}-ზე მეტ სიტყვას შეიცავს @msg `{key}` is a design name `{key}` არის დიზაინის სახელი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 120e3725f6..692d1573d9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8017,6 +8017,8 @@ breakText Glyphs 글리프 @msg `{f}` is the copy of a document open now `{f}`은(는) 지금 열려 있는 문서의 복사본입니다 @msg `{id}` is no writable format (see document.formats) `{id}`은(는) 기록할 수 있는 형식이 아닙니다(document.formats 참조) @msg `{id}` isn't a loaded library `{id}`은(는) 불러온 라이브러리가 아닙니다 +@msg `{file}` has no swatches of its own `{file}`에 자체 견본이 없습니다 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`에 패턴 견본이 있어 .vcswatches 파일에 담을 수 없습니다 @msg `{key}` has no colours `{key}`에 색상이 없습니다 @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`에 단어가 {MAX_EDIT_WORDS}개보다 많습니다 @msg `{key}` is a design name `{key}`은(는) 디자인 이름입니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4d27a4a053..e3fdb0170e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6261,6 +6261,8 @@ imageTrace Outline Contour @msg `{f}` is the copy of a document open now `{f}` is de kopie van een document dat nu geopend is @msg `{id}` is no writable format (see document.formats) `{id}` is geen schrijfbare indeling (zie document.formats) @msg `{id}` isn't a loaded library `{id}` is geen geladen bibliotheek +@msg `{file}` has no swatches of its own `{file}` heeft geen eigen stalen +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` heeft patroonstalen, die een .vcswatches-bestand niet kan bevatten @msg `{key}` has no colours `{key}` heeft geen kleuren @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` bevat meer dan {MAX_EDIT_WORDS} woorden @msg `{key}` is a design name `{key}` is de naam van een ontwerp diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 707c46b26e..fc6aac4932 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8458,6 +8458,8 @@ breakText Glyphs Glify @msg `{f}` is the copy of a document open now `{f}` to kopia otwartego teraz dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` nie jest formatem z możliwością zapisu (patrz document.formats) @msg `{id}` isn't a loaded library `{id}` nie jest wczytaną biblioteką +@msg `{file}` has no swatches of its own `{file}` nie ma własnych próbek +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` zawiera próbki wzorków, których plik .vcswatches nie może przechować @msg `{key}` has no colours `{key}` nie zawiera kolorów @msg `{key}` is a design name `{key}` to nazwa wzoru @msg `{key}` is a design name or a list of them `{key}` to nazwa wzoru lub lista takich nazw diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 03d7f77082..d9cdb4f2a4 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8482,6 +8482,8 @@ swatch Yellow Green Verde-amarelado @msg `{f}` is the copy of a document open now `{f}` é a cópia de um documento aberto agora @msg `{id}` is no writable format (see document.formats) `{id}` não é um formato gravável (veja document.formats) @msg `{id}` isn't a loaded library `{id}` não é uma biblioteca carregada +@msg `{file}` has no swatches of its own `{file}` não tem amostras próprias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tem amostras de padrão, que um arquivo .vcswatches não pode conter @msg `{key}` has no colours `{key}` não tem cores @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contém mais de {MAX_EDIT_WORDS} palavras @msg `{key}` is a design name `{key}` é o nome de um projeto diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 54f2357e2d..bfd8bcd8c4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8403,6 +8403,8 @@ shape Open Открытый @msg `{f}` is the copy of a document open now `{f}` — копия документа, открытого сейчас @msg `{id}` is no writable format (see document.formats) `{id}` не является форматом для записи (см. document.formats) @msg `{id}` isn't a loaded library `{id}` не является загруженной библиотекой +@msg `{file}` has no swatches of its own в `{file}` нет собственных образцов +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold в `{_1}` есть образцы узоров, которые файл .vcswatches не может хранить @msg `{key}` has no colours в `{key}` нет цветов @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` содержит больше {MAX_EDIT_WORDS} слов @msg `{key}` is a design name `{key}` — имя дизайна diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5dcf9abdca..5efa50628a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7977,6 +7977,8 @@ digits Hindi Hindi @msg `{file}` is over {_1} MB `{file}` är större än {_1} MB @msg `{id}` is no writable format (see document.formats) `{id}` är inget skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` är inte ett inläst bibliotek +@msg `{file}` has no swatches of its own `{file}` har inga egna färgrutor +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mönsterprover, som en .vcswatches-fil inte kan innehålla @msg `{k}.family` is required `{k}.family` är obligatoriskt @msg `{k}` is a number 0..1 `{k}` är ett tal 0..1 @msg `{k}` is true or false `{k}` är true eller false diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 88adae991f..32ecccff44 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7757,6 +7757,8 @@ axis Y Axis Y ekseni @msg `{f}` is the copy of a document open now `{f}` şu anda açık olan bir belgenin kopyası @msg `{id}` is no writable format (see document.formats) `{id}` yazılabilir bir biçim değil (bkz. document.formats) @msg `{id}` isn't a loaded library `{id}` yüklenmiş bir kütüphane değil +@msg `{file}` has no swatches of its own `{file}` dosyasının kendi renk örnekleri yok +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` desen örnekleri içeriyor ve bir .vcswatches dosyası bunları tutamaz @msg `{key}` has no colours `{key}` renk içermiyor @msg `{key}` is a design name `{key}` bir tasarım adıdır @msg `{key}` is a design name or a list of them `{key}` bir tasarım adı veya tasarım adları listesidir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6d78c620d6..253ece7b39 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8021,6 +8021,8 @@ breakText Glyphs Гліфи @msg `{f}` is the copy of a document open now `{f}` — це копія документа, відкритого зараз @msg `{id}` is no writable format (see document.formats) `{id}` не є форматом, доступним для запису (див. document.formats) @msg `{id}` isn't a loaded library `{id}` не є завантаженою бібліотекою +@msg `{file}` has no swatches of its own у `{file}` немає власних зразків +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold у `{_1}` є зразки візерунків, яких файл .vcswatches не може містити @msg `{key}` has no colours `{key}` не містить кольорів @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` містить понад {MAX_EDIT_WORDS} слів @msg `{key}` is a design name `{key}` — це назва дизайну diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6d51bc5965..09bd7d6bf1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5517,6 +5517,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg no target object has an opacity mask: select one or give `id` không có đối tượng đích có mặt nạ độ mờ: hãy chọn hoặc cung cấp `id` @msg no threaded text selected chưa chọn văn bản liên kết @msg no user library folder here không có thư mục thư viện người dùng ở đây +@msg `{file}` has no swatches of its own `{file}` không có mẫu màu riêng +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` có mẫu họa tiết, mà tệp .vcswatches không thể chứa @msg no user workspace `{from}` không có không gian làm việc người dùng `{from}` @msg node {_1} is not text nút {_1} không phải là văn bản @msg node {_1} is on a locked artboard nút {_1} nằm trên bảng vẽ bị khóa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 852ffca760..b11024656b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8446,6 +8446,8 @@ breakText Glyphs 字形 @msg `{f}` is the copy of a document open now `{f}` 是当前已打开文档的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可写入的格式 (参见 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已载入的库 +@msg `{file}` has no swatches of its own `{file}` 没有自己的色板 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有图案色板,.vcswatches 文件无法保存 @msg `{key}` has no colours `{key}` 中没有颜色 @msg `{key}` is a design name `{key}` 是设计名称 @msg `{key}` is a design name or a list of them `{key}` 是一个设计名称或设计名称的列表 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5c0a8af013..961562644a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8375,6 +8375,8 @@ breakText Glyphs 字符 @msg `{f}` is the copy of a document open now `{f}` 是目前開啟文件的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可寫入的格式 (請參閱 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已載入的資料庫 +@msg `{file}` has no swatches of its own `{file}` 沒有自己的色票 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有圖樣色票,.vcswatches 檔案無法儲存 @msg `{key}` has no colours `{key}` 沒有顏色 @msg `{key}` is a design name `{key}` 是設計名稱 @msg `{key}` is a design name or a list of them `{key}` 是設計名稱或設計名稱的清單 diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index fdfb2f7c3b..01c3af49a2 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -576,7 +576,7 @@ fn set(app: &mut VectorcraftApp, panel: &str, mut params: Value) { /// (symbol and brush libraries: any document). pub(crate) fn library_pick_filters(kind: &str) -> Vec<(&'static str, &'static [&'static str])> { match kind { - super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_EXTS).collect(), + super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_PICK_EXTS).collect(), super::graphic_styles::GraphicStyleLibraries::KIND => fileio::library_open_filters("Graphic Style Libraries", &[STYLES_EXT]).collect(), _ => fileio::builtin_open_filters().collect(), } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 7b70844dcc..da789a9944 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,7 +14,7 @@ use vectorcraft_color::libraries::{BuiltinLibrary, GRADIENT_LIBRARIES, SWATCH_LI use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, GradientKind, Paint, Swatch, SwatchLibrary}; use vectorcraft_doc::Document; -use vectorcraft_engine::cmd::patternlib::{self, PATTERN_LIBRARIES}; +use vectorcraft_engine::cmd::patternlib::PATTERN_LIBRARIES; use vectorcraft_engine::cmd::swatchlib; use super::library_panel::{self, LibraryKind, LibraryRef, Row}; diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 864f6ae7e0..d5722e6354 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -3,7 +3,7 @@ use super::dnd::selection; use super::tiles::{describe, global_mark, list_icons, pattern_thumb_in}; use super::{ Arc, BuiltinLibrary, GRADIENT_LIBRARIES, Item, LibraryKind, LibraryRef, PATTERN_LIBRARIES, Rect, Row, SWATCH_LIBRARIES, Swatch, SwatchLibrary, - Ui, Value, VectorcraftApp, json, library_panel, menu_item, patternlib, swatch_tile, swatchlib, + Ui, Value, VectorcraftApp, json, library_panel, menu_item, swatch_tile, swatchlib, }; fn library_refs(libs: Vec) -> Vec { @@ -97,10 +97,10 @@ impl LibraryKind for SwatchLibraries { } out } - fn draw(_: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { + fn draw(app: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { swatch_tile(ui, r, &w.paint, selected, hovered); - // A built-in pattern library's pattern, drawn from the library. - if let Some(src) = patternlib::swatch_source(w) { + // A pattern library's pattern, or a loaded library's, drawn from the library. + if let Some(src) = swatchlib::pattern_source(&app.session, w) { pattern_thumb_in(&src, ui, r.shrink(1.0), &w.paint); } if w.global { diff --git a/docs/mcp.md b/docs/mcp.md index efcdc592f6..c4a9779fe9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5016,10 +5016,18 @@ spot or process swatches and keeps their color groups. A color book (such as a P CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the same extension and bytes as one there, loads as that User Defined library (category `user`). +From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches +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 +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". The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` +(`.epsf`) files as well as the library files. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` -as `.vcswatches`) under a name no file there has, and lists it as User Defined from then on; until the app -quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` +as `.vcswatches`; a library with pattern swatches is refused) under a name no file there has, and lists it as User +Defined from then on; until the app quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` when the folder already held the same file). Without a user library folder the command is disabled. These commands refuse a parameter of the wrong form with an error that names it: `library`, `apply`, `path`, `data`, `dataBase64`, `format` and `name` must be strings, `names` must be a list of names, and `focus`, `replace` and `user` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bf34a32491..5272ed37e0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1970,6 +1970,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 `.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`).