From 6024f86da12b123b80efd621b24c74573f1b32e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 15:05:54 -0800 Subject: [PATCH 001/189] Artwork Cleanup: Empty Text and Off-Artboard Art leave type that clips art A clipping path hides the art outside it. Empty Text removed empty type that clips a clipping group, and Off-Artboard Art removed type that clips a layer from off every artboard, so the art they hid showed. Both now leave type that is a clipping path, as the other kinds already did, also when the clipping path itself is selected. Docs: docs/mcp.md (Artwork Cleanup kinds table). --- .../engine/src/cmd/addons/cleanup/checks.rs | 13 ++++-- crates/engine/src/cmd/addons/cleanup/tests.rs | 43 +++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup/checks.rs b/crates/engine/src/cmd/addons/cleanup/checks.rs index c3abd029be..4b03f0e433 100644 --- a/crates/engine/src/cmd/addons/cleanup/checks.rs +++ b/crates/engine/src/cmd/addons/cleanup/checks.rs @@ -120,12 +120,12 @@ impl Kind { let removable = !place.clips && !is_guide_or_clip(n); let gone = |is: bool| is.then(Vec::new); match self { - Kind::EmptyText => gone(matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())), + Kind::EmptyText => gone(removable && matches!(&n.kind, NodeKind::Text(t) if t.plain_text().trim().is_empty())), Kind::StrayPoints => gone(removable && matches!(&n.kind, NodeKind::Path { path, .. } if path.anchor_count() <= 1)), Kind::Unpainted => gone(removable && !place.in_compound && is_shape(n) && !is_painted(&n.appearance)), Kind::ZeroOpacity => gone(removable && !place.in_compound && n.opacity <= 0.0), Kind::DuplicateObjects => gone(removable && duplicates_the_one_below(cx.d, n)), - Kind::OffArtboard => gone(place.top && !is_guide_or_clip(n) && off_artboards(cx, n)), + Kind::OffArtboard => gone(place.top && removable && off_artboards(cx, n)), Kind::NeedlessGroups => needless_group(n), Kind::NeedlessCompounds => needless_compound(n), Kind::NeedlessClipGroups => needless_clip_group(cx, n), @@ -175,7 +175,9 @@ fn objects<'a>(d: &'a Document, scope: &Scope) -> Vec<(&'a Node, Place)> { let top = Place { top: true, ..Place::default() }; match scope { Scope::Document => d.layers.iter().for_each(|l| visit(l, top, &mut out)), - Scope::Objects(ids) => ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, top, &mut out)), + Scope::Objects(ids) => { + ids.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, Place { clips: is_clipping_path(d, n.id), ..top }, &mut out)) + } } let editable = d.editable(); out.retain(|(n, _)| editable(n.id)); @@ -202,6 +204,11 @@ fn visit<'a>(n: &'a Node, place: Place, out: &mut Vec<(&'a Node, Place)>) { } } +/// Is `id` the clipping path of its group or layer? +fn is_clipping_path(d: &Document, id: NodeId) -> bool { + d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips)) +} + /// A group that stands for live or generated art: its members aren't loose art to clean. fn is_generated(n: &Node) -> bool { let e = n.extras(); diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index d02e1e4c09..2860d39e78 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -226,6 +226,49 @@ fn each_check_finds_and_fixes_its_issue_and_leaves_clean_art_alone() { } } +/// The pixel at (100, 100) of the document drawn on white. +fn pixel(s: &Session) -> [u8; 4] { + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 300, vectorcraft_geom::Affine::IDENTITY, &opts).pixel(100, 100) +} + +/// A clipping path hides the art outside it: empty type that clips a group, and type off every +/// artboard that clips a layer, stay, and the art stays hidden. +#[test] +fn clipping_type_stays_with_the_art_it_hides() { + const WHITE: [u8; 4] = [255, 255, 255, 255]; + let mut s = session(); + let art = rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 60, "y": 80, "text": " ", "size": 40})).unwrap()); + select(&mut s, &[art, t]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + select(&mut s, &[]); + assert_eq!(pixel(&s), WHITE); + assert_eq!(found(&mut s, "emptyText", "document"), 0); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + select(&mut s, &[t]); + assert_eq!(found(&mut s, "emptyText", "selection"), 0, "the clipping path selected"); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0); + assert!(node(&s, t).is_some()); + assert_eq!(pixel(&s), WHITE); + + let mut s = session(); + rect(&mut s, 50.0, 50.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": -300, "y": -300, "text": "Clip", "size": 40})).unwrap()); + s.execute("layer.clippingMask.toggle", &json!({})).unwrap(); + select(&mut s, &[]); + assert_eq!(pixel(&s), WHITE); + assert_eq!(found(&mut s, "offArtboard", "document"), 0); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "document"})).unwrap()["total"], 0); + select(&mut s, &[t]); + assert_eq!(found(&mut s, "offArtboard", "selection"), 0, "the clipping path selected"); + assert_eq!(s.execute("addon.cleanup.fix", &json!({"scope": "selection"})).unwrap()["total"], 0); + assert!(node(&s, t).is_some()); + assert_eq!(pixel(&s), WHITE); +} + /// Type set twice in the same place (from a PDF, or for a fake bold) is a duplicate within a point: /// Show selects the upper copy and Fix removes it. Other text, or the same text further off, stays. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..20a3f2720a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5936,12 +5936,12 @@ envelopes, graphs, symbols), are left out. | Kind | Finds | Fix | |---|---|---| -| `emptyText` | Text with no characters, or only spaces | Removes it | +| `emptyText` | Text with no characters, or only spaces (not clipping paths) | Removes it | | `strayPoints` | Paths of one anchor (not clipping paths) | Removes them | | `unpainted` | Paths and compound paths with no fill and no stroke | Removes them | | `zeroOpacity` | Objects at 0 % opacity | Removes them | | `duplicateObjects` | A path stacked directly on an identical one (geometry, paint, opacity), or type stacked directly on the same type (text, styles, paint) within 1 pt of it | Removes the upper one | -| `offArtboard` | Top-level objects that touch no artboard | Removes them | +| `offArtboard` | Top-level objects that touch no artboard (not clipping paths) | Removes them | | `duplicateAnchors` | Neighbouring anchors within 0.01 pt | Merges them | | `tinyHandles` | Handles shorter than 0.01 pt | Retracts them | | `collinearAnchors` | Corner anchors on a straight run (turning by a sine of 0.005 or less) | Removes them | From 387197c037a57e6ad68ac85cc67116d6a2d63aa3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:28:09 -0800 Subject: [PATCH 002/189] Separations Preview: Gamut Check counts colors in the singular and the plural Gamut Check reported "1 colour(s) are out of the CMYK gamut". It now reports "1 color is out of the CMYK gamut", "3 colors are out of the CMYK gamut" and "All colors are within the CMYK gamut", and the status bar shows them in the interface language through new @msg and @msgplural rows in every catalog. The plain catalog rows for the old British text are removed, since the status bar does not read them. --- crates/ui-egui/src/i18n/bg.tsv | 3 ++- crates/ui-egui/src/i18n/bs.tsv | 3 ++- crates/ui-egui/src/i18n/ca.tsv | 3 ++- crates/ui-egui/src/i18n/cs.tsv | 3 ++- crates/ui-egui/src/i18n/da.tsv | 3 ++- crates/ui-egui/src/i18n/de.tsv | 3 ++- crates/ui-egui/src/i18n/el.tsv | 3 ++- crates/ui-egui/src/i18n/es.tsv | 3 ++- crates/ui-egui/src/i18n/fi.tsv | 3 ++- crates/ui-egui/src/i18n/fr.tsv | 3 ++- crates/ui-egui/src/i18n/hu.tsv | 3 ++- crates/ui-egui/src/i18n/id.tsv | 3 ++- crates/ui-egui/src/i18n/it.tsv | 3 ++- crates/ui-egui/src/i18n/ja.tsv | 3 ++- crates/ui-egui/src/i18n/ka.tsv | 3 ++- crates/ui-egui/src/i18n/ko.tsv | 3 ++- crates/ui-egui/src/i18n/nl.tsv | 3 ++- crates/ui-egui/src/i18n/pl.tsv | 3 ++- crates/ui-egui/src/i18n/pt-br.tsv | 3 ++- crates/ui-egui/src/i18n/ru.tsv | 3 ++- crates/ui-egui/src/i18n/sv.tsv | 3 ++- crates/ui-egui/src/i18n/tests.rs | 23 +++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 3 ++- crates/ui-egui/src/i18n/uk.tsv | 3 ++- crates/ui-egui/src/i18n/vi.tsv | 3 ++- crates/ui-egui/src/i18n/zh-hans.tsv | 3 ++- crates/ui-egui/src/i18n/zh-hant.tsv | 3 ++- crates/ui-egui/src/panels/separations.rs | 12 ++++++++++-- docs/target-app-parity.md | 1 + 29 files changed, 86 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f3f6cbfbb6..bf1a723622 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -151,7 +151,6 @@ All Artwork Above Всички графични елементи отгоре All Caps Всички главни букви All Categories Всички категории - All colours are within the CMYK gamut Всички цветове са в CMYK цветовата гама All on Active Artboard Всички на активната работна област All on Same Layers Всички на същите слоеве All printer's marks Всички печатарски марки @@ -4409,6 +4408,8 @@ axis Both И двете @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Копиран е CSS кодът на {n} обект|Копиран е CSS кодът на {n} обекта @msgplural Downloaded {n} file|Downloaded {n} files Изтеглен е {n} файл|Изтеглени са {n} файла @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Експортиран е {n} файл в {folder}|Експортирани са {n} файла в {folder} +@msg All colors are within the CMYK gamut Всички цветове са в CMYK цветовата гама +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} цвят е извън CMYK цветовата гама|{n} цвята са извън CMYK цветовата гама @msg Unembedded to {_1} Извадено от вграждане в {_1} @msg Reset {_1} Нулирано: {_1} @msg Sent to {_1} Изпратено към {_1} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7efa9c0e7..956524aab3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1895,7 +1895,6 @@ digits Malayalam Malajalam Smart Guides (⌘U) Pametne vodilice (⌘U) Snap Options Opcije hvatanja Type: Vrsta: - All colours are within the CMYK gamut Sve boje su unutar CMYK gamuta Assign: Dodijeli: Color Settings Postavke boja Gamut Check Provjera gamuta @@ -4811,6 +4810,8 @@ imageTrace Outline Obris @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopiran je CSS {n} objekta|Kopiran je CSS {n} objekta|Kopiran je CSS {n} objekata @msgplural Downloaded {n} file|Downloaded {n} files Preuzeta je {n} datoteka|Preuzete su {n} datoteke|Preuzeto je {n} datoteka @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Izvezena je {n} datoteka u {folder}|Izvezene su {n} datoteke u {folder}|Izvezeno je {n} datoteka u {folder} +@msg All colors are within the CMYK gamut Sve boje su unutar CMYK gamuta +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} boja je izvan CMYK gamuta|{n} boje su izvan CMYK gamuta|{n} boja je izvan CMYK gamuta @msg Unembedded to {_1} Ugrađivanje poništeno u {_1} @msg Reset {_1} Vrati na početno: {_1} @msg Sent to {_1} Poslano na {_1} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd6172d6a6..d555bc2a03 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -249,7 +249,6 @@ All Artwork Above Tot l’art superior All Caps Totes majúscules All Categories Totes les categories - All colours are within the CMYK gamut Tots els colors són dins de la gamma CMYK All in One Folder Tot en una carpeta All Layers Totes les capes All on Active Artboard Tot al tauler actiu @@ -5341,6 +5340,8 @@ digits Malayalam Malaiàlam @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects S’ha copiat el CSS de {n} objecte|S’ha copiat el CSS de {n} objectes @msgplural Downloaded {n} file|Downloaded {n} files S’ha baixat {n} fitxer|S’han baixat {n} fitxers @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} S’ha exportat {n} fitxer a {folder}|S’han exportat {n} fitxers a {folder} +@msg All colors are within the CMYK gamut Tots els colors són dins de la gamma CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} color és fora de la gamma CMYK|{n} colors són fora de la gamma CMYK @msg Reload the page to go on (changes not saved yet may be lost). Recarrega la pàgina per continuar (els canvis encara no desats es poden perdre). @msg Replace Spine: select a blend and a path Substitueix l’espina: selecciona una fusió i un traçat @msg replace: the object to replace was changed or deleted replace: l’objecte que s’havia de substituir s’ha canviat o suprimit diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 34c7f4e035..2093e072d0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1921,7 +1921,6 @@ digits Malayalam Malajálamské Smart Guides (⌘U) Chytrá vodítka (⌘U) Snap Options Možnosti přichytávání Type: Typ: - All colours are within the CMYK gamut Všechny barvy jsou v gamutu CMYK Assign: Přiřadit: Color Settings Nastavení barev Gamut Check Kontrola gamutu @@ -4851,6 +4850,8 @@ imageTrace Outline Obrys @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Zkopírováno CSS {n} objektu|Zkopírováno CSS {n} objektů|Zkopírováno CSS {n} objektů @msgplural Downloaded {n} file|Downloaded {n} files Stažen {n} soubor|Staženy {n} soubory|Staženo {n} souborů @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exportován {n} soubor do {folder}|Exportovány {n} soubory do {folder}|Exportováno {n} souborů do {folder} +@msg All colors are within the CMYK gamut Všechny barvy jsou v gamutu CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} barva je mimo gamut CMYK|{n} barvy jsou mimo gamut CMYK|{n} barev je mimo gamut CMYK @msg Unembedded to {_1} Vložení zrušeno, uloženo do: {_1} @msg Reset {_1} Obnoveno: {_1} @msg Sent to {_1} Odesláno do {_1} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5a23913424..06c7829677 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1726,7 +1726,6 @@ digits Malayalam Malayalam Smart Guides (⌘U) Smarte hjælpelinjer (⌘U) Snap Options Fastgørelsesindstillinger Type: Type: - All colours are within the CMYK gamut Alle farver er inden for CMYK-farveomfanget Assign: Tildel: Color Settings Farveindstillinger Gamut Check Farveomfangskontrol @@ -4505,6 +4504,8 @@ imageTrace Outline Kontur @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopierede CSS fra {n} objekt|Kopierede CSS fra {n} objekter @msgplural Downloaded {n} file|Downloaded {n} files Downloadede {n} fil|Downloadede {n} filer @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Eksporterede {n} fil til {folder}|Eksporterede {n} filer til {folder} +@msg All colors are within the CMYK gamut Alle farver er inden for CMYK-farveomfanget +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} farve er uden for CMYK-farveomfanget|{n} farver er uden for CMYK-farveomfanget @msg Unembedded to {_1} Fjernede indlejring til {_1} @msg Reset {_1} Nulstillede {_1} @msg Sent to {_1} Sendte til {_1} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 101bbefac6..4c2b629c7d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -140,7 +140,6 @@ All Artwork Above Gesamte Grafik darüber All Caps Großbuchstaben All Categories Alle Kategorien - All colours are within the CMYK gamut Alle Farben liegen im CMYK-Farbumfang All on Active Artboard Alles auf der aktiven Zeichenfläche All on Same Layers Alles auf denselben Ebenen All printer's marks Alle Druckermarken @@ -4460,6 +4459,8 @@ theme Appearance Erscheinungsbild @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS von {n} Objekt kopiert|CSS von {n} Objekten kopiert @msgplural Downloaded {n} file|Downloaded {n} files {n} Datei heruntergeladen|{n} Dateien heruntergeladen @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} Datei nach {folder} exportiert|{n} Dateien nach {folder} exportiert +@msg All colors are within the CMYK gamut Alle Farben liegen im CMYK-Farbumfang +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} Farbe liegt außerhalb des CMYK-Farbumfangs|{n} Farben liegen außerhalb des CMYK-Farbumfangs @msg Unembedded to {_1} Einbettung aufgehoben, gespeichert unter {_1} @msg Reset {_1} {_1} zurückgesetzt @msg Sent to {_1} An {_1} gesendet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e704faade5..7cc3d3c18c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -145,7 +145,6 @@ All Artwork Above Όλα τα γραφικά στοιχεία παραπάνω All Caps Όλα κεφαλαία All Categories Όλες οι κατηγορίες - All colours are within the CMYK gamut Όλα τα χρώματα βρίσκονται εντός της χρωματικής γκάμας CMYK All on Active Artboard Όλα στον ενεργό πίνακα σχεδίασης All on Same Layers Όλα στα ίδια επίπεδα All printer's marks Όλα τα σημάδια εκτύπωσης @@ -4493,6 +4492,8 @@ digits Malayalam Μαλαγιάλαμ @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Αντιγράφηκαν οι κανόνες CSS από {n} αντικείμενο|Αντιγράφηκαν οι κανόνες CSS από {n} αντικείμενα @msgplural Downloaded {n} file|Downloaded {n} files Έγινε λήψη {n} αρχείου|Έγινε λήψη {n} αρχείων @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Εξήχθη {n} αρχείο στον φάκελο {folder}|Εξήχθησαν {n} αρχεία στον φάκελο {folder} +@msg All colors are within the CMYK gamut Όλα τα χρώματα βρίσκονται εντός της χρωματικής γκάμας CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} χρώμα βρίσκεται εκτός της χρωματικής γκάμας CMYK|{n} χρώματα βρίσκονται εκτός της χρωματικής γκάμας CMYK @msg Unembedded to {_1} Καταργήθηκε η ενσωμάτωση στο {_1} @msg Reset {_1} Επαναφορά {_1} @msg Sent to {_1} Στάλθηκε στο {_1} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4ebddbe9a9..da29f385eb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -165,7 +165,6 @@ All Artwork Above Toda la ilustración superior All Caps Shiftculas All Categories Todas las categorías - All colours are within the CMYK gamut Todos los colores están dentro de la gama CMYK All on Active Artboard Todo en la mesa de trabajo activa All on Same Layers Todo en las mismas capas All printer's marks Todas las marcas de impresora @@ -4545,6 +4544,8 @@ axis Both Ambos @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Se copió el CSS de {n} objeto|Se copió el CSS de {n} objetos @msgplural Downloaded {n} file|Downloaded {n} files Se descargó {n} archivo|Se descargaron {n} archivos @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Se exportó {n} archivo a {folder}|Se exportaron {n} archivos a {folder} +@msg All colors are within the CMYK gamut Todos los colores están dentro de la gama CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} color está fuera de la gama CMYK|{n} colores están fuera de la gama CMYK @msg Unembedded to {_1} Se desincrustó en {_1} @msg Reset {_1} Se restableció {_1} @msg Sent to {_1} Se envió a {_1} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7042b21f22..ed94877b69 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1882,7 +1882,6 @@ digits Malayalam Malajalam Smart Guides (⌘U) Älykkäät apuviivat (⌘U) Snap Options Tartunta-asetukset Type: Tyyppi: - All colours are within the CMYK gamut Kaikki värit ovat CMYK-väriavaruuden sisällä Assign: Määritä: Color Settings Väriasetukset Gamut Check Väriavaruuden tarkistus @@ -4753,6 +4752,8 @@ imageTrace Outline Ääriviiva @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopioitiin {n} objektin CSS|Kopioitiin {n} objektin CSS @msgplural Downloaded {n} file|Downloaded {n} files Ladattiin {n} tiedosto|Ladattiin {n} tiedostoa @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Vietiin {n} tiedosto kansioon {folder}|Vietiin {n} tiedostoa kansioon {folder} +@msg All colors are within the CMYK gamut Kaikki värit ovat CMYK-väriavaruuden sisällä +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} väri on CMYK-väriavaruuden ulkopuolella|{n} väriä on CMYK-väriavaruuden ulkopuolella @msg Unembedded to {_1} Upotus purettiin kohteeseen {_1} @msg Reset {_1} Palautettiin oletukseksi {_1} @msg Sent to {_1} Lähetettiin kohteeseen {_1} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 48eb621eb9..3bf7a3da8f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -166,7 +166,6 @@ All Artwork Above Toute l’illustration au-dessus All Caps Tout en capitales All Categories Toutes les catégories - All colours are within the CMYK gamut Toutes les couleurs sont dans la gamme CMJN All on Active Artboard Tout sur le plan de travail actif All on Same Layers Tout sur les mêmes calques All printer's marks Tous les repères d’impression @@ -4535,6 +4534,8 @@ axis Both Les deux @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS de {n} objet copié|CSS de {n} objets copié @msgplural Downloaded {n} file|Downloaded {n} files {n} fichier téléchargé|{n} fichiers téléchargés @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} fichier exporté vers {folder}|{n} fichiers exportés vers {folder} +@msg All colors are within the CMYK gamut Toutes les couleurs sont dans la gamme CMJN +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} couleur est hors de la gamme CMJN|{n} couleurs sont hors de la gamme CMJN @msg Unembedded to {_1} Incorporation annulée vers {_1} @msg Reset {_1} {_1} réinitialisé @msg Sent to {_1} Envoyé à {_1} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 81f9482631..d551ba5fa2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -236,7 +236,6 @@ All Artwork Above Az összes fölötte lévő grafika All Caps Csupa nagybetű All Categories Összes kategória - All colours are within the CMYK gamut Minden szín a CMYK-színtartományon belül van All Layers Összes réteg All on Active Artboard Az összes az aktív rajztáblán All on Same Layers Az összes ugyanazokon a rétegeken @@ -5037,6 +5036,8 @@ imageTrace Outline Körvonal @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS másolva, objektumok: {n} @msgplural Downloaded {n} file|Downloaded {n} files Letöltött fájlok: {n} @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exportált fájlok: {n}, mappa: {folder} +@msg All colors are within the CMYK gamut Minden szín a CMYK-színtartományon belül van +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} szín a CMYK-színtartományon kívül van @msg Reload the page to go on (changes not saved yet may be lost). A folytatáshoz töltsd újra az oldalt (a még nem mentett módosítások elveszhetnek). @msg Replace Spine: select a blend and a path Gerinc cseréje: jelölj ki egy összemosást és egy útvonalat @msg Reset {_1} Visszaállítva: {_1} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 89633ae991..b1a6a6b838 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1726,7 +1726,6 @@ digits Malayalam Malayalam Smart Guides (⌘U) Panduan cerdas (⌘U) Snap Options Opsi snap Type: Jenis: - All colours are within the CMYK gamut Semua warna berada dalam gamut CMYK Assign: Tetapkan: Color Settings Pengaturan warna Gamut Check Pemeriksaan gamut @@ -4505,6 +4504,8 @@ imageTrace Outline Kontur @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Berhasil menyalin CSS dari {n} objek @msgplural Downloaded {n} file|Downloaded {n} files Berhasil mengunduh {n} file @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Berhasil mengekspor {n} file ke {folder} +@msg All colors are within the CMYK gamut Semua warna berada dalam gamut CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} warna berada di luar gamut CMYK @msg Unembedded to {_1} Gambar tersemat dilepas ke {_1} @msg Reset {_1} {_1} diatur ulang @msg Sent to {_1} Dikirim ke {_1} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6acfaf3c9a..a00301d770 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -165,7 +165,6 @@ All Artwork Above Tutta la grafica soprastante All Caps Tutto maiuscolo All Categories Tutte le categorie - All colours are within the CMYK gamut Tutti i colori rientrano nella gamma CMYK All on Active Artboard Tutto nella tavola da disegno attiva All on Same Layers Tutto sugli stessi livelli All printer's marks Tutti i segni di stampa @@ -4586,6 +4585,8 @@ axis Both Entrambi @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Copiato il CSS di {n} oggetto|Copiato il CSS di {n} oggetti @msgplural Downloaded {n} file|Downloaded {n} files Scaricato {n} file|Scaricati {n} file @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Esportato {n} file in {folder}|Esportati {n} file in {folder} +@msg All colors are within the CMYK gamut Tutti i colori rientrano nella gamma CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} colore è fuori dalla gamma CMYK|{n} colori sono fuori dalla gamma CMYK @msg Unembedded to {_1} Incorporamento rimosso, salvato in {_1} @msg Reset {_1} Reimpostato {_1} @msg Sent to {_1} Inviato a {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bf3cd6bd1..5516eed086 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3383,7 +3383,6 @@ gradient-kind Radial 円形 Align center 中央揃え Align left 左揃え Align right 右揃え - All colours are within the CMYK gamut すべてのカラーが CMYK の色域内です Alt Alt Amount 量 Area Type Options エリア内文字オプション @@ -4646,6 +4645,8 @@ swatch Bright Violet ビビッドバイオレット @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects {n} 個のオブジェクトの CSS をコピーしました @msgplural Downloaded {n} file|Downloaded {n} files {n} 個のファイルをダウンロードしました @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} 個のファイルを {folder} に書き出しました +@msg All colors are within the CMYK gamut すべてのカラーが CMYK の色域内です +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個のカラーが CMYK の色域外です @msg Unembedded to {_1} 埋め込みを解除して {_1} に保存しました @msg no swatch library `{l}` (see swatch.library.list) スウォッチライブラリ `{l}` が見つかりません (swatch.library.list を参照) @msg no user library folder here この環境にはユーザーライブラリフォルダーがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cf411b072c..439229dd9f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1629,7 +1629,6 @@ digits Malayalam მალაიალამური Smart Guides (⌘U) ჭკვიანი დამხმარე ხაზები (⌘U) Snap Options მიბმის პარამეტრები Type: ტიპი: - All colours are within the CMYK gamut ყველა ფერი CMYK-ის გამის ფარგლებშია Assign: მინიჭება: Color Settings ფერის პარამეტრები Gamut Check გამის შემოწმება @@ -4292,6 +4291,8 @@ font-technology Variable ცვლადი @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects კოპირებულია ობიექტის CSS ({n}) @msgplural Downloaded {n} file|Downloaded {n} files ჩამოტვირთულია ფაილი ({n}) @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} ექსპორტირებულია ფაილი ({n}) საქაღალდეში {folder} +@msg All colors are within the CMYK gamut ყველა ფერი CMYK-ის გამის ფარგლებშია +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut CMYK-ის გამის ფარგლებს გარეთაა ფერი ({n}) @msg Unembedded to {_1} ჩაშენება მოხსნილია: {_1} @msg Reset {_1} ჩამოყრილია: {_1} @msg Sent to {_1} გაგზავნილია: {_1} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81f6c600c6..37ea4cc346 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3371,7 +3371,6 @@ gradient-kind Radial 방사형 Align center 가운데 정렬 Align left 왼쪽 정렬 Align right 오른쪽 정렬 - All colours are within the CMYK gamut 모든 색상이 CMYK 색상 범위 안에 있습니다 Alt Alt Amount 양 Area Type Options 영역 문자 옵션 @@ -4573,6 +4572,8 @@ theme Appearance 외관 @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 개체 {n}개의 CSS를 복사했습니다 @msgplural Downloaded {n} file|Downloaded {n} files 파일 {n}개를 다운로드했습니다 @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 파일 {n}개를 {folder}에 내보냈습니다 +@msg All colors are within the CMYK gamut 모든 색상이 CMYK 색상 범위 안에 있습니다 +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut 색상 {n}개가 CMYK 색상 범위를 벗어났습니다 @msg Unembedded to {_1} {_1}에 포함 해제했습니다 @msg no swatch library `{l}` (see swatch.library.list) 견본 라이브러리 `{l}`이(가) 없습니다(swatch.library.list 참조) @msg no user library folder here 여기에는 사용자 라이브러리 폴더가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3448536832..9d8f5b2cfe 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1740,7 +1740,6 @@ digits Malayalam Malayalam Smart Guides (⌘U) Slimme hulplijnen (⌘U) Snap Options Snapopties Type: Type: - All colours are within the CMYK gamut Alle kleuren vallen binnen het CMYK-gamut Assign: Toewijzen: Color Settings Kleurinstellingen Gamut Check Gamutcontrole @@ -4517,6 +4516,8 @@ imageTrace Outline Contour @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS van {n} object gekopieerd|CSS van {n} objecten gekopieerd @msgplural Downloaded {n} file|Downloaded {n} files {n} bestand gedownload|{n} bestanden gedownload @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} bestand geëxporteerd naar {folder}|{n} bestanden geëxporteerd naar {folder} +@msg All colors are within the CMYK gamut Alle kleuren vallen binnen het CMYK-gamut +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kleur valt buiten het CMYK-gamut|{n} kleuren vallen buiten het CMYK-gamut @msg Unembedded to {_1} Extern gemaakt: {_1} @msg Reset {_1} {_1} opnieuw ingesteld @msg Sent to {_1} Verzonden naar {_1} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14825f83cf..7d3505f3ec 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1840,7 +1840,6 @@ digits Malayalam Malajalam Smart Guides (⌘U) Inteligentne linie pomocnicze (⌘U) Snap Options Opcje przyciągania Type: Typ: - All colours are within the CMYK gamut Wszystkie kolory mieszczą się w gamucie CMYK Assign: Przypisz: Color Settings Ustawienia kolorów Gamut Check Sprawdzanie gamutu @@ -4677,6 +4676,8 @@ imageTrace Outline Kontur @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Skopiowano CSS {n} obiektu|Skopiowano CSS {n} obiektów|Skopiowano CSS {n} obiektów @msgplural Downloaded {n} file|Downloaded {n} files Pobrano {n} plik|Pobrano {n} pliki|Pobrano {n} plików @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Wyeksportowano {n} plik do {folder}|Wyeksportowano {n} pliki do {folder}|Wyeksportowano {n} plików do {folder} +@msg All colors are within the CMYK gamut Wszystkie kolory mieszczą się w gamucie CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kolor nie mieści się w gamucie CMYK|{n} kolory nie mieszczą się w gamucie CMYK|{n} kolorów nie mieści się w gamucie CMYK @msg Unembedded to {_1} Wyodrębniono do {_1} @msg Reset {_1} Zresetowano {_1} @msg Sent to {_1} Wysłano do {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 96a31c3e57..607759936a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4116,6 +4116,8 @@ axis Both Ambos @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects CSS de {n} objeto copiado|CSS de {n} objetos copiado @msgplural Downloaded {n} file|Downloaded {n} files {n} arquivo baixado|{n} arquivos baixados @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} arquivo exportado para {folder}|{n} arquivos exportados para {folder} +@msg All colors are within the CMYK gamut Todas as cores estão dentro do gamut CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} cor está fora do gamut CMYK|{n} cores estão fora do gamut CMYK @msg Unembedded to {_1} Desincorporado para {_1} @msg Reset {_1} Redefinir {_1} @msg Sent to {_1} Enviado para {_1} @@ -4355,7 +4357,6 @@ axis Both Ambos Align center Alinhar ao Centro Align left Alinhar à Esquerda Align right Alinhar à Direita - All colours are within the CMYK gamut Todas as cores estão dentro do gamut CMYK Alt Alt Amount Quantidade Area Type Options Opções de Texto de Área diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fdb51b80df..887faee217 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -163,7 +163,6 @@ All Artwork Above Весь рисунок выше All Caps Все прописные All Categories Все категории - All colours are within the CMYK gamut Все цвета входят в цветовой охват CMYK All on Active Artboard Всё на активной монтажной области All on Same Layers Всё на тех же слоях All printer's marks Все типографские метки @@ -4581,6 +4580,8 @@ axis Both Оба @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Скопирован CSS {n} объекта|Скопирован CSS {n} объектов|Скопирован CSS {n} объектов @msgplural Downloaded {n} file|Downloaded {n} files Скачан {n} файл|Скачано {n} файла|Скачано {n} файлов @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Экспортирован {n} файл в {folder}|Экспортировано {n} файла в {folder}|Экспортировано {n} файлов в {folder} +@msg All colors are within the CMYK gamut Все цвета входят в цветовой охват CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} цвет выходит за пределы цветового охвата CMYK|{n} цвета выходят за пределы цветового охвата CMYK|{n} цветов выходят за пределы цветового охвата CMYK @msg Unembedded to {_1} Извлечено в {_1} @msg Reset {_1} Сброшено: {_1} @msg Sent to {_1} Отправлено в {_1} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e2dddf022b..72803496c4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -153,7 +153,6 @@ All Artwork Above All grafik ovanför All Caps Versaler All Categories Alla kategorier - All colours are within the CMYK gamut Alla färger ligger inom CMYK-färgomfånget All on Active Artboard Alla på aktiv rityta All on Same Layers Alla på samma lager All printer's marks Alla tryckmärken @@ -4444,6 +4443,8 @@ axis Both Båda @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Kopierade CSS för {n} objekt|Kopierade CSS för {n} objekt @msgplural Downloaded {n} file|Downloaded {n} files Hämtade {n} fil|Hämtade {n} filer @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Exporterade {n} fil till {folder}|Exporterade {n} filer till {folder} +@msg All colors are within the CMYK gamut Alla färger ligger inom CMYK-färgomfånget +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} färg ligger utanför CMYK-färgomfånget|{n} färger ligger utanför CMYK-färgomfånget @msg Unembedded to {_1} Extraherad till {_1} @msg Reset {_1} Återställ {_1} @msg Sent to {_1} Skickat till {_1} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7e5ca938c6..6c80beb0db 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1528,6 +1528,29 @@ fn messages_with_a_count_take_the_plural_form() { assert_eq!(message(cs, "Packaged 21 files"), "Zabaleno 21 souborů"); } +/// The Gamut Check status line names a count of 1 in the singular and other counts in the plural, +/// and every complete catalog translates it, in the form its plural rule picks. +#[test] +fn gamut_check_status_takes_the_plural_form() { + use crate::panels::separations::gamut_check_status; + assert_eq!(gamut_check_status(0), "All colors are within the CMYK gamut"); + assert_eq!(gamut_check_status(1), "1 color is out of the CMYK gamut"); + assert_eq!(gamut_check_status(3), "3 colors are out of the CMYK gamut"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for n in [0, 1, 3] { + let s = gamut_check_status(n); + assert_ne!(message(lang, &s), s, "{code}: {s}"); + } + } + assert_eq!(message(de(), &gamut_check_status(1)), "1 Farbe liegt außerhalb des CMYK-Farbumfangs"); + assert_eq!(message(de(), &gamut_check_status(3)), "3 Farben liegen außerhalb des CMYK-Farbumfangs"); + let cs = cs(); + assert_eq!(message(cs, &gamut_check_status(1)), "1 barva je mimo gamut CMYK"); + assert_eq!(message(cs, &gamut_check_status(3)), "3 barvy jsou mimo gamut CMYK"); + assert_eq!(message(cs, &gamut_check_status(5)), "5 barev je mimo gamut CMYK"); +} + /// The link, font and export status messages with a count, in English for a count of 1 and of 2. const COUNTED_STATUS_MESSAGES: &[(&str, &str)] = &[ ("1 linked file can't be read here: its preview shows", "2 linked files can't be read here: their previews show"), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9ecf2ccf93..7a60100483 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -150,7 +150,6 @@ All Artwork Above Yukarıdaki Tüm Sanat Eserleri All Caps Tamamı Büyük Harf All Categories Tüm Kategoriler - All colours are within the CMYK gamut Tüm renkler CMYK gamındadır All on Active Artboard Hepsi Aktif Çalışma Yüzeyinde All on Same Layers Hepsi Aynı Katmanlarda All printer's marks Tüm yazıcı işaretleri @@ -4287,6 +4286,8 @@ axis Both Her İkisi @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects {n} nesnenin CSS'si kopyalandı @msgplural Downloaded {n} file|Downloaded {n} files {n} dosya indirildi @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} {n} dosya {folder} klasörüne aktarıldı +@msg All colors are within the CMYK gamut Tüm renkler CMYK gamındadır +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} renk CMYK gamının dışında @msg Unembedded to {_1} {_1}'ye gömülü değil @msg Reset {_1} {_1}'yi sıfırla @msg Sent to {_1} {_1}'ye gönderildi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d348440a2c..007750e663 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -159,7 +159,6 @@ All Artwork Above Весь малюнок вище All Caps Всі великі All Categories Усі категорії - All colours are within the CMYK gamut Усі кольори входять у колірне охоплення CMYK All on Active Artboard Все на активній монтажній області All on Same Layers Все на тих же шарах All printer's marks Усі друкарські мітки @@ -4570,6 +4569,8 @@ axis Both Обидві @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Скопійовано CSS {n} об’єкта|Скопійовано CSS {n} об’єктів|Скопійовано CSS {n} об’єктів @msgplural Downloaded {n} file|Downloaded {n} files Завантажено {n} файл|Завантажено {n} файли|Завантажено {n} файлів @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Експортовано {n} файл до {folder}|Експортовано {n} файли до {folder}|Експортовано {n} файлів до {folder} +@msg All colors are within the CMYK gamut Усі кольори входять у колірне охоплення CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} колір виходить за межі колірного охоплення CMYK|{n} кольори виходять за межі колірного охоплення CMYK|{n} кольорів виходять за межі колірного охоплення CMYK @msg Unembedded to {_1} Вилучено у {_1} @msg Reset {_1} Скинуто: {_1} @msg Sent to {_1} Відправлено до {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 09652ede2b..9e2471f85c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -181,7 +181,6 @@ All Artwork Above Tất cả tác phẩm phía trên All Caps Viết hoa toàn bộ All Categories Tất cả danh mục - All colours are within the CMYK gamut Tất cả màu nằm trong gam CMYK All on Active Artboard Tất cả trên bảng vẽ hiện hoạt All on Same Layers Tất cả trên cùng lớp All printer's marks Tất cả dấu máy in @@ -4691,6 +4690,8 @@ theme Appearance Giao diện @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects Đã sao chép CSS của {n} đối tượng @msgplural Downloaded {n} file|Downloaded {n} files Đã tải xuống {n} tệp @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} Đã xuất {n} tệp vào {folder} +@msg All colors are within the CMYK gamut Tất cả màu nằm trong gam CMYK +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} màu nằm ngoài gam CMYK @msg Reload the page to go on (changes not saved yet may be lost). Tải lại trang để tiếp tục (các thay đổi chưa lưu có thể bị mất). @msg Replace Spine: select a blend and a path Thay thế trục: chọn một đối tượng hòa trộn và một đường dẫn @msg Reset {_1} Đã đặt lại {_1} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 841bd4528a..e89f3a7953 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -115,7 +115,6 @@ All Artwork Above 上方所有图稿 All Caps 全部大写 All Categories 所有类别 - All colours are within the CMYK gamut 所有颜色皆在 CMYK 色域内 All on Active Artboard 当前画板上的所有对象 All on Same Layers 同层上的所有对象 All printer's marks 所有打印机标记 @@ -4363,6 +4362,8 @@ imageTrace Outline 轮廓 @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 已复制 {n} 个对象的 CSS @msgplural Downloaded {n} file|Downloaded {n} files 已下载 {n} 个文件 @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 已将 {n} 个文件导出到 {folder} +@msg All colors are within the CMYK gamut 所有颜色皆在 CMYK 色域内 +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 个颜色超出 CMYK 色域 @msg Unembedded to {_1} 已取消嵌入到 {_1} @msg no swatch library `{l}` (see swatch.library.list) 没有色板库 `{l}` (请参阅 swatch.library.list) @msg no user library folder here 此处没有用户库文件夹 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a515d59a74..e9230ccd93 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -123,7 +123,6 @@ All Artwork Above 上方所有圖稿 All Caps 全部大寫 All Categories 所有類別 - All colours are within the CMYK gamut 所有顏色皆在 CMYK 色域內 All on Active Artboard 作用中工作區域上的全部 All on Same Layers 相同圖層上的全部 All printer's marks 所有印表機標記 @@ -2286,6 +2285,8 @@ file-filter Templates 範本 @msgplural Copied the CSS of {n} object|Copied the CSS of {n} objects 已複製 {n} 個物件的 CSS @msgplural Downloaded {n} file|Downloaded {n} files 已下載 {n} 個檔案 @msgplural Exported {n} file to {folder}|Exported {n} files to {folder} 已將 {n} 個檔案匯出至 {folder} +@msg All colors are within the CMYK gamut 所有顏色皆在 CMYK 色域內 +@msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個顏色超出 CMYK 色域 @msg Unembedded to {_1} 已取消內嵌至 {_1} @msg no swatch library `{l}` (see swatch.library.list) 沒有色票資料庫 `{l}` (請參閱 swatch.library.list) @msg no user library folder here 此處沒有使用者資料庫資料夾 diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index e50db115ea..38cfa604e2 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -122,8 +122,7 @@ fn settings_section(app: &mut VectorcraftApp, ui: &mut Ui) { match app.run("color.gamutCheck", json!({})) { Ok(r) => { let n = r["outOfGamut"].as_array().map_or(0, Vec::len); - app.ui.status = - if n == 0 { "All colours are within the CMYK gamut".into() } else { format!("{n} colour(s) are out of the CMYK gamut") }; + app.ui.status = gamut_check_status(n); } Err(e) => app.ui.status = e, } @@ -142,6 +141,15 @@ fn settings_section(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The status bar's line after Gamut Check finds `n` colors outside the CMYK gamut. +pub(crate) fn gamut_check_status(n: usize) -> String { + if n == 0 { + "All colors are within the CMYK gamut".into() + } else { + crate::i18n::msg_n(n as u64, "{n} color is out of the CMYK gamut", "{n} colors are out of the CMYK gamut", &[]) + } +} + fn proof_section(app: &mut VectorcraftApp, ui: &mut Ui) { let v = proof::view(); widgets::section_header(ui, tl!("Proof Setup")); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..2d552390ab 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -959,6 +959,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). A Cmd/Ctrl-click on the Color panel's spectrum applies Complement and a Cmd/Ctrl+Shift-click applies Invert to the active Fill or Stroke (`paint.complement`, `paint.invert`); with Alt also held, the click recolors the inactive one, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) list them. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. + The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. From d5849d6553e7dc801ac84dcf6cecf9b79102a528 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 16:41:20 -0800 Subject: [PATCH 003/189] Fix #2181: PDF layer forms get real boxes and lose their off-page marks With Create PDF layers on, every layer's form XObject had /BBox [-32767 -32767 32767 32767] and started with an empty clip at x = -32000 that only marked the form while the file was written. Other apps read that as art about 23 m across, and the reporters could not move or place the imported layers. - The marks of layer, overprint and invisible-text forms are removed when the file is finished. - A layer's form gets a box round its art and the page's paper, in whole units. Since the box still covers the page, PDF import skips it as a clip, so sublayers still import as sublayers. --- crates/pdf/src/export.rs | 3 + crates/pdf/src/export/exporter.rs | 1 + crates/pdf/src/export/nodes.rs | 3 +- crates/pdf/src/export/writer.rs | 2 + crates/pdf/src/forms.rs | 121 +++++++++++++++++++++++------- crates/pdf/src/tests/layers.rs | 39 ++++++++++ 6 files changed, 142 insertions(+), 27 deletions(-) diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 529396fce6..71c9ab25de 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -94,6 +94,9 @@ pub(crate) struct Exporter<'a> { layer_index: HashMap, /// The address of the layer whose form is being drawn. in_layer: usize, + /// The paper of the page being drawn, in its drawing space: the box of each layer's form + /// covers it ([`crate::forms::layer_form`]). + paper: Rect, /// Overprinting fills and strokes are drawn as forms marked to overprint. pub overprint: bool, /// An overprinting fill or stroke was drawn so. diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index ac53090f56..a40e272b01 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -45,6 +45,7 @@ impl<'a> Exporter<'a> { layers: false, layer_index: crate::forms::pdf_layers(doc).iter().enumerate().map(|(i, l)| (address(l.node), i)).collect(), in_layer: 0, + paper: Rect::ZERO, symbol_nodes: 0, overprint: false, overprinted: false, diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 8367bef11d..7d063046cb 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -102,7 +102,8 @@ impl Exporter<'_> { { // A PDF layer: hidden layers and sublayers are written too (their group is off). let enclosing = std::mem::replace(&mut self.in_layer, address(n)); - crate::forms::form(s, Mark::Layer(i), |s| self.node(s, n, page, true)); + let paper = self.paper; + crate::forms::layer_form(s, i, paper, |s| self.node(s, n, page, true)); self.in_layer = enclosing; return; } diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index b2ca788eb1..5e7c7e77ab 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -156,6 +156,8 @@ impl Writer { s.push_mask(all); } if fits { + let shown = (sheet.view * sheet.place).inverse().transform_rect_bbox(paper); + ex.paper = if [shown.x0, shown.y0, shown.x1, shown.y1].iter().all(|v| v.is_finite()) { shown.union(r) } else { r }; ex.children(&mut s, &doc.layers, r); } if page_group || cmyk_page_group { diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index e382ccb0fe..4a1d061473 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -4,9 +4,10 @@ //! form is. Marked forms also stay apart (the writer shares identical forms). [`finish`] completes //! them in the written file: a layer's form is drawn as the layer's optional content (`/OC … //! BDC`), an overprinting form sets a graphics state that overprints first, and the text of an -//! invisible form is drawn in rendering mode 3 (neither filled nor stroked). +//! invisible form is drawn in rendering mode 3 (neither filled nor stroked). It also removes the +//! marks, so no form keeps an empty clip far off the page (#2181). -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::io::Read; use craft_pdf::write::backend as krilla; @@ -77,13 +78,30 @@ impl Mark { /// Draw `draw` as a form of its own, marked `mark`. pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface)) { + let (x, y) = mark.at(); + marked(s, mark, [(x + 1.0, y), (x + 1.0, y + 1.0)], draw); +} + +/// Draw `draw` (the art of layer `i` of [`pdf_layers`]) as a form of its own, marked as the +/// layer's. The mark's other two points are the corners of `paper` (the page's paper in the +/// form's drawing space), rounded outwards to whole units: [`finish`] gives the form a box that +/// covers the paper and the art. +pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rect, draw: impl FnOnce(&mut Surface)) { + let corner = |x: f64, y: f64| (x as f32, y as f32); + marked(s, Mark::Layer(i), [corner(paper.x0.floor(), paper.y0.floor()), corner(paper.x1.ceil(), paper.y1.ceil())], draw); +} + +/// Draw `draw` as a form of its own, marked `mark`: an empty clip from the mark's first point +/// through `rest`. +fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(&mut Surface)) { let mut sb = s.stream_builder(); let mut fs = sb.surface(); let (x, y) = mark.at(); let mut pb = PathBuilder::new(); pb.move_to(x, y); - pb.line_to(x + 1.0, y); - pb.line_to(x + 1.0, y + 1.0); + for (x, y) in rest { + pb.line_to(x, y); + } pb.close(); // A form's drawing space is its own: the mark's points are written as they are. if let Some(p) = pb.finish() { @@ -102,8 +120,9 @@ pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface)) const OVERPRINT_GS: &str = "VCop"; /// The prefix of the resource names of the layers' optional content groups (then the index). const LAYER_OC: &str = "VCoc"; -/// The most bytes of a form's content read to find its mark. -const HEAD: u64 = 64; +/// The most bytes of a form's content read to find its mark (a layer's mark holds four more +/// numbers of up to 11 characters each). +const HEAD: u64 = 128; fn bad(why: &str) -> PdfError { PdfError::Write(format!("can't write PDF layers, overprint or invisible text: {why}")) @@ -159,6 +178,31 @@ impl Object<'_> { _ => None, } } + + /// The paper a layer's form's mark gives ([`layer_form`]): its left, top, right and bottom. + fn paper(&self, pdf: &[u8]) -> Option<[i64; 4]> { + let head = self.data(pdf, HEAD)?; + let mut lx = Lexer::at(&head, 0); + let mut word = || match lx.next() { + Some((Tok::Word(w), ..)) => Some(w), + _ => None, + }; + let words = [(); 10].map(|_| word()); + let [Some(b"q"), _, _, Some(b"m"), x0, y0, Some(b"l"), x1, y1, Some(b"l")] = words else { return None }; + Some([x0.and_then(int)?, y0.and_then(int)?, x1.and_then(int)?, y1.and_then(int)?]) + } +} + +/// `content` (a marked form's) without its mark: what follows the mark's `Q`. +fn unmarked(content: &[u8]) -> Option<&[u8]> { + let mut lx = Lexer::at(content, 0); + while let Some((tok, _, end)) = lx.next() { + if let Tok::Word(b"Q") = tok { + let rest = content.get(end..)?; + return rest.get(rest.iter().take_while(|c| c.is_ascii_whitespace()).count()..); + } + } + None } /// The objects of the written file that have a dictionary, by number. @@ -293,7 +337,7 @@ pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bo return Err(bad("an overprinting form can't be read")); }; let mut new = format!("/{OVERPRINT_GS} gs\n").into_bytes(); - new.extend_from_slice(&content); + new.extend_from_slice(unmarked(&content).ok_or_else(|| bad("an overprinting form can't be read"))?); o.rewrite(&mut patch, &new)?; add_resources(&mut patch, res, "ExtGState", &format!("/{OVERPRINT_GS} {gs} 0 R"))?; } @@ -302,15 +346,19 @@ pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bo for (n, _) in marks.iter().filter(|(_, m)| **m == Mark::Invisible) { let Some(o) = objects.get(n) else { continue }; let content = o.data(&pdf, u64::MAX).ok_or_else(|| bad("an invisible text form can't be read"))?; - o.rewrite(&mut patch, &invisible_text(&content).ok_or_else(|| bad("an invisible text form can't be read"))?)?; + let text = unmarked(&content).and_then(invisible_text).ok_or_else(|| bad("an invisible text form can't be read"))?; + o.rewrite(&mut patch, &text)?; } } if layers { - write_layers(&pdf, &xref, &objects, &marks, &mut patch, doc, set)?; + let rewritten = write_layers(&pdf, &xref, &objects, &marks, &mut patch, doc, set)?; for (n, _) in marks.iter().filter(|(_, m)| matches!(m, Mark::Layer(_))) { - if let Some(o) = objects.get(n) { - unbox(&pdf, o, &mut patch)?; + let Some(o) = objects.get(n) else { continue }; + if !rewritten.contains(n) { + let content = o.data(&pdf, u64::MAX).ok_or_else(|| bad("a layer's form can't be read"))?; + o.rewrite(&mut patch, unmarked(&content).ok_or_else(|| bad("a layer's form can't be read"))?)?; } + rebox(&pdf, o, &mut patch)?; } } let pdf = patch.apply(&pdf, &xref)?; @@ -321,7 +369,7 @@ pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bo /// The optional content groups of `doc`'s layers and sublayers ([`pdf_layers`]), the uses of their /// forms marked as their content, and the catalog's `/OCProperties`, listing sublayers under their -/// layers. +/// layers. Returns the content streams it rewrote (a layer's form among them without its mark). fn write_layers( pdf: &[u8], xref: &Xref, @@ -330,7 +378,7 @@ fn write_layers( patch: &mut Patch, doc: &Document, set: &PdfSettings, -) -> Result<(), PdfError> { +) -> Result, PdfError> { // One group per layer, in paint order (bottom first). let layers = pdf_layers(doc); let mut groups: HashMap = HashMap::new(); @@ -357,13 +405,14 @@ fn write_layers( } } // Every content stream drawing layers' forms: the pages' and the forms'. - for o in objects.values() { + let mut rewritten = HashSet::new(); + for (n, o) in objects { let content = match o.dict.get(b"Contents") { - Some(Obj::Ref(c, _)) if o.dict.name(b"Type") == Some(b"Page") => objects.get(c), - _ if o.dict.name(b"Subtype") == Some(b"Form") => Some(o), + Some(Obj::Ref(c, _)) if o.dict.name(b"Type") == Some(b"Page") => objects.get(c).map(|o| (*c, o)), + _ if o.dict.name(b"Subtype") == Some(b"Form") => Some((*n, o)), _ => None, }; - let (Some(content), Some(res)) = (content, resources(objects, o)) else { continue }; + let (Some((number, content)), Some(res)) = (content, resources(objects, o)) else { continue }; let Some(Obj::Dict { entries, .. }) = res.get(b"XObject") else { continue }; let forms: HashMap<&[u8], usize> = entries .iter() @@ -379,8 +428,11 @@ fn write_layers( continue; } let data = content.data(pdf, u64::MAX).ok_or_else(|| bad("a content stream can't be read"))?; - let Some((new, marked)) = mark_layers(&data, &forms) else { continue }; + // A layer's form drawing its sublayers' forms loses its own mark here too. + let data = if marks.contains_key(&number) { unmarked(&data).ok_or_else(|| bad("a layer's form can't be read"))? } else { &data[..] }; + let Some((new, marked)) = mark_layers(data, &forms) else { continue }; content.rewrite(patch, &new)?; + rewritten.insert(number); let entries: String = marked.iter().filter_map(|i| Some(format!("/{LAYER_OC}{i} {} 0 R", groups.get(i)?))).collect(); add_resources(patch, res, "Properties", &entries)?; } @@ -399,24 +451,41 @@ fn write_layers( let root = xref.trailer_ref(pdf, b"/Root").and_then(|n| objects.get(&n)); let Some(Object { dict: Obj::Dict { start, .. }, .. }) = root else { return Err(bad("the written PDF has no catalog")) }; patch.replace(start + 2, start + 2, format!("/OCProperties<>>>", refs(&all)).into_bytes()); - Ok(()) + Ok(rewritten) } -/// A form's box as large as a page can be: the box of a layer's form is only the bounds of its -/// art, and a reader that makes a clipping group of a form's box (as importers do) would gather a -/// layer's art and its sublayers' in one group, which no layer can hold. A box round the whole -/// page clips nothing. +/// A form's box as large as a page can be, for a layer's form whose mark gives no paper. const UNBOXED: &[u8] = b"[-32767 -32767 32767 32767]"; -/// Give the layer's form `o` the [`UNBOXED`] box. -fn unbox(pdf: &[u8], o: &Object<'_>, patch: &mut Patch) -> Result<(), PdfError> { +/// Give the layer's form `o` a box round its art and the paper its mark gives ([`layer_form`]): +/// the box of a layer's form is only the bounds of its art, and a reader that makes a clipping +/// group of a form's box (as importers do) would gather a layer's art and its sublayers' in one +/// group, which no layer can hold. A box round the whole paper clips nothing, and its bounds stay +/// those of the page and the art (#2181). +fn rebox(pdf: &[u8], o: &Object<'_>, patch: &mut Patch) -> Result<(), PdfError> { let Obj::Dict { start, end, .. } = o.dict else { return Err(bad("a layer's form has no dictionary")) }; let dict = pdf.get(start..end).ok_or_else(|| bad("a layer's form can't be read"))?; // The writer writes the box as an array of numbers. let at = dict.windows(5).position(|w| w == b"/BBox").ok_or_else(|| bad("a layer's form has no box"))? + 5; let open = at + dict.get(at..).and_then(|d| d.iter().position(|&c| c == b'[')).ok_or_else(|| bad("a layer's form box isn't an array"))?; let close = open + dict.get(open..).and_then(|d| d.iter().position(|&c| c == b']')).ok_or_else(|| bad("a layer's form box isn't an array"))? + 1; - patch.replace(start + open, start + close, UNBOXED.to_vec()); + let art: Vec = std::str::from_utf8(dict.get(open + 1..close - 1).unwrap_or_default()) + .unwrap_or_default() + .split_ascii_whitespace() + .filter_map(|v| v.parse().ok()) + .collect(); + let new = match (o.paper(pdf), art.as_slice()) { + (Some([x0, y0, x1, y1]), &[a0, b0, a1, b1]) if [a0, b0, a1, b1].iter().all(|v| v.is_finite()) => { + let (a0, a1, b0, b1) = (a0.min(a1), a0.max(a1), b0.min(b1), b0.max(b1)); + // Whole units, outwards (the art's box is written to a few decimals). + let lo = |v: i64, a: f64| (v as f64).min(a.floor()); + let hi = |v: i64, a: f64| (v as f64).max(a.ceil()); + format!("[{} {} {} {}]", lo(x0, a0), lo(y0, b0), hi(x1, a1), hi(y1, b1)).into_bytes() + } + (Some([x0, y0, x1, y1]), _) => format!("[{x0} {y0} {x1} {y1}]").into_bytes(), + _ => UNBOXED.to_vec(), + }; + patch.replace(start + open, start + close, new); Ok(()) } diff --git a/crates/pdf/src/tests/layers.rs b/crates/pdf/src/tests/layers.rs index 05ad63106b..cb5bf9a12e 100644 --- a/crates/pdf/src/tests/layers.rs +++ b/crates/pdf/src/tests/layers.rs @@ -339,6 +339,45 @@ fn overprinting_art_imports_as_it_was_drawn() { } } +/// The `/BBox` of each form of the uncompressed `bytes`, in the order written. +fn form_boxes(bytes: &[u8]) -> Vec { + let text = String::from_utf8_lossy(bytes); + text.split("/Subtype/Form").skip(1).filter_map(|d| Some(d.split("/BBox[").nth(1)?.split(']').next()?.to_string())).collect() +} + +/// #2181: a layer's form has a box round the paper and its art, not one 23 m across, and no +/// form (a layer's, an overprinting one or invisible text's) keeps the empty clip far off the +/// page that marked it while the file was written. +#[test] +fn layer_forms_have_real_boxes_and_no_marks() { + let mut d = overprinting(RED); + // Invisible text (neither fill nor stroke) and art across the paper's left edge. + let l = d.layers[0].id; + let style = CharStyle { size: 24.0, fill: Paint::None, ..Default::default() }; + let t = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(200.0, 40.0), "Hid", style)))); + let past = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-50.0, 10.0, 5.0, 40.0)), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.insert(Some(l), 0, t).unwrap(); + d.insert(Some(l), 0, past).unwrap(); + let mut sub = Node::layer(d.alloc_id(), "Sub", LayerColor::Preset(1)); + if let NodeKind::Layer { children, .. } = &mut sub.kind { + children.push(rect(&mut d, 250.0, BLUE).into()); + } + d.insert(Some(l), 0, sub).unwrap(); + let r = export(&d, json!({"createLayers": true, "compression": {"compressText": false}})); + let text = String::from_utf8_lossy(&r.bytes); + for mark in ["-32000 ", "-32001 ", "-32002 ", "32767"] { + assert!(!text.contains(mark), "{mark} is in the file: {text}"); + } + assert!(text.contains("3 Tr") && text.contains("/VCop gs"), "invisible text and overprint are still written: {text}"); + // The layer's form reaches the art across the left edge; its sublayer's covers the paper. + let boxes = form_boxes(&r.bytes); + assert!(boxes.contains(&"-50 0 300 100".to_string()) && boxes.contains(&"0 0 300 100".to_string()), "{boxes:?}"); + // It still imports as it was drawn: a layer holding its sublayer, no clipping group. + let mut got = vec![]; + tree(&import(&r.bytes).unwrap().layers, 0, &mut got); + assert!(got.contains(&"1 Sub true".to_string()) && got.contains(&format!("2 {:?}", Some(BLUE))), "{got:?}"); +} + #[test] fn pdf_x1a_keeps_overprint() { let r = export(&overprinting(RED), json!({"standard": "pdfX1a", "compatibility": "1.4", "compression": {"compressText": false}})); From ac298b683b22b87f3b354f5df391ba5a21961add Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 17:00:36 -0800 Subject: [PATCH 004/189] Canvas: a drag ends where its button went up When a frame brought pointer moves after the button-up, the canvas ended the drag at the frame's last pointer position. A Rectangle drag stretched to it, a Pencil stroke ran on to it, and dragged art moved there. The release now uses the position the button went up at; the moves after it are hover. --- crates/ui-egui/src/canvas/input.rs | 16 +++++++- crates/ui-egui/src/canvas/tests.rs | 63 ++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 728a38b090..5b45fbe29d 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -117,11 +117,13 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo } else if let Some(d) = drag { // The pointer gone (a pen lifted with its press), the drag ends where it was last seen. let p = pointer.interact_pos().or_else(|| ui.data(|dd| dd.get_temp(drag_pos_id()))).unwrap_or(rect.center()); - let held = if middle_pan { pointer.button_down(egui::PointerButton::Middle) } else { pointer.primary_down() }; + let button = if middle_pan { egui::PointerButton::Middle } else { egui::PointerButton::Primary }; + let held = pointer.button_down(button); if held { drag_held(app, ui, &f, d, p); } else { - drag_released(app, ui, &f, d, p); + // The drag ends where its button went up: the moves after the release in this frame are hover. + drag_released(app, ui, &f, d, release_pos(ui, button).unwrap_or(p)); } } else if let Some(p) = hover_tool && (pointer.is_moving() || mods_changed || !was_over || tool_switched || (context_changed && app.session.tool_wants_rehover())) @@ -550,6 +552,16 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { } } +/// Where `button` went up in this frame, if it did. +fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option { + ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { pos, button: b, pressed: false, .. } if *b == button => Some(*pos), + _ => None, + }) + }) +} + /// Whether Space moves the Zoom tool's marquee in the drag under way ([`zoom_marquee_start`]). fn zoom_space_free_id() -> egui::Id { egui::Id::unique("canvas-zoom-space-free") diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4b59bdb8f6..c5d5327523 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6321,6 +6321,69 @@ fn a_bezier_drag_preview_follows_the_pointer_back_into_the_window_and_to_the_rel assert!(app.session.active().unwrap().interaction.is_none(), "committed"); } +/// A drag ends where its button went up. Pointer moves that come after the release in the same +/// frame are hover: they do not stretch a Rectangle drag, add to a Pencil stroke or move dragged +/// art. +#[test] +fn a_drag_ends_where_the_button_went_up_in_its_frame() { + use egui::{Event, Modifiers}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let last_bounds = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap() + }; + let center = app.canvas_rect.unwrap().center(); + let far = center + vec2(150.0, 100.0); + + app.select_tool("rectangle"); + let a = center - vec2(100.0, 60.0); + let end = a + vec2(80.0, 50.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(a)]); + frame(&mut app, &ctx, vec![button(a, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(40.0, 20.0))]); + frame(&mut app, &ctx, vec![Event::PointerMoved(end), button(end, false), Event::PointerMoved(far)]); + let r = last_bounds(&app); + let want = xf.to_doc(end); + assert!((r.x1 - want.x).abs() < 1e-3 && (r.y1 - want.y).abs() < 1e-3, "the rectangle ends at the release: {r:?}, {want:?}"); + + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pencil"); + let a = center - vec2(100.0, 0.0); + let end = a + vec2(120.0, 0.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(a)]); + frame(&mut app, &ctx, vec![button(a, true)]); + for x in [20.0, 40.0, 60.0] { + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(x, 0.0))]); + } + frame(&mut app, &ctx, vec![Event::PointerMoved(a + vec2(90.0, 0.0)), Event::PointerMoved(end), button(end, false), Event::PointerMoved(far)]); + let r = last_bounds(&app); + let (left, right) = (xf.to_doc(a), xf.to_doc(end)); + assert!((r.x0 - left.x).abs() < 1.0 && (r.x1 - right.x).abs() < 1.0 && r.height() < 1.0, "the stroke ends at the release: {r:?}"); + + app.session.execute("shape.rectangle", &json!({"x": 250, "y": 40, "width": 60, "height": 40})).unwrap(); + app.session.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("selection"); + let before = Rect::new(250.0, 40.0, 310.0, 80.0); + let grab = xf.to_screen(Point::new(280.0, 60.0)); + let to = grab + vec2(30.0, 40.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(grab)]); + frame(&mut app, &ctx, vec![button(grab, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(grab + vec2(10.0, 10.0))]); + frame(&mut app, &ctx, vec![Event::PointerMoved(to), button(to, false), Event::PointerMoved(far)]); + let moved = last_bounds(&app); + let d = xf.to_doc(to) - xf.to_doc(grab); + assert!((moved.x0 - before.x0 - d.x).abs() < 1e-3 && (moved.y0 - before.y0 - d.y).abs() < 1e-3, "the art moves to the release: {moved:?}, {d:?}"); + assert!(app.session.active().unwrap().interaction.is_none(), "committed"); +} + #[test] fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { let ctx = egui::Context::default(); From 0567eaffbf15bb7054d754fa4674954c628c4c02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 17:20:56 -0800 Subject: [PATCH 005/189] Recolor: the Global Adjust sliders change every color at once The Edit tab's color mode menu offers Global Adjust, with Saturation, Brightness, Temperature and Luminosity sliders from -100% to 100% that open at 0%, which changes nothing. One slider changes every recolored color, each one separately, in its own model; the rows keep their new colors and the art previews the change. The Edit tab also shows the color sliders of the selected new color in the other modes. recolor.apply takes globalAdjust {saturation, brightness, temperature, luminosity}. Excluded rows and colors no row holds stay as they are, a rewritten color group takes the same change, and with Limit to Library each row's new color takes it before it snaps to the library. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/color/src/recolor.rs | 142 ++++++++++++++++++++++ crates/engine/src/cmd/recolor.rs | 64 ++++++++-- crates/engine/src/tests/recolor.rs | 115 ++++++++++++++++++ crates/ui-egui/src/dialogs/recolor.rs | 167 ++++++++++++++++++++++---- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/tests/recolor.rs | 67 ++++++++++- docs/control-protocol.md | 7 +- docs/mcp.md | 19 ++- docs/target-app-parity.md | 2 +- 34 files changed, 590 insertions(+), 41 deletions(-) diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index e88f767a5e..53cb12478d 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -255,6 +255,77 @@ pub fn shaded(c: Color, f: f32) -> Color { } } +/// Recolor Artwork's Global Adjust: the same change to every color, by four amounts from -1 to 1 +/// (-100% to +100%), where 0 leaves a color as it is. The steps run in this order: +/// +/// 1. Saturation multiplies HSB saturation by 1 + `saturation` (-1 gives a gray, 1 doubles it). +/// 2. Brightness moves HSB brightness that share of the way to its top (above 0) or to black +/// (below 0). +/// 3. Temperature adds 0.2 × `temperature` to display red and takes as much from blue (warmer +/// above 0, cooler below). +/// 4. Luminosity moves Lab lightness that share of the way to 100 (above 0) or to 0 (below 0), +/// with Lab a and b, and so the Lab hue, kept. +/// +/// The result is in the model of the color it changes, with its components clamped to their +/// ranges. An amount that is not finite counts as 0. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct GlobalAdjust { + pub saturation: f32, + pub brightness: f32, + pub temperature: f32, + pub luminosity: f32, +} + +impl GlobalAdjust { + /// The four amounts, in order, each finite and within -1..=1. + fn amounts(&self) -> [f32; 4] { + [self.saturation, self.brightness, self.temperature, self.luminosity].map(|v| if v.is_finite() { v.clamp(-1.0, 1.0) } else { 0.0 }) + } + + /// Whether every color stays as it is (all four amounts 0). + pub fn is_identity(&self) -> bool { + self.amounts().iter().all(|v| *v == 0.0) + } + + /// `c` with the adjustment, in `c`'s model; `c` itself when [`GlobalAdjust::is_identity`]. + pub fn apply(&self, c: Color) -> Color { + let [sat, bri, temp, lum] = self.amounts(); + if [sat, bri, temp, lum].iter().all(|v| *v == 0.0) { + return c; + } + // `v` moved the share `a` of the way to `top` (a > 0) or to 0 (a < 0). + let toward = |v: f32, a: f32, top: f32| if a >= 0.0 { v + (top - v) * a } else { v * (1.0 + a) }; + let mut out = c; + if sat != 0.0 || bri != 0.0 { + let [h, s, v] = out.to_hsb(); + out = Color::from_hsb(h, (s * (1.0 + sat)).clamp(0.0, 1.0), toward(v.clamp(0.0, 1.0), bri, 1.0)); + } + if temp != 0.0 { + let [r, g, b] = out.to_rgb(); + out = Color::rgb((r + 0.2 * temp).clamp(0.0, 1.0), g.clamp(0.0, 1.0), (b - 0.2 * temp).clamp(0.0, 1.0)); + } + if lum != 0.0 { + let Lab { l, a, b } = match out { + Color::Lab { l, a, b } => Lab::new(l, a, b), + _ => out.to_lab(), + }; + out = Color::lab(toward(l.clamp(0.0, 100.0), lum, 100.0), a, b); + } + clamped(keep_model(c, out)) + } +} + +/// `c` with its components in their ranges: RGB, CMYK and Gray 0..1, Lab lightness 0..100. +fn clamped(c: Color) -> Color { + let u = |v: f32| v.clamp(0.0, 1.0); + match c { + Color::Rgb { r, g, b } => Color::rgb(u(r), u(g), u(b)), + Color::Cmyk { c, m, y, k } => Color::cmyk(u(c), u(m), u(y), u(k)), + Color::Gray { k } => Color::gray(u(k)), + Color::Lab { l, a, b } => Color::lab(l.clamp(0.0, 100.0), a, b), + } +} + /// One row of Recolor Artwork prepared for mapping: its current colours take `to` by `method`. #[derive(Clone, Copy, Debug)] pub struct RowMap { @@ -615,6 +686,77 @@ mod tests { assert!(row.iter().all(|c| kept.map(*c).model() == c.model())); } + fn adjust(saturation: f32, brightness: f32, temperature: f32, luminosity: f32) -> GlobalAdjust { + GlobalAdjust { saturation, brightness, temperature, luminosity } + } + + #[test] + fn global_adjust_at_zero_leaves_every_color_as_it_is() { + let zero = GlobalAdjust::default(); + assert!(zero.is_identity()); + assert!(adjust(f32::NAN, 0.0, f32::INFINITY, 0.0).is_identity(), "amounts that aren't finite count as 0"); + for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.1234, 0.5, 0.0, 0.07), Color::gray(0.4), Color::lab(55.0, 60.5, -40.25)] { + assert_eq!(zero.apply(c), c); + } + assert!(!adjust(0.0, 0.0, 0.0, 0.01).is_identity()); + } + + #[test] + fn global_adjust_saturation_and_brightness_reach_their_ends() { + let c = Color::rgb(0.8, 0.4, 0.2); + let [h, s, v] = c.to_hsb(); + let gray = adjust(-1.0, 0.0, 0.0, 0.0).apply(c).to_hsb(); + assert!(gray[1].abs() < 1e-4 && (gray[2] - v).abs() < 1e-4, "-100% saturation gives a gray as bright: {gray:?}"); + let more = adjust(0.5, 0.0, 0.0, 0.0).apply(c).to_hsb(); + assert!((more[0] - h).abs() < 0.5 && more[1] > s && (more[1] - (s * 1.5).min(1.0)).abs() < 1e-3, "{more:?}"); + assert!(adjust(-1.0, 0.0, 0.0, 0.0).apply(Color::rgb(0.5, 0.5, 0.5)) == Color::rgb(0.5, 0.5, 0.5), "a gray stays gray"); + assert!(adjust(0.0, -1.0, 0.0, 0.0).apply(c).to_hsb()[2] < 1e-4, "-100% brightness is black"); + assert!((adjust(0.0, 1.0, 0.0, 0.0).apply(c).to_hsb()[2] - 1.0).abs() < 1e-4, "+100% brightness is full brightness"); + let half = adjust(0.0, 0.5, 0.0, 0.0).apply(c).to_hsb(); + assert!((half[2] - (v + (1.0 - v) * 0.5)).abs() < 1e-3 && (half[1] - s).abs() < 1e-3, "{half:?}"); + } + + #[test] + fn global_adjust_temperature_warms_and_cools() { + let c = Color::rgb(0.5, 0.5, 0.5); + let warm = adjust(0.0, 0.0, 1.0, 0.0).apply(c).to_rgb(); + let cool = adjust(0.0, 0.0, -1.0, 0.0).apply(c).to_rgb(); + assert!(warm[0] > warm[1] && warm[1] > warm[2], "warmer: more red, less blue {warm:?}"); + assert!(cool[2] > cool[1] && cool[1] > cool[0], "cooler: more blue, less red {cool:?}"); + let edge = adjust(0.0, 0.0, 1.0, 0.0).apply(Color::rgb(1.0, 0.0, 0.0)); + assert_eq!(edge, Color::rgb(1.0, 0.0, 0.0), "clamped at the ends of the channels"); + } + + #[test] + fn global_adjust_luminosity_keeps_the_hue() { + let lab = Color::lab(50.0, 30.0, -20.0); + assert_eq!(adjust(0.0, 0.0, 0.0, 0.5).apply(lab), Color::lab(75.0, 30.0, -20.0), "a Lab color keeps a and b exactly"); + assert_eq!(adjust(0.0, 0.0, 0.0, -0.5).apply(lab), Color::lab(25.0, 30.0, -20.0)); + let c = Color::rgb(0.6, 0.35, 0.3); + let (before, after) = (c.to_lab(), adjust(0.0, 0.0, 0.0, 0.2).apply(c).to_lab()); + assert!(after.l > before.l, "lighter: {after:?}"); + assert!((after.hue() - before.hue()).abs() < 2.0, "hue kept: {} vs {}", after.hue(), before.hue()); + let darkest = adjust(0.0, 0.0, 0.0, -1.0).apply(c).to_lab(); + assert!(darkest.l < before.l * 0.5, "-100% is far darker: {darkest:?}"); + assert_eq!(adjust(0.0, 0.0, 0.0, -1.0).apply(Color::gray(0.4)), Color::gray(1.0), "-100% makes a gray black"); + } + + #[test] + fn global_adjust_keeps_the_model_and_the_ranges() { + let all = adjust(1.0, 1.0, 1.0, 1.0); + for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.2, 0.9, 0.1, 0.3), Color::gray(0.4), Color::lab(55.0, 60.0, -40.0)] { + let out = all.apply(c); + assert_eq!(out.model(), c.model(), "{c:?} → {out:?}"); + let comps: Vec = match out { + Color::Rgb { r, g, b } => vec![r, g, b], + Color::Cmyk { c, m, y, k } => vec![c, m, y, k], + Color::Gray { k } => vec![k], + Color::Lab { l, .. } => vec![l / 100.0], + }; + assert!(comps.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}"); + } + } + #[test] fn palette_snaps_to_the_nearest_colour() { let p = Palette::new([Color::rgb(1.0, 0.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::gray(0.5)]); diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index b1fd2489e9..75b2cc73b6 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeSet, HashMap}; use serde_json::{Value, json}; -use vectorcraft_color::recolor::{ColorKey, Method, Preserve, Rng, RowMap, cluster}; +use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster}; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::swatches::{node_colors, node_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", has_doc, apply ), @@ -224,6 +224,30 @@ fn reduce(s: &mut Session, p: &Value) -> Result { Ok(json!({"map": map, "preserved": kept.iter().map(|u| key_str(&u.color)).collect::>(), "method": method.id()})) } +/// The `globalAdjust` parameter: `{saturation?, brightness?, temperature?, luminosity?}`, each a +/// percentage from -100 to 100 (0 when left out or null), as amounts from -1 to 1. +fn adjust_param(p: &Value, cmd: &str) -> Result { + let given = match p.get("globalAdjust") { + None | Some(Value::Null) => return Ok(GlobalAdjust::default()), + Some(v @ Value::Object(_)) => v, + Some(_) => return Err(bad(cmd, "`globalAdjust` must be an object")), + }; + let amount = |key: &str| -> Result { + let x = super::number_or(given, key, 0.0, cmd)?; + let (min, max) = (-100, 100); + if !(f64::from(min)..=f64::from(max)).contains(&x) { + return Err(bad(cmd, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + Ok((x / 100.0) as f32) + }; + Ok(GlobalAdjust { + saturation: amount("saturation")?, + brightness: amount("brightness")?, + temperature: amount("temperature")?, + luminosity: amount("luminosity")?, + }) +} + /// A current colour of a row: an exact colour, or every colour shown as a hex. enum Match { Key(ColorKey), @@ -370,15 +394,25 @@ struct ColorMap { hexes: HashMap, /// Set when a colour took a new colour of another model in its own model. converted: std::cell::Cell, + /// The Global Adjust every mapped colour takes after its row's new colour. + adjust: GlobalAdjust, } impl ColorMap { /// `links`: the swatch of each of `rows`' new colours (as many as `rows`, or none); `group`: the /// global swatches of the color group being rewritten; `model`: the model rule of a row without - /// its own. - fn new(rows: &[Row], method: Method, model: ModelRule, links: &[Option], group: Vec) -> Self { - let mut out = - Self { rows: vec![], links: vec![], tos: vec![], group, keys: HashMap::new(), hexes: HashMap::new(), converted: Default::default() }; + /// its own; `adjust`: the Global Adjust of each mapped colour. + fn new(rows: &[Row], method: Method, model: ModelRule, links: &[Option], group: Vec, adjust: GlobalAdjust) -> Self { + let mut out = Self { + rows: vec![], + links: vec![], + tos: vec![], + group, + keys: HashMap::new(), + hexes: HashMap::new(), + converted: Default::default(), + adjust, + }; for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) { let Some(to) = r.new_color() else { continue }; let i = out.rows.len(); @@ -387,7 +421,8 @@ impl ColorMap { // Colors that can't link to the swatch take the row's tint of it too. let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint)); out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(r.model.unwrap_or(model) != ModelRule::Keep)); - out.tos.push(to); + // Compared with the group's new colours, which take the adjustment too. + out.tos.push(adjust.apply(to)); out.links.push(link); for m in &r.from { match m { @@ -409,7 +444,7 @@ impl ColorMap { if r.converts(c) { self.converted.set(true); } - r.map(c) + self.adjust.apply(r.map(c)) } /// Recolour a colour that can link to a swatch: a row whose new colour is a global or spot @@ -448,7 +483,7 @@ impl ColorMap { if row.converts(*c) { self.converted.set(true); } - row.map(*c) + self.adjust.apply(row.map(*c)) } }; // A color its row leaves as it is still loses its link to a swatch of the rewritten group @@ -468,9 +503,13 @@ fn apply(s: &mut Session, p: &Value) -> Result { let method = method_param(p, C, Method::Exact)?; let palette = super::swatchlib::limit_param(s, p, C)?; let mut rows = parse_rows(p, C)?; + let adjust = adjust_param(p, C)?; + // With Limit to Library a row's new colour takes the Global Adjust before it snaps, so the art + // still takes the library's colours; otherwise every colour the rows map takes it. + let mapped_adjust = if palette.is_some() { GlobalAdjust::default() } else { adjust }; if let Some(pl) = &palette { for r in &mut rows { - r.to = r.to.map(|c| pl.nearest(c)); + r.to = r.to.map(|c| pl.nearest(adjust.apply(c))); } } // With Limit to Library, a row's new colour is a swatch of the library: the art takes that @@ -510,11 +549,12 @@ fn apply(s: &mut Session, p: &Value) -> Result { .iter() .map(|v| { color_value(v) + .map(|c| adjust.apply(c)) .map(|c| in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))) .ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))) }) .collect::>()?, - None => rows.iter().filter_map(Row::new_color).collect(), + None => rows.iter().filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(), }; let rename = text_param(p, "rename", C)?; let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok(); @@ -553,7 +593,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .collect() }) .unwrap_or_default(); - let map = ColorMap::new(&rows, method, model, &links, kept); + let map = ColorMap::new(&rows, method, model, &links, kept, mapped_adjust); let f = |c: Color| map.map(c); let lf = |c: &mut Color, link: &mut Option, tint: &mut f32| map.map_link(c, link, tint); let changed = Recolor::with_links(scope, &f, &lf).run(d, &ids); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 565405d58e..cadf9314a9 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -721,3 +721,118 @@ fn document_model_converts_the_colours_of_a_group_too() { run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#00ff00"], "model": "document"})); assert!(group(&s).iter().all(|c| c.model() == vectorcraft_color::cms::Model::Cmyk), "{:?}", group(&s)); } + +fn stroke(s: &Session, id: NodeId) -> Color { + s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_paint().color().unwrap() +} + +/// Global Adjust changes every colour the rows recolour, each one separately (the colours of a +/// row of several, fills and strokes alike), in its own model, as one undo step; an excluded +/// row's colours and preserved colours stay. +#[test] +fn global_adjust_changes_every_recolored_color() { + let mut s = session(); + let red = rect(&mut s, json!("#ff0000")); + let pink = rect(&mut s, json!("#ff8080")); + let cmyk = rect(&mut s, json!({"c": 100, "m": 0, "y": 0, "k": 0})); + let kept = rect(&mut s, json!("#00ff00")); + run(&mut s, "paint.setStroke", json!({"ids": [red.0], "color": "#0000ff", "width": 2})); + select_all(&mut s); + let map = json!([ + {"from": ["rgb 255 0 0", "rgb 255 128 128"], "to": "rgb 255 0 0"}, + {"from": ["cmyk 100 0 0 0"], "to": "cmyk 100 0 0 0"}, + {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"}, + {"from": ["rgb 0 255 0"], "to": "rgb 0 255 0", "exclude": true}, + ]); + let undo = s.doc().unwrap().history.undo.len(); + let sat = |c: Color| c.to_hsb()[1]; + let saturations = [fill(&s, red), fill(&s, pink), fill(&s, cmyk), stroke(&s, red)].map(sat); + let r = run(&mut s, "recolor.apply", json!({"map": map, "method": "scaleTints", "globalAdjust": {"saturation": -50}})); + assert_eq!(r["changed"], 4, "three fills and a stroke: {r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let after = [fill(&s, red), fill(&s, pink), fill(&s, cmyk), stroke(&s, red)].map(sat); + for (n, what) in ["red", "pink", "cyan", "the stroke"].iter().enumerate() { + // CMYK reads back through the profile-free conversion, so its saturation is near half, not exact. + assert!((after[n] - saturations[n] * 0.5).abs() < 0.05, "{what} has about half its saturation: {} → {}", saturations[n], after[n]); + } + assert!(close(fill(&s, red), Color::rgb(1.0, 0.5, 0.5)), "{:?}", fill(&s, red)); + assert!(close(fill(&s, pink), Color::rgb(1.0, 0.75, 0.75)), "each colour of a row changes on its own: {:?}", fill(&s, pink)); + assert!(matches!(fill(&s, cmyk), Color::Cmyk { .. }), "a CMYK colour stays CMYK: {:?}", fill(&s, cmyk)); + assert_eq!(fill(&s, kept).to_hex(), "#00ff00", "an excluded row keeps its colours"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(fill(&s, red).to_hex(), "#ff0000"); + assert_eq!(fill(&s, pink).to_hex(), "#ff8080"); + assert_eq!(stroke(&s, red).to_hex(), "#0000ff"); + // Brightness -100 makes every recolored color black; the rows' new colors are taken first. + run(&mut s, "recolor.apply", json!({"map": [{"from": ["#ff0000"], "to": "#00ff00"}], "globalAdjust": {"brightness": -100}})); + assert_eq!(fill(&s, red).to_hex(), "#000000"); + assert_eq!(fill(&s, pink).to_hex(), "#ff8080", "a colour no row holds stays"); +} + +/// Global Adjust at 0 changes nothing, a global swatch's link included, and a non-zero adjustment +/// gives the art the adjusted colour without the link. +#[test] +fn global_adjust_at_zero_keeps_colors_and_links() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Brand", "color": "#2878f0", "global": true})); + let art = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [art.0], "swatch": "Brand"})); + select_all(&mut s); + let link = |s: &Session| match s.doc().unwrap().doc.node(art).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { swatch, .. } => swatch, + p => panic!("a solid fill: {p:?}"), + }; + let before = fill(&s, art); + let zero = json!({"saturation": 0, "brightness": 0, "temperature": 0, "luminosity": 0}); + run(&mut s, "recolor.apply", json!({"map": {"rgb 40 120 240": "rgb 40 120 240"}, "globalAdjust": zero})); + assert_eq!(fill(&s, art), before); + assert_eq!(link(&s).as_deref(), Some("Brand"), "the link stays"); + run(&mut s, "recolor.apply", json!({"map": {"rgb 40 120 240": "rgb 40 120 240"}, "globalAdjust": {"temperature": 50}})); + let [r, _, b] = fill(&s, art).to_rgb(); + let [r0, _, b0] = before.to_rgb(); + assert!(r > r0 && b < b0, "warmer: {:?}", fill(&s, art)); + assert_eq!(link(&s), None, "the adjusted colour is no longer the swatch's"); +} + +/// With Limit to Library each row's new colour takes the Global Adjust and then snaps to the +/// library; a colour group rewritten with the rows' new colours takes the adjustment too. +#[test] +fn global_adjust_with_a_library_and_a_group() { + let mut s = session(); + let art = rect(&mut s, json!("#f01020")); + select_all(&mut s); + run(&mut s, "recolor.apply", json!({"map": {"#f01020": "#f01020"}, "limitTo": "Web Safe 216", "globalAdjust": {"brightness": -100}})); + assert_eq!(fill(&s, art).to_hex(), "#000000", "black, a colour of the library"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "swatch.newGroup", json!({"name": "Theme", "colors": ["#f01020"]})); + run(&mut s, "recolor.apply", json!({"map": [{"from": ["#f01020"], "to": "#f01020"}], "group": "Theme", "globalAdjust": {"saturation": -100}})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + let c = g.swatches[0].paint.color().unwrap(); + assert!(c.to_hsb()[1] < 1e-3, "the group's colour is adjusted: {c:?}"); + assert_eq!(c, fill(&s, art), "as the art is"); +} + +/// `globalAdjust` must be an object of numbers from -100 to 100; a refusal changes nothing and +/// records no undo step. A null counts as left out. +#[test] +fn global_adjust_refuses_params_of_the_wrong_form() { + let mut s = session(); + let art = rect(&mut s, json!("#ff0000")); + select_all(&mut s); + let undo = s.doc().unwrap().history.undo.len(); + let map = json!({"#ff0000": "#ff0000"}); + for (adjust, msg) in [ + (json!(5), "`globalAdjust` must be an object"), + (json!({"saturation": "50"}), "`saturation` must be a number"), + (json!({"brightness": 101}), "`brightness` must be between -100 and 100 (got 101)"), + (json!({"luminosity": -100.5}), "`luminosity` must be between -100 and 100 (got -100.5)"), + ] { + let e = s.execute("recolor.apply", &json!({"map": map, "globalAdjust": adjust})).unwrap_err().to_string(); + assert!(e.contains(msg), "{adjust}: {e}"); + } + assert_eq!(fill(&s, art).to_hex(), "#ff0000", "nothing changed"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + run(&mut s, "recolor.apply", json!({"map": map, "globalAdjust": null})); + run(&mut s, "recolor.apply", json!({"map": map, "globalAdjust": {"saturation": null, "temperature": -100}})); + assert_ne!(fill(&s, art).to_hex(), "#ff0000", "an amount at the end of the range applies"); +} diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 76f3a15e87..1f319ca96e 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -13,7 +13,9 @@ //! library file and limits to it; a library's colours apply as its swatches: a spot colour stays a //! spot colour, and joins the document's swatches). Edit tab: a hue and //! saturation wheel with a marker per new colour (drag one; with linked handles they all turn and -//! scale together), a brightness slider and the harmony rules. The preset menu sets up a 1, 2 or 3 +//! scale together), a brightness slider, the harmony rules, and the color sliders with their mode +//! menu, whose Global Adjust shows Saturation, Brightness, Temperature and Luminosity (-100% to +//! 100%, 0% changes nothing), which change every new color at once. The preset menu sets up a 1, 2 or 3 //! colour job or a library. Opened on a colour group (Edit or Apply Color Group), OK also rewrites //! the group with the new colours (renamed by `groupName`); without art only the group changes. //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new @@ -24,13 +26,15 @@ //! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none), //! `group`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, //! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for -//! a gray and Tint for a spot color). Changing `colors`, a preserve flag or `limitTo` reduces the -//! rows again. +//! a gray and Tint for a spot color; `global`: Global Adjust, on the Edit tab), `globalAdjust` +//! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s +//! `globalAdjust` in every slider mode). Changing `colors`, a preserve flag or `limitTo` reduces +//! the rows again. use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; use vectorcraft_color::harmony::{Harmony, move_on_wheel}; -use vectorcraft_color::recolor::{ColorKey, Method}; +use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method}; use vectorcraft_color::{Color, keep_model}; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; @@ -70,9 +74,18 @@ const NEW_CHIP: &str = "recolor-new"; /// The color modes of the sliders under the rows; a row whose new color is a spot color of the /// library also has Tint. const SLIDER_MODES: [Mode; 4] = [Mode::Hsb, Mode::Rgb, Mode::Cmyk, Mode::Lab]; -/// Widths of a color slider and of its number field. +/// Widths of a color slider's label, of the slider and of its number field. +const SLIDER_LABEL_W: f32 = 12.0; const SLIDER_W: f32 = 170.0; const SLIDER_FIELD_W: f32 = 48.0; +/// The `sliderMode` of the Edit tab's Global Adjust sliders, and the menu's name for it. +const GLOBAL: &str = "global"; +const GLOBAL_ADJUST: &str = "Global Adjust"; +/// The `globalAdjust` field's keys (and `recolor.apply`'s), in the order of the sliders. +const ADJUSTS: [&str; 4] = ["saturation", "brightness", "temperature", "luminosity"]; +/// Widths of a Global Adjust slider's label and of the slider. +const GLOBAL_LABEL_W: f32 = 76.0; +const GLOBAL_SLIDER_W: f32 = 110.0; /// The slider values last shown: `{row, key, mode, v}` (HSB keeps its hue at no saturation). const COMPS: &str = "__comps"; @@ -260,6 +273,11 @@ fn apply_params(d: &Dialog) -> Value { }); // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); + // The Global Adjust amounts, kept while the sliders show another mode; at 0% they are left out. + let values = adjust_values(d); + if values.iter().any(|v| *v != 0.0) { + p["globalAdjust"] = Value::Object(ADJUSTS.iter().zip(values).map(|(k, v)| (k.to_string(), json!(v))).collect()); + } if let (Some(Value::Object(g)), Some(p)) = (group, p.as_object_mut()) { p.extend(g.into_iter().filter(|(_, v)| !v.is_null())); } @@ -288,7 +306,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { ui.add_space(4.0); let mut rs = rows(d); let top = ui.cursor().top(); - let (changed, pick) = if d.str("tab") == "edit" { (edit_tab(ui, d, &mut rs), None) } else { assign_tab(app, ui, d, &mut rs) }; + let (changed, pick) = if d.str("tab") == "edit" { (edit_tab(app, ui, d, &mut rs), None) } else { assign_tab(app, ui, d, &mut rs) }; if d.str("tab") != "edit" { ui.add_space((TAB_H - (ui.cursor().top() - top)).max(0.0)); } @@ -335,7 +353,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); sync(app, &mut d); if d.bool("__newGroup") { - let colors: Vec = rows(&d).into_iter().filter(|r| !excluded(r)).map(|r| r["to"].clone()).collect(); + // The new colors with the Global Adjust, as `recolor.apply` gives them to a group. + let adjust = global_adjust(adjust_values(&d)); + let colors: Vec = rows(&d) + .into_iter() + .filter(|r| !excluded(r)) + .map(|r| to_color(&r).filter(|_| !adjust.is_identity()).map_or_else(|| r["to"].clone(), |c| key(&adjust.apply(c)))) + .collect(); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); } let r = form::commit_preview(app, CMD, apply_params(&d))?; @@ -529,7 +553,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut } } let target = SliderTarget::of(app, d, rows); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| mode_menu(ui, d, &target, false)); }); ui.add_space(6.0); changed |= sliders(app, ui, d, rows); @@ -686,30 +710,84 @@ impl SliderTarget { } } -/// The color mode menu of the sliders (HSB, RGB, CMYK, Lab, and Tint for a spot color), drawn -/// right to left: the menu, then its label. -fn mode_menu(ui: &mut Ui, d: &mut Dialog, target: &SliderTarget) { +/// The color mode menu of the sliders (HSB, RGB, CMYK, Lab, Tint for a spot color, and with +/// `global` Global Adjust), drawn right to left: the menu, then its label. +fn mode_menu(ui: &mut Ui, d: &mut Dialog, target: &SliderTarget, global: bool) { let t = Tokens::get(ui.ctx()); let mut labels: Vec<&str> = SLIDER_MODES.iter().map(|m| m.label()).collect(); if target.spot.is_some() { labels.push("Tint"); } - let current = target.mode(d).map_or("Tint", Mode::label); + if global { + labels.push(GLOBAL_ADJUST); + } + let adjusting = global && d.str("sliderMode") == GLOBAL; + let current = if adjusting { GLOBAL_ADJUST } else { target.mode(d).map_or("Tint", Mode::label) }; // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. let chosen = ui - .add_enabled_ui(target.color.is_some(), |ui| { - widgets::dropdown_named(ui, "recolor-slider-mode", Some(tl!("Color Mode:")), current, &labels, 90.0) + .add_enabled_ui(target.color.is_some() || global, |ui| { + widgets::dropdown_named(ui, "recolor-slider-mode", Some(tl!("Color Mode:")), current, &labels, if global { 110.0 } else { 90.0 }) }) .inner; if let Some(i) = chosen { - d.fields.insert("sliderMode".into(), json!(SLIDER_MODES.get(i).map_or_else(|| "tint".to_string(), |m| mode_id(*m)))); + let id = match SLIDER_MODES.get(i) { + Some(m) => mode_id(*m), + None if labels.get(i) == Some(&GLOBAL_ADJUST) => GLOBAL.to_string(), + None => "tint".to_string(), + }; + d.fields.insert("sliderMode".into(), json!(id)); } ui.label(egui::RichText::new(tl!("Color Mode:")).color(t.text_dim)); } -/// One color slider in the grid: its label, its rail with `track` and its number field, showing -/// `shown` with `suffix`. Returns the whole number in `shown`'s range that a drag, a key or the -/// field sets. +/// The Global Adjust amounts, in percent from -100 to 100, of `ADJUSTS`' keys in the +/// `globalAdjust` field (0 for one it lacks). +fn adjust_values(d: &Dialog) -> [f64; 4] { + let given = d.fields.get("globalAdjust"); + ADJUSTS.map(|k| given.and_then(|g| g.get(k)).and_then(Value::as_f64).unwrap_or(0.0).clamp(-100.0, 100.0)) +} + +/// The Global Adjust of `values` (percent, in the order of `ADJUSTS`). +fn global_adjust(values: [f64; 4]) -> GlobalAdjust { + let [saturation, brightness, temperature, luminosity] = values.map(|v| (v / 100.0) as f32); + GlobalAdjust { saturation, brightness, temperature, luminosity } +} + +/// The Global Adjust sliders, two to a line: Saturation, Brightness, Temperature and Luminosity, +/// each from -100% to 100% (0% changes nothing). They change every new color at once, so they +/// edit no row; each rail shows its amounts on `sample`. +fn global_sliders(ui: &mut Ui, d: &mut Dialog, sample: Color) { + let labels = [tl!("Saturation"), tl!("Brightness"), tl!("Temperature"), tl!("Luminosity")]; + let values = adjust_values(d); + let mut set: Option<(usize, f64)> = None; + egui::Grid::new("recolor-global-adjust").num_columns(6).spacing([6.0, 4.0]).show(ui, |ui| { + for (n, lbl) in labels.iter().enumerate() { + let shown = widgets::SliderValue::field(values[n], -100.0..=100.0, "%", 0); + // The rail: `sample` with this slider's amount alone. + let track = |x: f32| { + let mut one = [0.0; 4]; + one[n] = f64::from(x) * 200.0 - 100.0; + c32(&global_adjust(one).apply(sample)) + }; + if let Some(v) = slider_cell(ui, ("global", n), lbl, shown, "%", &track, GLOBAL_LABEL_W, GLOBAL_SLIDER_W) { + set = Some((n, v)); + } + if n % 2 == 1 { + ui.end_row(); + } + } + }); + if let Some((n, v)) = set { + let mut values = values; + values[n] = v; + d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().zip(values).map(|(k, v)| (k.to_string(), json!(v))).collect())); + } +} + +/// One color slider in the grid: its label `label_w` wide, its rail with `track` `slider_w` wide +/// and its number field, showing `shown` with `suffix`. Returns the whole number in `shown`'s +/// range that a drag, a key or the field sets. +#[allow(clippy::too_many_arguments)] fn slider_cell( ui: &mut Ui, id: impl std::hash::Hash + Copy, @@ -717,13 +795,15 @@ fn slider_cell( shown: widgets::SliderValue, suffix: &str, track: &dyn Fn(f32) -> egui::Color32, + label_w: f32, + slider_w: f32, ) -> Option { let t = Tokens::get(ui.ctx()); let (lo, hi) = (*shown.range.start(), *shown.range.end()); let value = shown.value; - ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(label).size(12.5).color(t.text))); + ui.add_sized(vec2(label_w, 22.0), egui::Label::new(egui::RichText::new(label).size(12.5).color(t.text))); let unit = ((value - lo) / (hi - lo)) as f32; - let (dragged, _, keyed) = widgets::color_slider_stepped(ui, ("recolor-slider", id), label, Some(shown), unit, SLIDER_W, track); + let (dragged, _, keyed) = widgets::color_slider_stepped(ui, ("recolor-slider", id), label, Some(shown), unit, slider_w, track); let typed = widgets::plain_field_named(ui, ("recolor-slider-field", id), Some(label), value, suffix, 0, SLIDER_FIELD_W); dragged.map(|x| (lo + f64::from(x) * (hi - lo)).round()).or(keyed).or(typed).map(|v| v.clamp(lo, hi)).filter(|v| (v - value).abs() > 1e-6) } @@ -746,7 +826,7 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] let gray = move |_: f32| input; for (n, lbl) in mode.labels().iter().enumerate() { let shown = widgets::SliderValue::field(0.0, f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); - slider_cell(ui, n, lbl, shown, mode.suffix(n), &gray); + slider_cell(ui, n, lbl, shown, mode.suffix(n), &gray, SLIDER_LABEL_W, SLIDER_W); if n % 2 == 1 { ui.end_row(); } @@ -757,7 +837,7 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] // Tint of the spot color, and its name. let tint = f64::from(row_tint(&rows[i])) * 100.0; let shown = widgets::SliderValue::field(tint, 0.0..=100.0, "%", 0); - if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&spot_tinted(app, c, x))) { + if let Some(v) = slider_cell(ui, usize::MAX, "T", shown, "%", &|x| c32(&spot_tinted(app, c, x)), SLIDER_LABEL_W, SLIDER_W) { rows[i]["tint"] = json!(v); changed = true; } @@ -769,7 +849,8 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] for (n, lbl) in mode.labels().iter().enumerate() { let v = comps.get(n).copied().unwrap_or(0.0); let shown = widgets::SliderValue::field(f64::from(v), f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); - if let Some(nv) = slider_cell(ui, n, lbl, shown, mode.suffix(n), &|x| c32(&track_color(mode, &comps, n, x))) { + if let Some(nv) = slider_cell(ui, n, lbl, shown, mode.suffix(n), &|x| c32(&track_color(mode, &comps, n, x)), SLIDER_LABEL_W, SLIDER_W) + { let mut c2 = comps.clone(); c2[n] = nv as f32; set = Some(c2); @@ -845,13 +926,14 @@ fn move_color(rows: &mut [Value], i: usize, hsb: [f32; 3], linked: bool) { const DRAG: &str = "__drag"; /// The Edit tab. Returns true when the rows changed. -fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { +fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { let top = ui.cursor().top(); let t = Tokens::get(ui.ctx()); let mut changed = false; let linked = d.bool("linked"); let active = active_rows(rows); let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied()); + let target = SliderTarget::of(app, d, rows); ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Harmony Rules:")).color(t.text_dim)); let rule = Harmony::parse(&d.str("rule")).unwrap_or(Harmony::Complementary); @@ -870,6 +952,10 @@ fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { if widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tip, linked, 24.0).clicked() { d.fields.insert("linked".into(), json!(!linked)); } + ui.add_space(8.0); + // The mode of the color sliders under the wheel: the selected new color in a color + // mode, or Global Adjust for all of them. + mode_menu(ui, d, &target, true); }); }); ui.add_space(8.0); @@ -899,6 +985,12 @@ fn edit_tab(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool { d.fields.remove(DRAG); } ui.add_space(6.0); + if d.str("sliderMode") == GLOBAL { + let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25)); + global_sliders(ui, d, sample); + } else { + changed |= sliders(app, ui, d, rows); + } // The new colours: click one to make it the base colour. let min_height = (TAB_H - (ui.cursor().top() - top)).max(0.0); super::modal::scrolled_rows(ui, "recolor-edit-colors", |ui| { @@ -957,6 +1049,33 @@ mod tests { assert!(apply_params(d).get("model").is_none()); } + /// `recolor.apply` gets the Global Adjust amounts only when one of them is not 0%, whatever + /// mode the sliders show. + #[test] + fn apply_params_send_global_adjust_only_when_it_changes_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("ui.recolorDialog", json!({"colors": ["#ff8000"]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert!(apply_params(d).get("globalAdjust").is_none(), "no field"); + d.fields.insert("globalAdjust".into(), json!({"saturation": 0, "brightness": 0})); + assert!(apply_params(d).get("globalAdjust").is_none(), "all 0%"); + d.fields.insert("globalAdjust".into(), json!({"temperature": 25, "luminosity": 500})); + d.fields.insert("sliderMode".into(), json!("hsb")); + assert_eq!( + apply_params(d)["globalAdjust"], + json!({"saturation": 0.0, "brightness": 0.0, "temperature": 25.0, "luminosity": 100.0}), + "every amount, clamped to 100%" + ); + // Colors opened alone become a new color group with the adjustment. + d.fields.insert("globalAdjust".into(), json!({"saturation": -100})); + let d = d.clone(); + confirm(&mut app, &d).unwrap(); + let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); + let c = g.swatches[0].paint.color().unwrap(); + assert!(c.to_hsb()[1] < 1e-3, "{c:?}"); + } + #[test] fn merge_and_separate_rows() { let mut r = rows(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f3f6cbfbb6..9d353951bd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1244,6 +1244,7 @@ font-technology Variable Променливи Get Preferences Извличане на предпочитания Get Text Range Вземане на текстов диапазон Global Глобален + Global Adjust Глобална корекция Global Brush Dimensions Глобални размери на четката Global Process Color Глобален процесен цвят Global Process Color, CMYK Глобален процесен цвят, CMYK diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7efa9c0e7..8951eb2262 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2138,6 +2138,7 @@ digits Malayalam Malajalam Color Mode: Način boja: Convert Pretvori Global Globalno + Global Adjust Globalno podešavanje Green Zelena Shifts the tints of global and spot colors; other colors stay. Pomjera nijanse globalnih i spot boja; ostale boje ostaju. Tint Preliv @@ -4260,6 +4261,7 @@ imageTrace Outline Obris @msg `library` is a library id or name (see {list}) `library` je ID ili naziv biblioteke (vidi {list}) @msg `mode` applies to freeform gradients `mode` se primjenjuje na gradijente slobodnog oblika @msg `preserve` must be an object `preserve` mora biti objekat +@msg `globalAdjust` must be an object `globalAdjust` mora biti objekat @msg `sampleSize` must be 1, 3 or 5 `sampleSize` mora biti 1, 3 ili 5 @msg `stops` must be an array `stops` mora biti niz @msg `svg` must be an object of SVG options (see document.formats) `svg` mora biti objekat SVG opcija (vidi document.formats) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd6172d6a6..08bf73630e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1699,6 +1699,7 @@ digits Malayalam Malaiàlam Glass Vidre Glass… Vidre… Global Global + Global Adjust Ajust global Global Brush Dimensions Dimensions globals del pinzell Global Edit Options Opcions globals d’edició Global Process Color Color de procés global @@ -4776,6 +4777,7 @@ digits Malayalam Malaiàlam @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte @msg `preserve` must be an object `preserve` ha de ser un objecte +@msg `globalAdjust` must be an object `globalAdjust` ha de ser un objecte @msg `sampleSize` must be 1, 3 or 5 `sampleSize` ha de ser 1, 3 o 5 @msg `select` must be true or false `select` ha de ser cert o fals @msg `stops` must be an array `stops` ha de ser una matriu diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 34c7f4e035..55f2c26ecc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2166,6 +2166,7 @@ digits Malayalam Malajálamské Color Mode: Barevný režim: Convert Převést Global Globální + Global Adjust Globální úprava Green Zelená Shifts the tints of global and spot colors; other colors stay. Posune tóny globálních a přímých barev; ostatní barvy zůstanou. Tint Tón @@ -4299,6 +4300,7 @@ imageTrace Outline Obrys @msg `library` is a library id or name (see {list}) `library` je ID nebo název knihovny (viz {list}) @msg `mode` applies to freeform gradients `mode` platí pro volné přechody @msg `preserve` must be an object `preserve` musí být objekt +@msg `globalAdjust` must be an object `globalAdjust` musí být objekt @msg `sampleSize` must be 1, 3 or 5 `sampleSize` musí být 1, 3 nebo 5 @msg `stops` must be an array `stops` musí být pole @msg `svg` must be an object of SVG options (see document.formats) `svg` musí být objekt s možnostmi SVG (viz document.formats) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5a23913424..f5f717ed56 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1969,6 +1969,7 @@ digits Malayalam Malayalam Color Mode: Farvetilstand: Convert Konvertér Global Global + Global Adjust Global justering Green Grøn Shifts the tints of global and spot colors; other colors stay. Flytter nuancerne af globale farver og spotfarver; andre farver forbliver uændrede. Tint Nuance diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 101bbefac6..831a355b22 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1268,6 +1268,7 @@ file-filter Templates Vorlagen Get Preferences Voreinstellungen abrufen Get Text Range Textbereich abrufen Global Global + Global Adjust Globale Anpassung Global Brush Dimensions Globale Pinselabmessungen Global Process Color Globale Prozessfarbe Global Process Color, CMYK Globale Prozessfarbe, CMYK @@ -3906,6 +3907,7 @@ theme Appearance Erscheinungsbild @msg `library` is a library id or name (see {list}) `library` ist die ID oder der Name einer Bibliothek (siehe {list}) @msg `mode` applies to freeform gradients `mode` gilt für Freiformverläufe @msg `preserve` must be an object `preserve` muss ein Objekt sein +@msg `globalAdjust` must be an object `globalAdjust` muss ein Objekt sein @msg `sampleSize` must be 1, 3 or 5 `sampleSize` muss 1, 3 oder 5 sein @msg `stops` must be an array `stops` muss ein Array sein @msg `svg` must be an object of SVG options (see document.formats) `svg` muss ein Objekt mit SVG-Optionen sein (siehe document.formats) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e704faade5..0c1adf7cff 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1208,6 +1208,7 @@ font-technology Variable Μεταβλητές Get Preferences Λήψη προτιμήσεων Get Text Range Λήψη περιοχής κειμένου Global Καθολικό + Global Adjust Καθολική ρύθμιση Global Brush Dimensions Καθολικές διαστάσεις πινέλου Global Process Color Καθολικό χρώμα τετραχρωμίας Global Process Color, CMYK Καθολικό χρώμα τετραχρωμίας, CMYK @@ -2208,6 +2209,7 @@ axis Both Και τα δύο @msg `library` is a library id or name (see {list}) Το `library` είναι αναγνωριστικό ή όνομα βιβλιοθήκης (δείτε {list}) @msg `mode` applies to freeform gradients Το `mode` ισχύει για ντεγκραντέ ελεύθερης μορφής @msg `preserve` must be an object Το `preserve` πρέπει να είναι αντικείμενο +@msg `globalAdjust` must be an object Το `globalAdjust` πρέπει να είναι αντικείμενο @msg `sampleSize` must be 1, 3 or 5 Το `sampleSize` πρέπει να είναι 1, 3 ή 5 @msg `stops` must be an array Το `stops` πρέπει να είναι πίνακας @msg `svg` must be an object of SVG options (see document.formats) Το `svg` πρέπει να είναι αντικείμενο επιλογών SVG (δείτε document.formats) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4ebddbe9a9..a93fd5d223 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1287,6 +1287,7 @@ font-technology Variable Variables Get Preferences Obtener preferencias Get Text Range Obtener rango de texto Global Global + Global Adjust Ajuste global Global Brush Dimensions Dimensiones globales de pincel Global Process Color Color de cuatricromía global Global Process Color, CMYK Color de cuatricromía global, CMYK @@ -3992,6 +3993,7 @@ axis Both Ambos @msg `library` is a library id or name (see {list}) `library` es el id o el nombre de una biblioteca (consulta {list}) @msg `mode` applies to freeform gradients `mode` se aplica a los degradados de forma libre @msg `preserve` must be an object `preserve` debe ser un objeto +@msg `globalAdjust` must be an object `globalAdjust` debe ser un objeto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` debe ser 1, 3 o 5 @msg `stops` must be an array `stops` debe ser una lista @msg `svg` must be an object of SVG options (see document.formats) `svg` debe ser un objeto con opciones de SVG (consulta document.formats) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7042b21f22..f5c9167093 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2125,6 +2125,7 @@ digits Malayalam Malajalam Color Mode: Väritila: Convert Muunna Global Globaali + Global Adjust Yleissäätö Green Vihreä Shifts the tints of global and spot colors; other colors stay. Siirtää globaalien värien ja spottivärien sävyjä; muut värit säilyvät. Tint Sävy @@ -4213,6 +4214,7 @@ imageTrace Outline Ääriviiva @msg `library` is a library id or name (see {list}) `library` on kirjaston tunnus tai nimi (ks. {list}) @msg `mode` applies to freeform gradients `mode` koskee vapaamuotoisia liukuvärejä @msg `preserve` must be an object `preserve` on oltava objekti +@msg `globalAdjust` must be an object `globalAdjust` on oltava objekti @msg `sampleSize` must be 1, 3 or 5 `sampleSize` on oltava 1, 3 tai 5 @msg `stops` must be an array `stops` on oltava taulukko @msg `svg` must be an object of SVG options (see document.formats) `svg` on oltava SVG-asetusten objekti (ks. document.formats) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 48eb621eb9..d590de2586 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1281,6 +1281,7 @@ font-technology Variable Variables Get Preferences Obtenir les préférences Get Text Range Obtenir une plage de texte Global Globale + Global Adjust Réglage global Global Brush Dimensions Dimensions globales des formes Global Process Color Couleur quadrichromique globale Global Process Color, CMYK Couleur quadrichromique globale, CMJN @@ -3982,6 +3983,7 @@ axis Both Les deux @msg `library` is a library id or name (see {list}) `library` est l’identifiant ou le nom d’une bibliothèque (voir {list}) @msg `mode` applies to freeform gradients `mode` s’applique aux dégradés de forme libre @msg `preserve` must be an object `preserve` doit être un objet +@msg `globalAdjust` must be an object `globalAdjust` doit être un objet @msg `sampleSize` must be 1, 3 or 5 `sampleSize` doit valoir 1, 3 ou 5 @msg `stops` must be an array `stops` doit être un tableau @msg `svg` must be an object of SVG options (see document.formats) `svg` doit être un objet d’options SVG (voir document.formats) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 81f9482631..23d51e8ea3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1602,6 +1602,7 @@ file-filter Templates Sablonok Glass Üveg Glass… Üveg… Global Globális + Global Adjust Globális beállítás Global Brush Dimensions Globális ecsetméretek Global Process Color Globális skálaszín Global Process Color, CMYK Globális skálaszín, CMYK @@ -4521,6 +4522,7 @@ imageTrace Outline Körvonal @msg `library` is a library id or name (see {list}) a `library` könyvtárazonosító vagy -név lehet (lásd: {list}) @msg `mode` applies to freeform gradients a `mode` a szabad formájú színátmenetekre vonatkozik @msg `preserve` must be an object `preserve`: objektum kell +@msg `globalAdjust` must be an object `globalAdjust`: objektum kell @msg `sampleSize` must be 1, 3 or 5 `sampleSize`: 1, 3 vagy 5 kell @msg `stops` must be an array `stops`: tömb kell @msg `svg` must be an object of SVG options (see document.formats) `svg`: SVG-beállításokat tartalmazó objektum kell (lásd: document.formats) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 89633ae991..ce1ce4436e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1969,6 +1969,7 @@ digits Malayalam Malayalam Color Mode: Mode warna: Convert Konversi Global Global + Global Adjust Penyesuaian global Green Hijau Shifts the tints of global and spot colors; other colors stay. Menggeser tint warna global dan warna spot; warna lainnya tetap. Tint Tint diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6acfaf3c9a..33b2c97797 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1298,6 +1298,7 @@ file-filter Templates Modelli Get Preferences Ottieni preferenze Get Text Range Ottieni intervallo di testo Global Globale + Global Adjust Regolazione globale Global Brush Dimensions Dimensioni pennello globali Global Process Color Colore quadricromia globale Global Process Color, CMYK Colore quadricromia globale, CMYK @@ -4033,6 +4034,7 @@ axis Both Entrambi @msg `library` is a library id or name (see {list}) `library` è l'id o il nome di una libreria (vedi {list}) @msg `mode` applies to freeform gradients `mode` si applica alle sfumature a forma libera @msg `preserve` must be an object `preserve` deve essere un oggetto +@msg `globalAdjust` must be an object `globalAdjust` deve essere un oggetto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` deve essere 1, 3 o 5 @msg `stops` must be an array `stops` deve essere un array @msg `svg` must be an object of SVG options (see document.formats) `svg` deve essere un oggetto di opzioni SVG (vedi document.formats) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bf3cd6bd1..18b45acef2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1662,6 +1662,7 @@ digits Malayalam マラヤーラム数字 Get Preferences 環境設定を取得 Get Text Range テキスト範囲を取得 Global グローバル + Global Adjust グローバル調整 Global Brush Dimensions ブラシサイズ (共通) Global Process Color グローバルプロセスカラー Go To Link リンク元へ移動 @@ -4149,6 +4150,7 @@ swatch Bright Violet ビビッドバイオレット @msg `groupColors` must be an array `groupColors` には配列を指定してください @msg `mode` applies to freeform gradients `mode` はフリーフォームグラデーションにのみ適用されます @msg `preserve` must be an object `preserve` にはオブジェクトを指定してください +@msg `globalAdjust` must be an object `globalAdjust` にはオブジェクトを指定してください @msg `stops` must be an array `stops` には配列を指定してください @msg `{k}` must be [x, y] `{k}` は [x, y] の形式で指定してください @msg a gradient needs at least two stops グラデーションには 2 つ以上の分岐点が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cf411b072c..437a7f1325 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1870,6 +1870,7 @@ digits Malayalam მალაიალამური Color Mode: ფერის რეჟიმი: Convert გარდაქმნა Global გლობალური + Global Adjust გლობალური კორექცია Green მწვანე Shifts the tints of global and spot colors; other colors stay. ცვლის გლობალური და სპოტ-ფერების ტონირებებს; სხვა ფერები უცვლელი რჩება. Tint ტონირება @@ -3778,6 +3779,7 @@ font-technology Variable ცვლადი @msg `library` is a library id or name (see {list}) `library` არის ბიბლიოთეკის id ან სახელი (იხ. {list}) @msg `mode` applies to freeform gradients `mode` ეხება თავისუფალი ფორმის გრადიენტებს @msg `preserve` must be an object `preserve` უნდა იყოს ობიექტი +@msg `globalAdjust` must be an object `globalAdjust` უნდა იყოს ობიექტი @msg `sampleSize` must be 1, 3 or 5 `sampleSize` უნდა იყოს 1, 3 ან 5 @msg `stops` must be an array `stops` უნდა იყოს მასივი @msg `svg` must be an object of SVG options (see document.formats) `svg` უნდა იყოს SVG-ის პარამეტრების ობიექტი (იხ. document.formats) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81f6c600c6..ac3d41d183 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1652,6 +1652,7 @@ digits Malayalam 말라얄람어 Get Preferences 환경 설정 가져오기 Get Text Range 텍스트 범위 가져오기 Global 전역 + Global Adjust 전체 조정 Global Brush Dimensions 전역 브러시 치수 Global Process Color 전역 프로세스 색상 Go To Link 링크로 이동 @@ -4076,6 +4077,7 @@ theme Appearance 외관 @msg `groupColors` must be an array `groupColors`는 배열이어야 합니다 @msg `mode` applies to freeform gradients `mode`는 자유형 그레이디언트에 적용됩니다 @msg `preserve` must be an object `preserve`는 개체여야 합니다 +@msg `globalAdjust` must be an object `globalAdjust`는 개체여야 합니다 @msg `stops` must be an array `stops`는 배열이어야 합니다 @msg `{k}` must be [x, y] `{k}`은(는) [x, y]여야 합니다 @msg a gradient needs at least two stops 그레이디언트에는 정지점이 두 개 이상 필요합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3448536832..8bdbcaa5f7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1983,6 +1983,7 @@ digits Malayalam Malayalam Color Mode: Kleurmodus: Convert Converteren Global Globaal + Global Adjust Globale aanpassing Green Groen Shifts the tints of global and spot colors; other colors stay. Verschuift de tinten van globale kleuren en spotkleuren; andere kleuren blijven ongewijzigd. Tint Tint diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14825f83cf..c5530da3f1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2083,6 +2083,7 @@ digits Malayalam Malajalam Color Mode: Tryb koloru: Convert Konwertuj Global Globalny + Global Adjust Dopasowanie globalne Green Zielony Shifts the tints of global and spot colors; other colors stay. Przesuwa tinty kolorów globalnych i dodatkowych; pozostałe kolory bez zmian. Tint Tinta @@ -4122,6 +4123,7 @@ imageTrace Outline Kontur @msg `library` is a library id or name (see {list}) `library` to identyfikator lub nazwa biblioteki (patrz {list}) @msg `mode` applies to freeform gradients `mode` dotyczy gradientów dowolnych @msg `preserve` must be an object `preserve` musi być obiektem +@msg `globalAdjust` must be an object `globalAdjust` musi być obiektem @msg `sampleSize` must be 1, 3 or 5 `sampleSize` musi wynosić 1, 3 lub 5 @msg `stops` must be an array `stops` musi być tablicą @msg `svg` must be an object of SVG options (see document.formats) `svg` musi być obiektem opcji SVG (patrz document.formats) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 96a31c3e57..d134a0be74 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1134,6 +1134,7 @@ Get Preferences Obter Preferências Get Text Range Obter Intervalo de Texto Global Global + Global Adjust Ajuste Global Global Brush Dimensions Dimensões Globais do Pincel Global Process Color Cor Global de Processo Glyphs Glifos @@ -3574,6 +3575,7 @@ axis Both Ambos @msg `library` is a library id or name (see {list}) `library` é o id ou o nome de uma biblioteca (veja {list}) @msg `mode` applies to freeform gradients `mode` se aplica a gradientes de forma livre @msg `preserve` must be an object `preserve` deve ser um objeto +@msg `globalAdjust` must be an object `globalAdjust` deve ser um objeto @msg `sampleSize` must be 1, 3 or 5 `sampleSize` deve ser 1, 3 ou 5 @msg `stops` must be an array `stops` deve ser uma matriz @msg `svg` must be an object of SVG options (see document.formats) `svg` deve ser um objeto com opções de SVG (veja document.formats) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fdb51b80df..9162379d9a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1295,6 +1295,7 @@ file-filter Templates Шаблоны Get Preferences Получить настройки Get Text Range Получить диапазон текста Global Глобальный + Global Adjust Глобальная настройка Global Brush Dimensions Глобальные размеры кисти Global Process Color Глобальный составной цвет Global Process Color, CMYK Глобальный составной цвет, CMYK @@ -4028,6 +4029,7 @@ axis Both Оба @msg `library` is a library id or name (see {list}) `library` — это идентификатор или имя библиотеки (см. {list}) @msg `mode` applies to freeform gradients `mode` применяется к произвольным градиентам @msg `preserve` must be an object `preserve` должно быть объектом +@msg `globalAdjust` must be an object `globalAdjust` должно быть объектом @msg `sampleSize` must be 1, 3 or 5 `sampleSize` должно быть 1, 3 или 5 @msg `stops` must be an array `stops` должно быть массивом @msg `svg` must be an object of SVG options (see document.formats) `svg` должно быть объектом параметров SVG (см. document.formats) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e2dddf022b..3d57ae9adb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1246,6 +1246,7 @@ font-technology Variable Variabla Get Preferences Hämta inställningar Get Text Range Hämta textintervall Global Global + Global Adjust Global justering Global Brush Dimensions Globala penseldimensioner Global Process Color Global processfärg Global Process Color, CMYK Global processfärg, CMYK @@ -3903,6 +3904,7 @@ axis Both Båda @msg `library` is a library id or name (see {list}) `library` är ett biblioteks-id eller biblioteksnamn (se {list}) @msg `mode` applies to freeform gradients `mode` gäller för fria gradienter @msg `preserve` must be an object `preserve` måste vara ett objekt +@msg `globalAdjust` must be an object `globalAdjust` måste vara ett objekt @msg `sampleSize` must be 1, 3 or 5 `sampleSize` måste vara 1, 3 eller 5 @msg `stops` must be an array `stops` måste vara en array @msg `svg` must be an object of SVG options (see document.formats) `svg` måste vara ett objekt med SVG-alternativ (se document.formats) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9ecf2ccf93..d547b2b351 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1224,6 +1224,7 @@ font-technology Variable Değişken Get Preferences Tercihleri Al Get Text Range Metin Aralığını Al Global Küresel + Global Adjust Genel Ayarlama Global Brush Dimensions Küresel Fırça Boyutları Global Process Color Global Proses Rengi Global Process Color, CMYK Küresel Proses Rengi, CMYK @@ -3786,6 +3787,7 @@ axis Both Her İkisi @msg `library` is a library id or name (see {list}) 'kitaplık' bir kitaplık kimliği veya adıdır (bkz. {list}) @msg `mode` applies to freeform gradients "mod" serbest biçimli degradeler için geçerlidir @msg `preserve` must be an object `preserve` bir nesne olmalıdır +@msg `globalAdjust` must be an object `globalAdjust` bir nesne olmalıdır @msg `sampleSize` must be 1, 3 or 5 "sampleSize" 1, 3 veya 5 olmalıdır @msg `stops` must be an array "duraklar" bir dizi olmalıdır @msg `svg` must be an object of SVG options (see document.formats) `svg`, SVG seçeneklerinin bir nesnesi olmalıdır (bkz. document.formats) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d348440a2c..18247cb531 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1292,6 +1292,7 @@ file-filter Templates Шаблони Get Preferences Отримати налаштування Get Text Range Отримати діапазон тексту Global Глобальний + Global Adjust Глобальне налаштування Global Brush Dimensions Глобальні розміри пензля Global Process Color Глобальний складовий колір Global Process Color, CMYK Глобальний складовий колір, CMYK @@ -4017,6 +4018,7 @@ axis Both Обидві @msg `library` is a library id or name (see {list}) `library` — це ідентифікатор або ім’я бібліотеки (див. {list}) @msg `mode` applies to freeform gradients `mode` застосовується до довільних градієнтів @msg `preserve` must be an object `preserve` має бути об’єктом +@msg `globalAdjust` must be an object `globalAdjust` має бути об’єктом @msg `sampleSize` must be 1, 3 or 5 `sampleSize` має бути 1, 3 або 5 @msg `stops` must be an array `stops` має бути масивом @msg `svg` must be an object of SVG options (see document.formats) `svg` має бути об’єктом параметрів SVG (див. document.formats) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 09652ede2b..9ee468d56c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1503,6 +1503,7 @@ file-filter Templates Mẫu Glass Kính Glass… Kính… Global Toàn cục + Global Adjust Điều chỉnh toàn cục Global Brush Dimensions Kích thước cọ toàn cục Global Process Color Màu xử lý toàn cục Global Process Color, CMYK Màu xử lý toàn cục, CMYK @@ -4173,6 +4174,7 @@ theme Appearance Giao diện @msg `library` is a library id or name (see {list}) `library` là id hoặc tên thư viện (xem {list}) @msg `mode` applies to freeform gradients `mode` áp dụng cho chuyển sắc tự do @msg `preserve` must be an object `preserve` phải là một đối tượng +@msg `globalAdjust` must be an object `globalAdjust` phải là một đối tượng @msg `sampleSize` must be 1, 3 or 5 `sampleSize` phải là 1, 3 hoặc 5 @msg `stops` must be an array `stops` phải là một mảng @msg `svg` must be an object of SVG options (see document.formats) `svg` phải là đối tượng tùy chọn SVG (xem document.formats) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 841bd4528a..2e6b58886c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1236,6 +1236,7 @@ file-filter Templates 模板 Get Preferences 获取首选项 Get Text Range 获取文本范围 Global 全局 + Global Adjust 全局调整 Global Brush Dimensions 全局画笔尺寸 Global Process Color 全局印刷色 Global Process Color, CMYK 全局印刷色,CMYK @@ -3878,6 +3879,7 @@ imageTrace Outline 轮廓 @msg `groupColors` must be an array `groupColors` 必须是数组 @msg `mode` applies to freeform gradients `mode` 仅适用于任意形状渐变 @msg `preserve` must be an object `preserve` 必须是对象 +@msg `globalAdjust` must be an object `globalAdjust` 必须是对象 @msg `stops` must be an array `stops` 必须是数组 @msg `{k}` must be [x, y] `{k}` 必须是 [x, y] @msg a gradient needs at least two stops 渐变至少需要两个色标 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a515d59a74..9f2adef1c2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1262,6 +1262,7 @@ file-filter Templates 範本 Get Preferences 取得偏好設定 Get Text Range 取得文字範圍 Global 全域 + Global Adjust 整體調整 Global Brush Dimensions 整體筆刷尺寸 Global Process Color 整體印刷色 Global Process Color, CMYK 整體印刷色,CMYK @@ -1801,6 +1802,7 @@ file-filter Templates 範本 @msg `groupColors` must be an array `groupColors` 必須是陣列 @msg `mode` applies to freeform gradients `mode` 只適用於任意形狀漸層 @msg `preserve` must be an object `preserve` 必須是物件 +@msg `globalAdjust` must be an object `globalAdjust` 必須是物件 @msg `stops` must be an array `stops` 必須是陣列 @msg `{k}` must be [x, y] `{k}` 必須是 [x, y] @msg a gradient needs at least two stops 漸層至少需要兩個色標 diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 7c20467185..1786b7a614 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -572,11 +572,76 @@ fn switching_tabs_or_slider_modes_keeps_the_dialog_height() { h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", "recolor")))).unwrap().height() }; let assign = height(&mut h, "sliderMode", json!("cmyk")); - for (k, v) in [("sliderMode", json!("hsb")), ("sliderMode", json!("lab")), ("tab", json!("edit")), ("tab", json!("assign"))] { + for (k, v) in [ + ("sliderMode", json!("hsb")), + ("sliderMode", json!("lab")), + ("tab", json!("edit")), + ("sliderMode", json!("global")), + ("sliderMode", json!("rgb")), + ("tab", json!("assign")), + ] { assert_eq!(height(&mut h, k, v.clone()), assign, "{k} {v}"); } } +/// The fills of the document's objects, in order. +fn fills(app: &VectorcraftApp) -> Vec> { + let d = &app.session.doc().unwrap().doc; + d.layers[0].children().unwrap().iter().map(|n| d.node(n.id).unwrap().appearance.fill_paint().color()).collect() +} + +/// The Edit tab's color mode menu offers Global Adjust: Saturation, Brightness, Temperature and +/// Luminosity open at 0%, which changes nothing; one slider changes every recolored color at once +/// (the rows keep their new colors) and the art previews it; back at 0% the art has its own colors +/// again; the amounts stay while the tab or the mode changes; OK keeps the change as one undo step +/// and Cancel leaves the art as it was. +#[test] +fn global_adjust_changes_every_color_at_once() { + for confirm in [true, false] { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]); + let before = fills(h.state()); + let undo = h.state().session.doc().unwrap().history.undo.len(); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Color Mode:").click(); + h.run_steps(2); + h.get_by_label("Global Adjust").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "sliderMode"), json!("global")); + for name in ["Saturation", "Temperature", "Luminosity"] { + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, name).is_some(), "{name}"); + } + // Global Adjust's Brightness and the wheel's. + assert_eq!(h.get_all_by_role_and_label(egui::accesskit::Role::Slider, "Brightness").count(), 2); + assert_eq!(fills(h.state()), before, "at 0% the art keeps its colors"); + let rows = field(h.state(), "rows"); + click_slider(&mut h, "Saturation", 0.0); + assert_eq!(field(h.state(), "globalAdjust")["saturation"], json!(-100.0)); + assert_eq!(field(h.state(), "rows"), rows, "the rows keep their new colors"); + let gray = |app: &VectorcraftApp| fills(app).iter().all(|c| c.is_some_and(|c| c.to_hsb()[1] < 1e-3)); + assert!(gray(h.state()), "every color previews gray: {:?}", fills(h.state())); + click_slider(&mut h, "Saturation", 0.5); + assert_eq!(field(h.state(), "globalAdjust")["saturation"], json!(0.0)); + assert_eq!(fills(h.state()), before, "back at 0% the art has its own colors"); + click_slider(&mut h, "Saturation", 0.0); + for (k, v) in [("tab", json!("assign")), ("tab", json!("edit")), ("sliderMode", json!("hsb")), ("sliderMode", json!("global"))] { + set(h.state_mut(), k, v); + h.run_steps(3); + } + assert_eq!(field(h.state(), "globalAdjust")["saturation"], json!(-100.0), "the amount stays"); + assert!(gray(h.state()), "and still applies"); + h.get_by_label(if confirm { "OK" } else { "Cancel" }).click(); + h.run_steps(2); + assert!(h.state().ui.dialog.is_none()); + let app = h.state(); + if confirm { + assert!(gray(app), "OK keeps the change: {:?}", fills(app)); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + } else { + assert_eq!(fills(app), before, "Cancel leaves the art unchanged"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + } + } +} + /// The Assign tab's per-row hex fields are named by their row, not all "Color": a screen reader can /// tell the second from the first. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8f09432303..ad3a44d500 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -259,7 +259,12 @@ as `recolor.reduce` returns them), `colors` (null for Auto), `method`, `preserve `sliderMode` (the mode of the color sliders under the rows: `hsb`, `rgb`, `cmyk`, `lab`, or `tint` for a row whose new color is a spot color of the library; unset, they show the new color's own model). The sliders edit the first selected row's new color and give that row `model: "new"`, so the preview and confirm give only that row's art the color in -the sliders' mode; another edit of the row's new color, Reset and rows reduced again remove it. Setting +the sliders' mode; another edit of the row's new color, Reset and rows reduced again remove it. The Edit tab shows the +same sliders under the wheel, and its mode menu also has Global Adjust (`sliderMode: "global"`): Saturation, +Brightness, Temperature and Luminosity sliders that set `globalAdjust` (`{saturation, brightness, temperature, +luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-zero `globalAdjust` as `recolor.apply`'s +`globalAdjust` in every slider mode, so one slider changes every recolored color at once and the rows keep their new +colors; colors opened alone are saved as a group with the change. Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..92d031ba53 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1929,7 +1929,7 @@ the objects `select.all` takes, which leaves out hidden and locked art, and the and locked objects inside a group are left out too, also in isolation mode. `recolor.reduce {colors?, method?, preserve?, limitTo?, ids?}` groups those colours into rows of similar colours (k-means in Lab, weighted by use; tints of a global swatch share its row; White and Black are preserved by default) and returns a map of rows -`[{from: [keys], to: key}]` to edit and pass to `recolor.apply {map, method?, model?, limitTo?, group?, groupColors?, rename?}`. +`[{from: [keys], to: key}]` to edit and pass to `recolor.apply {map, method?, model?, limitTo?, group?, groupColors?, rename?, globalAdjust?}`. For scripts and MCP, `model` selects the replacement color model: `keep` (default) retains each original color's model, `new` takes the replacement's model, and `document` converts replacements and edited color groups to the document's model. A row's own `model` (the same values) takes the @@ -1953,11 +1953,26 @@ is linked to a swatch rewritten with another color keeps its row's new color, ev linked to the swatch, as does art whose color the row converts into the art's own color model. Without `group`, the swatch keeps its color and the recolored art is no longer linked to it. +`globalAdjust: {saturation?, brightness?, temperature?, luminosity?}` is the dialog's Global Adjust: each amount is a +percentage from -100 to 100 (0 when left out), and all four at 0 change nothing. Every color that a row which is not +excluded recolors takes the same change after its row's new color, in this order: saturation multiplies HSB +saturation by 1 + saturation/100; brightness moves HSB brightness that share of the way to full brightness (above 0) +or to black (below 0); temperature adds 0.2 × temperature/100 to red and subtracts it from blue; luminosity moves Lab +lightness that share of the way to 100 or to 0 and keeps Lab a and b, so the hue stays. Each color keeps its own +model, and a changed color is no longer linked to its swatch. The colors a `group` is rewritten with take the same +change. With `limitTo`, each row's new color takes the change before it snaps to the library, so the art still takes +the library's colors. Colors that no row holds, such as preserved White and Black, and excluded rows stay as they are. + +```json +{"name":"run_command","arguments":{"command":"recolor.apply","params":{"map":{"#ff0000":"#ff0000","#0000ff":"#0000ff"},"globalAdjust":{"saturation":-40,"temperature":25}}}} +``` + The `recolor.*` commands refuse parameters of the wrong form. A `limitTo` or `method` that is not a string gets the error for an unknown library or method. Other wrong-form parameters get an error that names them. `includeImages`, `includePatterns`, a row's `exclude`, `order`, `saturationBrightness` and the `white`, `black` and `grays` switches of `preserve` must be true or false; `colors` and `seed` must be whole numbers; `group` and `rename` -must be strings, `groupColors` must be an array and `preserve` must be an object. Each refusal leaves the document unchanged and records no undo step. A `null` +must be strings, `groupColors` must be an array, `preserve` must be an object, and `globalAdjust` must be an object +whose amounts are numbers from -100 to 100. Each refusal leaves the document unchanged and records no undo step. A `null` counts as a value left out except for `recolor.apply`'s `model` and a `map` row's `model`, which must be strings when given. ```json diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..3a9260f931 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -123,7 +123,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939); the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies and excluding a match with Shift-click, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, and PDF gradients mixing a spot color with RGB or Lab stops | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, and PDF gradients mixing a spot color with RGB or Lab stops | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | From 1ef52dd50e8b2006f02b9b88ca985c25b3c75478 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 10:25:50 -0800 Subject: [PATCH 006/189] Artwork Cleanup: Simplify Anchors and Deep Ungroup leave hidden and locked art alone Simplify Anchors (Keep Shape) simplified every path under the selection, locked and hidden paths and paths in locked or hidden groups included. It now takes only the paths Document::editable allows, as the health check and Rejoin Path Pieces already do. Deep Ungroup took apart hidden and locked groups inside the selection, so their members became visible or unlocked. A hidden or locked group now stays whole, a locked or hidden object named in ids is left alone, and members that are locked or hidden themselves keep that and are not selected. With no group to take apart, the reply's ids list the selection, which stays as it was. --- crates/engine/src/cmd/addons/cleanup.rs | 35 ++++++--- crates/engine/src/cmd/addons/cleanup/tests.rs | 78 +++++++++++++++++++ docs/mcp.md | 8 +- 3 files changed, 107 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/addons/cleanup.rs b/crates/engine/src/cmd/addons/cleanup.rs index b65fc75ac3..cba512cd18 100644 --- a/crates/engine/src/cmd/addons/cleanup.rs +++ b/crates/engine/src/cmd/addons/cleanup.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Simplify Anchors (Keep Shape)…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay → {ids, before, after} anchor counts", + "{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts", has_selection, simplify ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Deep Ungroup…", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in → {ids (the objects left, selected), ungrouped (groups)}", + "{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}", has_selection, deep_ungroup ), @@ -91,7 +91,8 @@ pub fn specs() -> Vec { v } -/// The paths (not guides) under `roots`, compound path members included. +/// The paths (not guides) under `roots`, compound path members included; locked and hidden +/// paths, and those in locked or hidden groups, stay out. fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { let mut out = vec![]; for n in roots.iter().filter_map(|id| d.node(*id)) { @@ -101,6 +102,8 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec { } }); } + let editable = d.editable(); + out.retain(|id| editable(*id)); out } @@ -256,9 +259,9 @@ fn ungroupable(n: &Node, clips: bool) -> bool { /// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts /// the groups. Members take on the opacity of the groups they were in, and a clipping path -/// becomes a plain path. +/// becomes a plain path. A locked or hidden group stays whole. fn flatten(n: Node, clips: bool, out: &mut Vec, count: &mut usize) { - if !ungroupable(&n, clips) { + if !ungroupable(&n, clips) || n.locked || !n.visible { out.push(n); return; } @@ -282,6 +285,11 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result { let clips = switch_or(p, "includeClipGroups", false, C)?; let roots = checked_ids_or_selection(s, p, C)?; let d = &s.doc()?.doc; + // Locked and hidden objects, and those in locked or hidden groups, stay as they are. + let roots: Vec = { + let editable = d.editable(); + roots.into_iter().filter(|id| editable(*id)).collect() + }; let (mut items, mut selected, mut count) = (vec![], vec![], 0); for id in &roots { match d.node(*id).filter(|n| ungroupable(n, clips)) { @@ -294,13 +302,18 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result { None => selected.push(*id), } } - // With no group to take apart, the document and its undo history stay as they are. - if !items.is_empty() { - let ids = selected.clone(); - s.edit("Deep Ungroup", |d, sel| { + // With no group to take apart, the document, the selection and the undo history stay as they + // are, and the reply lists the selection. + if items.is_empty() { + selected = s.doc()?.selection.objects.to_vec(); + } else { + selected = s.edit("Deep Ungroup", move |d, sel| { d.insert_beside(items, true)?; - sel.set(ids); - Ok(()) + // Members that are locked or hidden themselves keep that, and are not selected. + let editable = d.editable(); + selected.retain(|id| editable(*id)); + sel.set(selected.iter().copied()); + Ok(selected) })?; } Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::>(), "ungrouped": count })) diff --git a/crates/engine/src/cmd/addons/cleanup/tests.rs b/crates/engine/src/cmd/addons/cleanup/tests.rs index d02e1e4c09..83b67c6b16 100644 --- a/crates/engine/src/cmd/addons/cleanup/tests.rs +++ b/crates/engine/src/cmd/addons/cleanup/tests.rs @@ -104,6 +104,39 @@ fn simplify_keeps_the_shape_with_fewer_anchors_in_one_step() { } } +#[test] +fn simplify_leaves_locked_and_hidden_paths_alone() { + let mut s = session(); + let mut ids = vec![]; + for x in [20.0, 140.0, 260.0] { + ids.push(id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": 50, "width": 100, "height": 100})).unwrap())); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + s.execute("object.path.addAnchorPoints", &json!({})).unwrap(); + } + select(&mut s, &ids); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, ids[1], |n| n.locked = true); + change(&mut s, ids[2], |n| n.visible = false); + select(&mut s, &[g]); + let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([ids[0].0])); + assert_eq!(r["before"], 16); + assert!(anchors(&s, ids[0]) < 16); + assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); + // Named by `ids`, or in a locked group, a path stays too, with no undo step. + let steps = undo_steps(&s); + s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap(); + assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16)); + assert_eq!(undo_steps(&s), steps); + change(&mut s, ids[1], |n| n.locked = false); + change(&mut s, g, |n| n.locked = true); + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap(); + assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0))); + assert_eq!(anchors(&s, ids[1]), 16); + assert_eq!(undo_steps(&s), steps); +} + /// Each kind: what makes the issue in a fresh document (beside a clean rectangle). fn make_issue(s: &mut Session, kind: &str) { match kind { @@ -333,6 +366,51 @@ fn deep_ungroup_takes_apart_every_level_but_clipping_groups() { assert!(matches!(d.node(clip).unwrap().kind, NodeKind::Path { clipping: false, .. })); } +#[test] +fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0); + let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0); + select(&mut s, &[b]); + let hidden = id_of(&s.execute("object.group", &json!({})).unwrap()); + select(&mut s, &[c]); + let locked = id_of(&s.execute("object.group", &json!({})).unwrap()); + change(&mut s, hidden, |n| n.visible = false); + change(&mut s, locked, |n| n.locked = true); + change(&mut s, e, |n| n.locked = true); + s.edit("t", |d, _| { + let w = d.alloc_id(); + Ok(d.wrap(&[a, hidden, locked, e], |ch| Node::group(w, ch))?) + }) + .unwrap(); + let outer = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + select(&mut s, &[outer]); + let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap(); + assert_eq!(r["ungrouped"], 1); + assert_eq!(r["ids"], json!([a.0])); + let d = &s.doc().unwrap().doc; + let layer: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(layer, [a, hidden, locked, e], "the hidden and locked groups stay whole"); + assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible); + assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked); + assert_eq!(s.doc().unwrap().selection.objects, [a]); + // Named by `ids`, a locked group stays as it is, with no undo step. + let steps = undo_steps(&s); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap(); + assert_eq!(r["ungrouped"], 0); + assert!(node(&s, locked).is_some()); + assert_eq!(undo_steps(&s), steps); + // With nothing ungrouped, the selection stays and the reply lists it. + assert_eq!(r["ids"], json!([a.0])); + let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0); + select(&mut s, &[a]); + let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap(); + assert_eq!((r["ids"].clone(), r["ungrouped"].clone()), (json!([a.0]), json!(0))); + assert_eq!(s.doc().unwrap().selection.objects, [a]); +} + #[test] fn rejoin_joins_pieces_within_the_gap_only() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index fa8e05fab3..97fd9dc64f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5910,8 +5910,9 @@ Plug-ins › Artwork Cleanup and in its panel (`window.panel {panel: "artworkCle `addon.cleanup.simplify {tolerance?, protectCorners?, ids?}` removes the anchors each selected path can do without and refits the handles beside each one, so the outline keeps its shape. `tolerance` runs from 1 to 100 (20 by default); the outline stays within tolerance × 0.02 pt of where it was, measured against the original outline, so removals don't add -up. With `protectCorners`, anchors where the path turns by more than 30° stay. Open ends always stay. It reports the -anchor counts `before` and `after`, as one undo step. +up. With `protectCorners`, anchors where the path turns by more than 30° stay. Open ends always stay. Locked and hidden +paths, and paths in locked or hidden groups, are left out. It reports the anchor counts `before` and `after`, as one +undo step. The health check looks for issues in the selection, or in the whole document while nothing is selected (`scope: "selection"|"document"` picks one). Locked and hidden objects, and the insides of live or generated art (blends, @@ -5945,7 +5946,8 @@ envelopes, graphs, symbols), are left out. `addon.cleanup.deepUngroup {includeClipGroups?, ids?}` takes apart every level of grouping in the selection. Clipping groups stay whole unless `includeClipGroups` is true; their clipping paths then become plain paths. Objects keep the -opacity of the groups they were in. +opacity of the groups they were in. Locked and hidden groups stay whole, and locked and hidden objects stay locked or +hidden and are left out of the selection. `addon.cleanup.rejoin {gap?, ids?}` welds the selected open paths whose ends lie within `gap` (0 to 6 pt, 0.1 by default) back into paths. Each end joins one other end: where several are in reach, the one the path turns least to go From d46284c52c389bccfa3ac497b01f6f248c5dc5ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 18:10:13 -0800 Subject: [PATCH 007/189] Recolor: Global Adjust gives linked tints of a rewritten group their adjusted color A tint linked to a global swatch of the color group that recolor.apply rewrites kept its link and showed the swatch's adjusted color at its tint, which differs from the same color adjusted on its own. It now keeps the link only when the two match, and otherwise takes the adjusted color, unlinked. --- crates/color/src/recolor.rs | 6 ++++++ crates/engine/src/cmd/recolor.rs | 9 +++++---- crates/engine/src/tests/recolor.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/color/src/recolor.rs b/crates/color/src/recolor.rs index 53cb12478d..e7cf22c41f 100644 --- a/crates/color/src/recolor.rs +++ b/crates/color/src/recolor.rs @@ -244,6 +244,12 @@ pub fn is_tint(c: Color, base: Color) -> bool { a.iter().zip(b).all(|(x, y)| (x - y * t).abs() <= 0.01) } +/// Whether `a` and `b` carry the same ink in `a`'s model, within [`is_tint`]'s tolerance. +pub fn same_ink(a: Color, b: Color) -> bool { + let (x, y) = (ink(a, a.model()), ink(b, a.model())); + x.iter().zip(y).all(|(p, q)| (p - q).abs() <= 0.01) +} + /// `c` darkened by `f` (0..1) toward black: more K for CMYK and Gray, scaled RGB and Lab. pub fn shaded(c: Color, f: f32) -> Color { let f = f.clamp(0.0, 1.0); diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 75b2cc73b6..1759372d0a 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeSet, HashMap}; use serde_json::{Value, json}; -use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster}; +use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink}; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::swatches::{node_colors, node_paints}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; @@ -452,7 +452,8 @@ impl ColorMap { /// stay unlinked), a /// process swatch gives its colour in its own model; a color linked to a global swatch of the /// rewritten group that takes the row's new color keeps its link (at its tint in the row) when - /// the row gives it the new color in that color's model; + /// the row gives it the new color in that color's model and the Global Adjust gives it the + /// swatch's new color at that tint; /// other rows map the colour, which loses its link when it changes or when the group's rewrite /// would change it. True when anything changed. fn map_link(&self, c: &mut Color, link: &mut Option, tint: &mut f32) -> bool { @@ -462,9 +463,9 @@ impl ColorMap { && let Some(g) = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)) && self.tos.get(i) == Some(&g.color) && !row.converts(*c) - && let Some(t) = row.tint(*c) + && let Some(t) = row.tint(*c).map(|t| t.clamp(0.0, 1.0)) + && (self.adjust.is_identity() || same_ink(self.adjust.apply(row.map(*c)), g.shown.tinted(t))) { - let t = t.clamp(0.0, 1.0); let shown = g.shown.tinted(t); let changed = *tint != t || *c != shown; (*c, *tint) = (shown, t); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index cadf9314a9..cff302503d 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -812,6 +812,34 @@ fn global_adjust_with_a_library_and_a_group() { assert_eq!(c, fill(&s, art), "as the art is"); } +/// Art linked to a global swatch of the rewritten group takes the same Global Adjust as unlinked +/// art of its color: at 100% it keeps the link, and a tint whose adjusted color is not the +/// swatch's new color at that tint takes the adjusted color and loses the link. +#[test] +fn global_adjust_gives_linked_tints_of_a_group_the_adjusted_color() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Theme", "colors": ["#ff0000"]})); + let name = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().swatches[0].name.clone(); + run(&mut s, "swatch.edit", json!({"name": name, "global": true})); + let full = rect(&mut s, json!("#000000")); + let tint = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [full.0], "swatch": name})); + run(&mut s, "paint.setFill", json!({"ids": [tint.0], "swatch": name, "tint": 50})); + let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, tint } => (color, swatch, tint), + p => panic!("{p:?}"), + }; + select_all(&mut s); + let tint_key = vectorcraft_color::recolor::ColorKey::of(&fill(&s, tint)).to_string(); + let rows = json!([{"from": ["rgb 255 0 0", tint_key], "to": "#ff0000"}]); + run(&mut s, "recolor.apply", json!({"map": rows, "method": "scaleTints", "group": "Theme", "globalAdjust": {"brightness": -50}})); + let (c, w, t) = link(&s, full); + assert!(close(c, Color::rgb(0.5, 0.0, 0.0)) && w.as_deref() == Some(name.as_str()) && t == 1.0, "{c:?} {w:?} {t}"); + let (c, w, _) = link(&s, tint); + assert!(close(c, Color::rgb(0.5, 0.25, 0.25)), "the tint's own color, adjusted: {c:?}"); + assert_eq!(w, None, "the adjusted tint is not a tint of the swatch's new color"); +} + /// `globalAdjust` must be an object of numbers from -100 to 100; a refusal changes nothing and /// records no undo step. A null counts as left out. #[test] From 7389cc22d6af82de9311193eb8cb6e30cb423d14 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 18:18:19 -0800 Subject: [PATCH 008/189] Document Info: Save writes the category the panel shows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Save… in the Document Info panel menu now writes only the category the panel shows, with Selection Only applied. With All Categories shown it writes every category, as before. docInfo.save takes an optional category (a document.info category id) and passes it to document.info. --- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/doc_info.rs | 71 +++++++++++++++++++++++-- docs/control-protocol.md | 3 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 5 files changed, 73 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 11f3424200..48a1d2ecc8 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1130,7 +1130,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "docInfo.save", "Save Document Info…", "", - "{path?, selectionOnly?} write Document Info's text report (document.info {format: \"text\"}) to path, else a picked file (the web downloads it) → {path}", + "{path?, selectionOnly?, category?} write Document Info's text report (document.info {format: \"text\"}) to path, else a picked file (the web downloads it); with category (a document.info category id) only that category, else every category. The panel menu's Save… passes the category the panel shows and its Selection Only → {path}", ), ( "ui.epsOptionsDialog", diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 87f08f7f3f..f6becb3911 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -101,11 +101,15 @@ fn named_rows(id: &str, rows: &[Value]) -> std::ops::Range { } } -/// `docInfo.save {path?, selectionOnly?}`: write the text report to `path`, else a picked file -/// (the web downloads it) → `{path}`. +/// `docInfo.save {path?, selectionOnly?, category?}`: write the text report (only `category` when given, +/// else every category) to `path`, else a picked file (the web downloads it) → `{path}`. pub(crate) fn save_report(app: &mut VectorcraftApp, p: &Value) -> Result { let sel_only = p.get("selectionOnly").and_then(Value::as_bool).unwrap_or(false); - let r = app.session.execute("document.info", &json!({ "format": "text", "selectionOnly": sel_only })).map_err(|e| e.to_string())?; + let mut q = json!({ "format": "text", "selectionOnly": sel_only }); + if let Some(c) = p.get("category").and_then(Value::as_str).filter(|c| !c.is_empty()) { + q["category"] = c.into(); + } + let r = app.session.execute("document.info", &q).map_err(|e| e.to_string())?; let text = r["text"].as_str().unwrap_or_default(); let title = app.session.active().map(|d| d.title()).unwrap_or_default(); let stem = std::path::Path::new(&title).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); @@ -134,7 +138,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); if menu_item(ui, tl!("Save…"), app.session.active().is_some(), false) { - crate::menus::invoke(app, "docInfo.save", json!({ "selectionOnly": sel })); + crate::menus::invoke(app, "docInfo.save", json!({ "selectionOnly": sel, "category": category })); } } @@ -207,4 +211,63 @@ mod tests { let report = String::from_utf8(written.borrow().clone()).unwrap(); assert!(report.starts_with("Document Info: ") && report.contains("\nFONT DETAILS\n") && report.contains("\nREPEAT OBJECTS\n"), "{report}"); } + + /// The report the panel menu's Save… writes with category `category` shown ("" for All + /// Categories) and Selection Only set to `sel_only`. + fn saved_from_menu(app: &mut VectorcraftApp, category: &str, sel_only: bool) -> String { + let written: std::rc::Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |_: &str, b: &[u8]| { + w.borrow_mut().extend_from_slice(b); + Ok(()) + })); + app.services.pick_save = Some(Box::new(|pick: &crate::FilePick| Some(format!("/tmp/{}", pick.name)))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "docinfo-category", category.to_string()); + set_pstate(&ctx, "docinfo-sel", sel_only); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(236.0, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| menu(app, ui)); + out.textures_delta.clear(); + crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()) + }; + let labels = frame(app, vec![]); + let at = labels.iter().find(|(t, _)| t.trim() == "Save…").map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no Save… in {labels:?}")); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(at), button(true)]); + frame(app, vec![button(false)]); + let report = String::from_utf8(written.borrow().clone()).unwrap(); + assert!(report.starts_with("Document Info: "), "nothing saved: {report:?}"); + report + } + + /// Save… writes the category the panel shows, with Selection Only applied; All Categories + /// writes every category. + #[test] + fn save_writes_the_category_the_panel_shows() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let text = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone(); + let objects = saved_from_menu(&mut app, "objects", false); + assert!(objects.contains("\nOBJECTS\n") && objects.contains("Paths: 1") && objects.contains("Text Objects: 1"), "{objects}"); + assert!(!objects.contains("\nDOCUMENT\n") && !objects.contains("\nFONTS\n"), "only Objects: {objects}"); + let fonts = saved_from_menu(&mut app, "fonts", false); + assert!(fonts.contains("\nFONTS\n") && fonts.contains("Source Sans 3"), "{fonts}"); + assert!(!fonts.contains("\nOBJECTS\n") && !fonts.contains("\nFONT DETAILS\n"), "only Fonts: {fonts}"); + let all = saved_from_menu(&mut app, "", false); + assert!( + all.contains("\nDOCUMENT\n") && all.contains("\nOBJECTS\n") && all.contains("\nFONTS\n") && all.contains("\nREPEAT OBJECTS\n"), + "{all}" + ); + app.session.execute("select.set", &json!({"ids": [text]})).unwrap(); + let selected = saved_from_menu(&mut app, "objects", true); + assert!(selected.contains("(the selection only)") && selected.contains("Text Objects: 1"), "{selected}"); + assert!(!selected.contains("Paths: 1") && !selected.contains("\nFONTS\n"), "the selection's objects only: {selected}"); + // The command takes the category too; an unknown one is an error and writes nothing. + let err = app.run("docInfo.save", json!({"path": "/tmp/info.txt", "category": "colors"})).unwrap_err(); + assert!(err.contains("category `colors`"), "{err}"); + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8f09432303..379c4b37b5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -646,7 +646,8 @@ Package: File → Package… (`ui.packageDialog`) opens the `package` dialog for gets a `confirm` dialog whose OK runs `file.saveAs`). Fields: `folder` (the location), `name` (the package folder), `copyLinks`, `linksFolder`, `relink`, `copyFonts`, `report`. `ui.dialog.confirm` saves unsaved changes, runs `file.package` and then opens a `confirm` dialog whose OK runs `file.showPackage {folder}`; the web downloads the zip -instead. Document Info's flyout picks a category and Save… runs `docInfo.save {path?, selectionOnly?}`. +instead. Document Info's flyout picks a category and Save… runs `docInfo.save {path?, selectionOnly?, category?}` with the +category the panel shows (none for All Categories, which writes every category). Slices: through the app, `object.slice.options` and `object.slice.divide` with no params open their dialogs on the selected slices. `sliceOptions` (fields `kind`: `image`/`noImage`/`htmlText`, `name`, `url`, `target`, `message`, diff --git a/docs/mcp.md b/docs/mcp.md index f1e55b9fd2..ac1eef8518 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4052,8 +4052,8 @@ groups and in other repeats included, with its type `radial`, `grid` or `mirror` and a grid's `rows` and `cols`; with `selectionOnly`, the Repeat objects in the selection) and `pathLength` (pt: the total length of the paths, compound paths' pieces included and guides left out, which objects lists as Path Length in the document's units, say for a cut line or an LED strip along the letters); -`format: "text"` returns the plain-text report Document Info › Save… (`docInfo.save {path?}`) and the package report -write. +`format: "text"` returns the plain-text report Document Info › Save… (`docInfo.save {path?, selectionOnly?, category?}`: +only `category` when given, else every category) and the package report write. ```json {"name":"run_command","arguments":{"command":"file.package","params":{"folder":"/tmp/handoff","copyFonts":false}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40e1d1267b..e0eacde1e4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -986,6 +986,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Brushes panel's Delete Brush button and panel menu item ask "Delete the selected brushes?" with Yes and No when none of the brushes is in use. Alt-click (Option-click on macOS) on the button deletes them without asking, as the [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page (archived copy) lists ("Delete without confirmation (except for Layers panel)"). When a stroke uses one of the brushes, the button, Alt-click and the menu item all ask with Remove Strokes and Cancel; Remove Strokes deletes the brushes and the strokes that used them become plain strokes. Tests: `panels::brushes::tests`, `dialogs::brush_delete::tests`. Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). + Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step. In Pattern Brush Options, a menu below the Outer Corner Tile and the Inner Corner Tile sets each to the brush's own corner art (Original), None, or a tile made from the side tile: Auto-Centered stretches one side tile around the corner, Auto-Between bends a side tile on each side into the corner's diagonal, Auto-Sliced cuts a side tile on each side along the diagonal, and Auto-Overlap runs a side tile on each side past the corner. Auto-Sliced masks the tiles at the diagonal, so their outlines stay as drawn. Brushes saved without these choices draw their corners as before (`brush.options` `outer_source`, `inner_source`). Evidence: `tests::pattern_auto_corners_fill_each_corner_of_a_square`, `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), `dialogs::brush_options::tests::pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile` (vectorcraft-ui-egui). From 1c6720a85c43d1297aaff0fa47ddd3929002d336 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 18:33:20 -0800 Subject: [PATCH 009/189] Recolor: a new color group keeps Global Adjust colors in Limit to Library OK on colors opened alone snaps each color the Global Adjust changed to the library's nearest color before saving the new group, as recolor.apply does for a group's colors. --- crates/ui-egui/src/dialogs/recolor.rs | 15 +++++++++++++-- crates/ui-egui/src/tests/recolor.rs | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1f319ca96e..70e69a78c5 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -353,12 +353,23 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); sync(app, &mut d); if d.bool("__newGroup") { - // The new colors with the Global Adjust, as `recolor.apply` gives them to a group. + // The new colors with the Global Adjust, snapped to Limit to Library, as `recolor.apply` + // gives them to a group. let adjust = global_adjust(adjust_values(&d)); + let limit = d.str("limitTo"); + let palette = Some(limit).filter(|l| !l.is_empty()).and_then(|l| swatchlib::limit_palette(&app.session, &l)); let colors: Vec = rows(&d) .into_iter() .filter(|r| !excluded(r)) - .map(|r| to_color(&r).filter(|_| !adjust.is_identity()).map_or_else(|| r["to"].clone(), |c| key(&adjust.apply(c)))) + .map(|r| { + to_color(&r).filter(|_| !adjust.is_identity()).map_or_else( + || r["to"].clone(), + |c| { + let c = adjust.apply(c); + key(&palette.as_ref().map_or(c, |p| p.nearest(c))) + }, + ) + }) .collect(); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 1786b7a614..0e7fe849b2 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -642,6 +642,24 @@ fn global_adjust_changes_every_color_at_once() { } } +/// Colors opened alone with Limit to Library: OK saves the new colors with the Global Adjust as a +/// new color group, each snapped to the library again, as `recolor.apply` gives them to a group. +#[test] +fn global_adjust_on_a_new_group_keeps_its_colors_in_the_library() { + let mut app = app(); + app.run("ui.recolorDialog", json!({"colors": ["#123456", "#abcdef"], "library": ""})).unwrap(); + assert_eq!(field(&app, "limitTo"), "web-safe-216"); + let web = |k: &Value| vectorcraft_engine::cmd::color_value(k).unwrap().to_rgb().iter().all(|v| ((v * 5.0).round() - v * 5.0).abs() < 1e-3); + let rows: Vec = field(&app, "rows").as_array().unwrap().iter().map(|r| r["to"].clone()).collect(); + assert!(rows.iter().all(web), "the rows open snapped: {rows:?}"); + set(&mut app, "globalAdjust", json!({"brightness": -60})); + dialogs::confirm(&mut app).unwrap(); + let keys = group_keys(&app, "Color Group"); + assert_eq!(keys.len(), 2); + assert_ne!(keys, rows, "the Global Adjust changed the colors"); + assert!(keys.iter().all(web), "every group color is a library color: {keys:?}"); +} + /// The Assign tab's per-row hex fields are named by their row, not all "Color": a screen reader can /// tell the second from the first. #[test] From 9dbbe52a3c3d34cd2a0e139780bb94d340c1c908 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:13:31 -0800 Subject: [PATCH 010/189] Variables: Edit Data Set keeps an empty text value when OK changes nothing A row's empty text value fills its field with nothing, the same as a row without a value for that variable, and OK left every empty field out of dataset.set. An untouched OK therefore removed the empty value, and selecting the row afterward left the previous row's text on the art. Edit Data Set now marks the fields that hold the row's empty text value and keeps those values on OK. Typing in such a field, or setting it with ui.dialog.set, removes the mark, so emptying it still unsets the variable. --- crates/ui-egui/src/dialogs.rs | 6 +- crates/ui-egui/src/dialogs/variables.rs | 79 +++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6e86304e21..82cd2b8b00 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -443,11 +443,15 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { } /// Set `field` of `d` to `value` for `ui.dialog.set`, as the dialog's own control for it does: a -/// Pattern Brush Options corner tile set this way is saved by OK, as one chosen from its menu is. +/// Pattern Brush Options corner tile set this way is saved by OK, as one chosen from its menu is, +/// and an Edit Data Set field set this way is no longer the row's empty text value. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); } + if d.kind == variables::KIND { + variables::note_set(d, &field); + } d.fields.insert(field, value); } diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index d63ea55620..58cb18c861 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -86,6 +86,13 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool let Some(current) = vars.dataset(&name) else { return true }; fields.insert("name".into(), json!(name)); value_fields(&vars, Some(¤t.values), &mut fields); + // An empty text value is a value, but its field looks like a field with no value: + // mark it so OK keeps it until the field is edited. + for (var, value) in ¤t.values { + if matches!(value, DataValue::Text(t) if t.is_empty()) { + fields.insert(empty_marker(&value_key(var)), json!(true)); + } + } } "dataset.select" => { fields.insert("name".into(), json!("")); @@ -142,6 +149,12 @@ fn value_key(name: &str) -> String { format!("value:{name}") } +/// The key that marks the field `key` as holding the edited row's empty text value. Editing the +/// field removes the mark. +fn empty_marker(key: &str) -> String { + format!("__empty:{key}") +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { @@ -227,11 +240,23 @@ fn text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> egui::Respo let mut s = d.str(key); let r = ui.add(egui::TextEdit::singleline(&mut s).align(egui::Align2::LEFT_CENTER).desired_width(width)); if r.changed() { - d.fields.insert(key.into(), json!(s)); + set_text(d, key, s); } r } +/// Write a typed `s` into `key`. +fn set_text(d: &mut Dialog, key: &str, s: String) { + note_set(d, key); + d.fields.insert(key.into(), json!(s)); +} + +/// Records that `field` was typed in or set by `ui.dialog.set`: it no longer holds the row's +/// empty text value, so emptying it unsets the variable. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + d.fields.remove(&empty_marker(field)); +} + /// A checkbox for `key`, written back as it is toggled, which screen readers call `name`. fn checkbox(ui: &mut egui::Ui, d: &mut Dialog, key: &str, name: &str) { let b = d.bool(key); @@ -256,7 +281,8 @@ fn dropdown(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[&str], widt } /// The `values` object the dialog's fields mean: a text, image or graph variable whose field is -/// empty carries no value in this row, and a visibility checkbox is always a value — its false, +/// empty carries no value in this row, except a text variable whose value in the edited row was +/// already the empty text, which keeps it. A visibility checkbox is always a value — its false, /// too. fn values_of(d: &Dialog, vars: &Variables) -> Value { let mut out = serde_json::Map::new(); @@ -265,7 +291,7 @@ fn values_of(d: &Dialog, vars: &Variables) -> Value { match v.kind { VariableKind::Text | VariableKind::Image | VariableKind::Graph => { let text = d.str(&key); - if !text.is_empty() { + if !text.is_empty() || (v.kind == VariableKind::Text && d.bool(&empty_marker(&key))) { out.insert(v.name.clone(), json!(text)); } } @@ -282,7 +308,7 @@ fn text_area(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) { let mut s = d.str(key); let r = ui.add(egui::TextEdit::multiline(&mut s).desired_width(width).desired_rows(4)); if r.changed() { - d.fields.insert(key.into(), json!(s)); + set_text(d, key, s); } } @@ -371,6 +397,51 @@ mod tests { assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true})); } + #[test] + fn an_untouched_edit_keeps_an_empty_text_value() { + let mut app = app_with_variables(); + let id = app.run("text.create", json!({"x": 10, "y": 10, "text": "x"})).unwrap()["id"].as_u64().unwrap(); + app.run("variable.bind", json!({"variable": "Title", "ids": [id]})).unwrap(); + app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "", "Badge": true}})).unwrap(); + app.run("dataset.new", json!({"name": "Row 2", "values": {"Title": "Bob", "Badge": true}})).unwrap(); + app.run("dataset.select", json!({"name": "Row 1"})).unwrap(); + open(&mut app, "dataset.set", None); + assert_eq!(app.ui.dialog.as_ref().unwrap().str(&value_key("Title")), ""); + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"]["Title"], json!({"text": ""}), "OK with nothing changed keeps the empty text"); + app.run("dataset.select", json!({"name": "Row 2"})).unwrap(); + app.run("dataset.select", json!({"name": "Row 1"})).unwrap(); + assert_eq!(app.run("text.getRange", json!({"id": id})).unwrap()["text"], "", "the row still empties the text"); + // A field the user empties on a row that had a value still leaves the variable unset. + app.run("dataset.select", json!({"name": "Row 2"})).unwrap(); + open(&mut app, "dataset.set", None); + app.ui.dialog.as_mut().unwrap().fields.insert(value_key("Title"), json!("")); + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][1]["values"]["Title"], json!(null)); + // Typing into the empty text value's field and emptying it again unsets it too, and so + // does the same edit through `ui.dialog.set`. + for typed in [true, false] { + app.run("dataset.set", json!({"name": "Row 1", "values": {"Title": "", "Badge": true}})).unwrap(); + app.run("dataset.select", json!({"name": "Row 1"})).unwrap(); + open(&mut app, "dataset.set", None); + { + let d = app.ui.dialog.as_mut().unwrap(); + for s in ["a", ""] { + if typed { + set_text(d, &value_key("Title"), s.into()); + } else { + crate::dialogs::set_field(d, value_key("Title"), json!(s)); + } + } + } + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"]["Title"], json!(null), "typed: {typed}"); + } + } + #[test] fn selecting_a_dataset_from_the_dialog_applies_it() { let mut app = app_with_variables(); From 43b2733fc96b865416b0fd25fb05495b4a4dc66e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 12:17:39 -0800 Subject: [PATCH 011/189] Tests: move the empty text value test next to the new data set test --- crates/ui-egui/src/dialogs/variables.rs | 38 ++++++++++++------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/dialogs/variables.rs b/crates/ui-egui/src/dialogs/variables.rs index 58cb18c861..7fd8639ab8 100644 --- a/crates/ui-egui/src/dialogs/variables.rs +++ b/crates/ui-egui/src/dialogs/variables.rs @@ -378,25 +378,6 @@ mod tests { assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": false})); } - #[test] - fn editing_a_dataset_opens_with_the_rows_own_values() { - let mut app = app_with_variables(); - app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Hello", "Badge": false}})).unwrap(); - app.run("dataset.set", json!({"name": "Row 1", "values": {"Badge": true}})).unwrap(); - open(&mut app, "dataset.set", None); - { - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.str("name"), "Row 1"); - assert_eq!(d.str(&value_key("Title")), "", "the row carries no value for it"); - assert!(d.bool(&value_key("Badge")), "the row's own value"); - } - app.ui.dialog.as_mut().unwrap().fields.insert(value_key("Title"), json!("Changed")); - crate::dialogs::confirm(&mut app).unwrap(); - let sets = app.run("dataset.list", json!({})).unwrap(); - assert_eq!(sets["datasets"][0]["values"]["Title"], json!({"text": "Changed"})); - assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true})); - } - #[test] fn an_untouched_edit_keeps_an_empty_text_value() { let mut app = app_with_variables(); @@ -442,6 +423,25 @@ mod tests { } } + #[test] + fn editing_a_dataset_opens_with_the_rows_own_values() { + let mut app = app_with_variables(); + app.run("dataset.new", json!({"name": "Row 1", "values": {"Title": "Hello", "Badge": false}})).unwrap(); + app.run("dataset.set", json!({"name": "Row 1", "values": {"Badge": true}})).unwrap(); + open(&mut app, "dataset.set", None); + { + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("name"), "Row 1"); + assert_eq!(d.str(&value_key("Title")), "", "the row carries no value for it"); + assert!(d.bool(&value_key("Badge")), "the row's own value"); + } + app.ui.dialog.as_mut().unwrap().fields.insert(value_key("Title"), json!("Changed")); + crate::dialogs::confirm(&mut app).unwrap(); + let sets = app.run("dataset.list", json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"]["Title"], json!({"text": "Changed"})); + assert_eq!(sets["datasets"][0]["values"]["Badge"], json!({"visible": true})); + } + #[test] fn selecting_a_dataset_from_the_dialog_applies_it() { let mut app = app_with_variables(); From fa8d3b8de4f5800b4b9864374dc4f64b1c0a6ca9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:05:22 -0800 Subject: [PATCH 012/189] Fix #3797: documents open in Preview, and Outline is a setting of each document View > Outline was one app-wide flag saved in the interface preferences, so after Cmd+Y every later launch drew every opened or new document as outlines, with no fills. The flag is now part of each document's view: a document opens in Preview, each tab shows its own Outline or Preview, and the setting is not saved at launch. An older preferences file that holds the flag still loads, and its value is ignored. The Outline command and ui.set's outline act on the active document and are an error without one. --- crates/ui-egui/src/app/view.rs | 7 +++- crates/ui-egui/src/canvas.rs | 8 ++-- crates/ui-egui/src/canvas/outline.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 62 +++++++++++++++++++++++++++- crates/ui-egui/src/chrome/tabs.rs | 10 ++++- crates/ui-egui/src/chrome/tests.rs | 12 ++++++ crates/ui-egui/src/control.rs | 6 ++- crates/ui-egui/src/control/tests.rs | 18 ++++++++ crates/ui-egui/src/menus/labels.rs | 2 +- crates/ui-egui/src/menus/run.rs | 6 ++- crates/ui-egui/src/menus/state.rs | 3 +- crates/ui-egui/src/state.rs | 9 ++-- docs/control-protocol.md | 2 +- 13 files changed, 129 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 6aac1150e3..fd38968d2d 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -72,6 +72,11 @@ impl VectorcraftApp { self.session.active_index().and_then(|i| self.views.get(i)) } + /// Whether the active document is in Outline view (View › Outline); false without one. + pub fn outline_view(&self) -> bool { + self.view().is_some_and(|v| v.outline) + } + /// The zero point shown by rulers and position fields: the document's with global rulers, the /// active artboard's with artboard rulers. Command coordinates stay absolute. pub(crate) fn ruler_origin(&self) -> vectorcraft_geom::Point { @@ -88,7 +93,7 @@ impl VectorcraftApp { pub fn view_info(&self) -> ViewInfo { ViewInfo { zoom: self.view().map(|v| v.zoom).unwrap_or(1.0), - outline: self.ui.view.outline, + outline: self.outline_view(), smart_guides: self.ui.view.smart_guides, guides: self.ui.view.guides, snap_to_grid: self.ui.view.snap_to_grid, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4850b9e259..c867918bf2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -492,7 +492,7 @@ fn cache_key( cy: v.center.y, w, h, - outline: app.ui.view.outline, + outline: app.outline_view(), trim: app.ui.view.trim_view, templates: app.ui.view.templates, guides: app.ui.view.guides, @@ -560,7 +560,7 @@ fn frame_options( mask_view: Option, smooth_images: bool, ) -> vectorcraft_render::RenderOptions { - let opts = vectorcraft_render::RenderOptions { outline: app.ui.view.outline, background: None, artboards: false, ..Default::default() }; + let opts = vectorcraft_render::RenderOptions { outline: app.outline_view(), background: None, artboards: false, ..Default::default() }; vectorcraft_render::RenderOptions { proof: vectorcraft_render::proof::active_proof(), overprint_preview: vectorcraft_render::proof::overprint_preview_on(), @@ -669,7 +669,7 @@ fn paint_paper(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: &Xf, // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). let setup = &doc.setup; painter.rect_filled(rect, 0.0, if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }); - } else if !app.ui.view.outline { + } else if !app.outline_view() { let setup = &doc.setup; let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent).then(|| checker_texture(ui.ctx(), setup)); let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }; @@ -687,7 +687,7 @@ fn paint_paper(app: &VectorcraftApp, ui: &Ui, painter: &egui::Painter, xf: &Xf, } } } - } else if app.ui.view.outline { + } else if app.outline_view() { for ab in &doc.artboards { painter.add(Shape::convex_polygon(xf.quad(ab.rect), Color32::WHITE, Stroke::NONE)); } diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index b5d14e1519..9d1794ab7d 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -184,7 +184,7 @@ pub(super) fn hit_with( let prefs = &app.session.prefs; let opt = vectorcraft_doc::hit::HitOptions { tol: prefs.selection_tolerance / zoom, - outline: app.ui.view.outline, + outline: app.outline_view(), path_only: prefs.object_selection_by_path_only, type_path_only: prefs.type_selection_by_path_only, scope: app.session.active().and_then(|st| st.isolation), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4b59bdb8f6..1d1eb43148 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2588,7 +2588,7 @@ fn pan_fills_the_area_the_last_frame_leaves() { assert!(app.canvas.fill_worker.as_ref().unwrap().pending.is_none(), "the late fill was taken"); // A pan with Outline turned on: the frame shown's options are not the ones asked for, and // no fill is asked for. - app.ui.view.outline = true; + app.view_mut().unwrap().outline = true; app.view_mut().unwrap().center = Point::new(400.0, 150.0); frame(&mut app); assert!(jobs.try_iter().last().is_some_and(|j| j.key.outline), "the outline frame is on the worker"); @@ -3521,7 +3521,7 @@ fn scrolls_and_pans_move_the_view_by_whole_device_pixels() { /// another document, or when the device pixels a point changed. #[test] fn a_scrolls_leftover_pixel_part_carries_only_to_the_same_view() { - let view = View { zoom: 1.0, center: Point::new(100.0, 100.0), fitted: true, rotation: 0.0, artboard: 0 }; + let view = View { zoom: 1.0, center: Point::new(100.0, 100.0), fitted: true, rotation: 0.0, artboard: 0, outline: false }; let mut v = view; let rest = scroll_by(&mut v, 1, 1.0, vec2(0.4, -0.3), ScrollRest::default()); assert_eq!(v.center, view.center, "less than half a pixel does not move the view"); @@ -3765,6 +3765,64 @@ fn show_live_paint_gaps_draws_the_selected_groups_gaps_in_their_preview_color() assert!(!serde_json::from_value::(saved).unwrap().view.live_paint_gaps); } +/// #3797: View › Outline is a setting of each document's view. A document opened or made after +/// another was put in Outline opens in Preview, where a click inside its fill picks it, and each +/// document keeps its own setting. +#[test] +fn outline_is_per_document_and_new_documents_start_in_preview() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + app.sync_views(); + let inside = Point::new(70.0, 70.0); + let picks_fill = |app: &VectorcraftApp| super::outline::hit_at(app, inside, 1.0).is_some(); + assert!(picks_fill(&app), "Preview picks the fill"); + app.run("view.outline", json!({})).unwrap(); + assert!(app.outline_view() && app.view_info().outline); + assert!(!picks_fill(&app), "Outline picks only the path"); + // An SVG opened now opens in Preview, its fill drawn and picked. + let svg = + br##""##; + crate::io::open_bytes(&mut app, "b.svg", svg, None).unwrap(); + assert_eq!(app.session.active_index(), Some(1)); + assert!(!app.outline_view() && !app.view_info().outline, "the opened document is in Preview"); + assert!(picks_fill(&app)); + assert_eq!(crate::menus::dynamic_label(&app, "view.outline", "Outline"), "Outline"); + assert_eq!(crate::menus::checked(&app, "view.outline", &json!({})), Some(false)); + // A new document opens in Preview too. + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + assert!(!app.outline_view()); + // The first document is still in Outline. + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + assert!(app.outline_view() && !picks_fill(&app)); + assert_eq!(crate::menus::dynamic_label(&app, "view.outline", "Outline"), "Preview"); + assert_eq!(crate::menus::checked(&app, "view.outline", &json!({})), Some(true)); + // Without a document there is nothing to put in Outline. + while !app.session.documents().is_empty() { + app.session.execute("file.close", &json!({})).unwrap(); + } + app.sync_views(); + assert!(!app.outline_view() && !crate::menus::enabled(&app, "view.outline")); + assert!(app.run("view.outline", json!({})).is_err()); +} + +/// #3797: a preferences file saved while View › Outline was an interface setting still loads, with +/// its other view settings, and its Outline value does not put a document in Outline. +#[test] +fn old_outline_preference_loads_but_does_not_restore_outline() { + let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); + assert!(saved["view"].get("outline").is_none(), "Outline is not saved with the interface"); + saved["view"]["outline"] = json!(true); + saved["view"]["rulers"] = json!(true); + let ui = serde_json::from_value::(saved).unwrap().sanitized(); + assert!(ui.view.rulers, "the other view settings load"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui = ui; + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + assert!(!app.outline_view(), "a new document is in Preview"); +} + /// #511: a star shows a widget in each of its ten corners with Direct Selection (none with /// the Selection tool: it isn't a live shape); View → Hide Corner Widget hides them. #[test] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 99ca027cb2..fe01e91cc4 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -12,6 +12,13 @@ pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bo format!("{}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom, display_print_size).replace('%', " %")) } +/// The title of open document `i`'s tab, with its own view's zoom and Outline or Preview. +pub(super) fn doc_tab_title(app: &VectorcraftApp, i: usize, d: &vectorcraft_engine::DocState) -> String { + let view = app.views.get(i); + let zoom = view.map_or(1.0, |v| v.zoom); + tab_title(d, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) +} + /// Whether a document tab's × comes before its title (macOS) rather than after it (Windows, /// Linux and the web). pub(super) const CLOSE_BEFORE_TITLE: bool = cfg!(target_os = "macos"); @@ -46,8 +53,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { .iter() .enumerate() .map(|(i, d)| { - let zoom = app.views.get(i).map(|v| v.zoom).unwrap_or(1.0); - let title = tab_title(d, zoom, app.ui.view.outline, app.session.prefs.display_print_size); + let title = doc_tab_title(app, i, d); let color = if Some(i) == active { t.text_strong } else { t.text_dim }; (title.clone(), ui.painter().layout_no_wrap(title, theme::semibold(title_size), color)) }) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index f32d3a9445..842ee1bc16 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -866,6 +866,18 @@ fn the_tab_title_names_the_opacity_mask_while_it_is_edited() { assert!(title(&s).ends_with("(RGB/Preview)")); } +/// #3797: each document's tab names its own Outline or Preview. +#[test] +fn only_the_outlined_documents_tab_reads_outline() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.run("view.outline", json!({})).unwrap(); + let titles: Vec = app.session.documents().iter().enumerate().map(|(i, d)| super::tabs::doc_tab_title(&app, i, d)).collect(); + assert!(titles[0].ends_with("(RGB/Preview)"), "{titles:?}"); + assert!(titles[1].ends_with("(RGB/Outline)"), "{titles:?}"); +} + /// One headless frame of the Control bar; returns the isolation button's rectangle, if it shows. fn isolation_button(app: &mut crate::VectorcraftApp, ctx: &egui::Context, events: Vec) -> Option { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 300.0)); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index a300757138..c586420a23 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -593,6 +593,10 @@ fn synthetic_click(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlR fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { let p = &req.params; let s = |k: &str| p.get(k).and_then(Value::as_str); + // Outline is a setting of the active document's view: without one, nothing is set. + if p.get("outline").is_some_and(Value::is_boolean) && app.session.active().is_none() { + return err("no document"); + } let mut r = Ok(Value::Null); if let Some(b) = s("brightness") { r = app.run("window.brightness", json!({"brightness": b})); @@ -613,7 +617,7 @@ fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { if let Some(want) = p.get(k).and_then(Value::as_bool) { let cur = match k { "rulers" => app.ui.view.rulers, - "outline" => app.ui.view.outline, + "outline" => app.outline_view(), "grid" => app.ui.view.grid, "smartGuides" => app.ui.view.smart_guides, _ => app.ui.view.bounding_box, diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 3e27607f39..ded29508ad 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -22,6 +22,24 @@ fn ui_set_turns_the_image_trace_preview_off_and_on() { } } +/// #3797: `ui.set` `outline` sets the active document's view; without a document it is an error +/// and sets nothing else either. +#[test] +fn ui_set_outline_sets_the_active_documents_view() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + for params in [json!({"outline": false}), json!({"outline": true, "grid": true})] { + let r = input_request(&mut app, "ui.set", params); + assert_eq!(r["ok"], false, "{r}"); + } + assert!(!app.ui.view.grid, "nothing is set"); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = input_request(&mut app, "ui.set", json!({"outline": true})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.outline_view()); + assert_eq!(app.views.iter().map(|v| v.outline).collect::>(), [false, true], "the other document stays in Preview"); +} + #[test] fn the_image_trace_preview_is_a_command() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index c95a17c461..d9888228c4 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -17,7 +17,7 @@ pub fn dynamic_label(app: &VectorcraftApp, id: &str, label: &str) -> String { fn view_toggle_label(app: &VectorcraftApp, id: &str) -> Option { let v = &app.ui.view; let text: String = match id { - "view.outline" => if v.outline { "Preview" } else { "Outline" }.into(), + "view.outline" => if app.outline_view() { "Preview" } else { "Outline" }.into(), "window.workspace.reset" => format!("Reset {}", app.ui.workspace), "view.edges" => if v.edges { "Hide Edges" } else { "Show Edges" }.into(), "view.template" => if v.templates { "Hide Template" } else { "Show Template" }.into(), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e7f80ecd81..b9e0b6ace9 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -184,7 +184,11 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { crate::panel_docking::reveal_panel(app, "separations").and_then(|_| app.session.execute(id, p).map_err(|e| e.to_string())) } - "view.outline" => flag(&mut app.ui.view.outline), + // Outline or Preview is a setting of the active document's view. + "view.outline" => match app.view_mut() { + Some(v) => flag(&mut v.outline), + None => Err("no document".into()), + }, _ => return None, }; Some(r) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index ad7f88c5c6..42456d7427 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -41,7 +41,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { selected_text(false).is_some_and(|t| t.vertical == (id == "type.orientation.vertical")) } "type.opticalMarginAlignment" => crate::panels::character::shared_text_flag(app, |t| t.optical_margin) == Some(true), - "view.outline" => v.outline, + "view.outline" => app.outline_view(), "view.pixelPreview" => v.pixel_preview, "view.trimView" => v.trim_view, "view.snapToPixel" => v.snap_to_pixel, @@ -205,6 +205,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { | "view.fitArtboard" | "view.fitAll" | "view.actualSize" + | "view.outline" | "view.rotate" => app.session.active().is_some(), "view.rotateToSelection" | crate::addons::arrange::ZOOM => app.session.active().is_some_and(|d| !d.selection.objects.is_empty()), id if id.starts_with("file.openRecent") => recent_slot(app, id).is_some(), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a78ee2b0f..533500d698 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -21,11 +21,15 @@ pub struct View { /// Size show it. #[serde(default)] pub artboard: usize, + /// View › Outline: the document's art is drawn as outlines. Each document has its own, and a + /// document opens in Preview. + #[serde(default)] + pub outline: bool, } impl Default for View { fn default() -> Self { - Self { zoom: 1.0, center: Point::new(306.0, 396.0), fitted: false, rotation: 0.0, artboard: 0 } + Self { zoom: 1.0, center: Point::new(306.0, 396.0), fitted: false, rotation: 0.0, artboard: 0, outline: false } } } @@ -45,6 +49,7 @@ impl View { fitted: true, rotation: if v.rotation.is_finite() { v.rotation } else { 0.0 }, artboard: 0, + outline: false, }) } } @@ -232,7 +237,6 @@ pub struct ViewFlags { pub guides: bool, pub smart_guides: bool, pub bounding_box: bool, - pub outline: bool, pub pixel_preview: bool, pub snap_to_grid: bool, pub snap_to_point: bool, @@ -271,7 +275,6 @@ impl Default for ViewFlags { guides: true, smart_guides: true, bounding_box: true, - outline: false, pixel_preview: false, snap_to_grid: false, snap_to_point: true, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8f09432303..d17704a530 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -101,7 +101,7 @@ the two can still win that race. | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | | `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls and Cmd- or Alt-wheel (Option on the Mac) zooms about the pointer; with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it | -| `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | +| `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | | `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value}` or `{fields: [{field, value}…]}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`), `__` fields, `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | From 06d037c1b254a2b944fcd8d48da17d2bc54d1ac4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:39:10 -0800 Subject: [PATCH 013/189] .ai import: a clipping path keeps its stroke A clipping path painted with a stroke (`W S`, `W B`) lost the stroke when a .ai file opened from its editing data. The clipping path now keeps it, and it paints over the clipped art as a clipping path's stroke does in VectorCraft. A gradient-filled clipping path stroked with `1 BB` or `2 BB` put the stroke on the painted copy of its fill, under the clipped art; it now goes on the clipping path too. Several clipping paths in one group make one compound path, which keeps their stroke, opacity and blend mode when they all have the same ones. --- crates/eps/src/import/ai/read/art.rs | 18 ++++++-- crates/eps/src/import/ai/read/containers.rs | 13 +++++- crates/eps/src/import/ai/tests.rs | 47 +++++++++++++++++++++ docs/file-format-parity.md | 2 +- 4 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index a32ea81daa..5e10d789f1 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -185,7 +185,8 @@ impl<'a> Reader<'a> { ..FillLayer::new(fill_paint.clone().unwrap_or(gs.fill.clone())) })); } - if stroke && !clip { + // A clipping path keeps its stroke, which paints over the art it clips. + if stroke { let mut st = StrokeLayer::new(stroke_paint.unwrap_or(gs.stroke.clone()), gs.width); st.cap = gs.cap; st.join = gs.join; @@ -297,11 +298,20 @@ impl<'a> Reader<'a> { Ok(()) } - /// Stroke the path just painted (a gradient-filled one, `1 BB` or `2 BB`) with the stroke's state. + /// Stroke the path just painted (a gradient-filled one, `1 BB` or `2 BB`) with the stroke's state. A clipping path + /// takes the stroke itself, not the painted copy of its fill. pub(super) fn stroke_last(&mut self) { let gs = self.gs.clone(); - let Some(n) = self.last_object() else { return }; - if !matches!(n.kind, NodeKind::Path { clipping: false, .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { + if !self.after_object { + return; + } + let Some(kids) = self.frames.last_mut().map(|f| &mut f.children) else { return }; + let Some(mut at) = kids.len().checked_sub(1) else { return }; + if kids.get(at).is_some_and(|n| self.clip_fills.contains(&n.id)) && at > 0 { + at -= 1; + } + let Some(n) = kids.get_mut(at) else { return }; + if !matches!(n.kind, NodeKind::Path { .. }) || n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))) { return; } let mut st = StrokeLayer::new(gs.stroke.clone(), gs.width); diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 8d69d8114e..a894b425bf 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -195,8 +195,19 @@ impl<'a> Reader<'a> { 1 => clip.pop().map(|(_, n)| n), _ => { let rule = clip.first().map_or(FillRule::NonZero, |(_, n)| path_rule(n)); + // The compound path keeps the clipping paths' stroke, opacity and blend mode when they all have the same + // ones: it has one appearance for all its paths. + let look = |n: &Node| (n.appearance.clone(), n.opacity, n.blend); + let shared = + clip.split_first().and_then(|((_, first), others)| others.iter().all(|(_, n)| look(n) == look(first)).then(|| look(first))); let children = clip.into_iter().map(|(_, n)| Arc::new(n)).collect(); - Some(Node::new(self.doc.alloc_id(), NodeKind::Compound { children, rule })) + let mut n = Node::new(self.doc.alloc_id(), NodeKind::Compound { children, rule }); + if let Some((appearance, opacity, blend)) = shared { + n.appearance = appearance; + n.opacity = opacity; + n.blend = blend; + } + Some(n) } }; let clips = clip_node.is_some(); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index a0a24d8650..4d3e5e01c3 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -360,6 +360,53 @@ fn compound_paths_and_clipping() { assert!(*clip && matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); } +/// A stroked clipping path (`W S`, `W B`, or a gradient fill with `1 BB`) keeps its stroke on the clipping path, and a +/// fill goes on the painted copy under the clipped art. +#[test] +fn a_clipping_paths_stroke_stays_on_the_clipping_path() { + let blue = Some(Color::rgb(0.0, 0.0, 1.0)); + let red = Some(Color::rgb(1.0, 0.0, 0.0)); + // (clipping, fill colour, a gradient fill, stroke colour and width) of each of the clipping group's children. + let children = |doc: &Document| { + let NodeKind::Group { children, clip: true } = &art(doc)[0].kind else { panic!("{:?}", art(doc)[0].kind) }; + children + .iter() + .map(|c| { + let clipping = matches!(c.kind, NodeKind::Path { clipping: true, .. }); + (clipping, fill(c).color(), matches!(fill(c), Paint::Gradient(_)), c.appearance.stroke().map(|s| (s.paint.color(), s.width))) + }) + .collect::>() + }; + let under = rect_path(0.0, 0.0, 30.0, 30.0); + let clip = rect_path(5.0, 5.0, 25.0, 25.0); + let stroked = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nS\nQ\n"); + assert_eq!(children(&read_ok(&layer(&stroked)).doc), [(true, None, false, Some((blue, 3.0))), (false, red, false, None)]); + let both = format!("0 Ae\nq\n{RED}{under}f\n0 1 0 0 0 1 0 Xa\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nB\nQ\n"); + assert_eq!( + children(&read_ok(&layer(&both)).doc), + [(true, None, false, Some((blue, 3.0))), (false, Some(Color::rgb(0.0, 1.0, 0.0)), false, None), (false, red, false, None)] + ); + let defs = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n0 0 0 0 1 0 0 2 0 6 %_BS\n%_0 0 0 0 1 0 0 2 0 6 0 0 Bs\n\ + %_0 0 0 0 0 0 1 2 1 6 100 50 Bs\nBD\n%AI5_EndGradient\n"; + let gradient = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{clip}W\nBb\n0 0 0 0 Bh\n1 (G) 5 5 0 20 1 0 0 1 0 0 1 Bg\nf\n1 BB\nQ\n"); + assert_eq!( + children(&read_ok(&format!("{defs}{}", layer(&gradient))).doc), + [(true, None, false, Some((blue, 3.0))), (false, None, true, None), (false, red, false, None)] + ); + // Several clipping paths clip as one compound path, which keeps their stroke when they all have the same one. + let inner = rect_path(10.0, 10.0, 20.0, 20.0); + let compound_stroke = |first: &str, second: &str| { + let body = format!("0 Ae\nq\n{RED}{under}f\n0 0 1 0 0 0 1 XA\n3 w\n{first}{clip}W\nS\n{second}{inner}W\nS\nQ\n"); + let doc = read_ok(&layer(&body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + assert!(matches!(children[0].kind, NodeKind::Compound { .. }), "{:?}", children[0].kind); + (children[0].appearance.stroke().map(|s| (s.paint.color(), s.width)), children[0].opacity, children[0].blend) + }; + assert_eq!(compound_stroke("", ""), (Some((blue, 3.0)), 1.0, BlendMode::Normal)); + assert_eq!(compound_stroke("9 0.5 0 0 0 Xy\n", ""), (Some((blue, 3.0)), 0.5, BlendMode::Lighten)); + assert_eq!(compound_stroke("", "5 w\n"), (None, 1.0, BlendMode::Normal), "strokes that differ"); +} + /// A clipping group's clipping path can sit alone in a group of its own, after the art it clips (`q … u W n U /// … Q`): it still clips the clipping group. #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 11440516d7..1f2f14bd81 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -88,7 +88,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format From db1144650232e481c3c9c3bffbfd399e349a203e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:55:44 -0800 Subject: [PATCH 014/189] .ai import: legacy type keeps its spacing, hanging punctuation and hyphenation Legacy type (`To` ... `TO`) now reads `min opt max TC` and `min opt max TW` into the paragraph's letter and word spacing, `hangingQuotes Tq` into Roman hanging punctuation, and `hyphenate limit lead tail max Th` into hyphenation on or off, After First, Before Last and the Hyphen Limit (0 when the limit flag is 0). Values are kept to the ranges the Justification and Hyphenation options take, and a spacing triple out of order goes back to its default. Operands of the legacy type attributes are read by their place: an attribute whose operands are missing, are not numbers, or are flags other than 0 and 1 stays as it was. Before, a value that was not a number shifted the later operands (`5 /x 7 Ti` set indents of 5, 7 and 0), and a bad `TA` or `Ta` turned kerning on or set the alignment to left. One long `Tx` no longer goes past the reader's limit on characters. --- crates/engine/tests/import_fuzz.rs | 7 + crates/eps/src/import/ai/legacy_text.rs | 162 ++++++++++++++++----- crates/eps/src/import/ai/read/ops.rs | 16 +- crates/eps/src/import/ai/tests.rs | 107 ++++++++++++++ crates/eps/src/import/tests_illustrator.rs | 11 ++ docs/file-format-parity.md | 3 +- 6 files changed, 260 insertions(+), 46 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 931963de39..c54c8e1335 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3310,6 +3310,13 @@ fn arb_ai_token() -> impl Strategy { "9 Ta", "1e308 -1e308 1e308 Ti", "0 1 Tk", + "-1e308 0 1e308 TC", + "1e308 -1 5 TW", + "/x 100 200 TW", + "1 Tq", + "7 Tq", + "1 1 1e308 -1e308 4e9 Th", + "1 1 (2) 3 4 Th", "[39/quotesingle 128/Euro/eacute/nosuch 300/x TE", "[1e308/a -1/b TE", "\n%AI3_BeginEncoding: _Helvetica Helvetica\n[/_Helvetica/Helvetica 0 0 1 TZ\n%AI3_EndEncoding AdobeType\n", diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index 126619c13e..fec2539304 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -1,6 +1,7 @@ //! Type in the legacy format (version 7 specification §15): text objects `type To` … `TO`, their //! text path (`a b c d tx ty startPt Tp`, an area's frame or the path type runs along, `TP`), the -//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`), the paint style, and +//! modal character and paragraph attributes (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's +//! letter and word spacing `TC TW`, hanging punctuation `Tq` and hyphenation `Th`), the paint style, and //! the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Final-form operators (the //! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the //! file's `TE` encoding, else as Windows-1252; a re-encoded font `/_name` is the font its @@ -78,8 +79,23 @@ impl TypeState { } } -fn num(vals: &[V], i: usize) -> Option { - vals.iter().filter_map(V::num).nth(i).filter(|v| v.is_finite()) +/// An operator's `N` operands, the last `N` values before it, when each is a finite number. +fn nums(vals: &[V]) -> Option<[f64; N]> { + let operands = vals.get(vals.len().checked_sub(N)?..)?; + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(operands) { + *o = v.num().filter(|n| n.is_finite())?; + } + Some(out) +} + +/// A flag operand: 0 or 1. +fn flag(v: f64) -> Option { + match v { + 0.0 => Some(false), + 1.0 => Some(true), + _ => None, + } } impl Reader<'_> { @@ -110,23 +126,28 @@ impl Reader<'_> { /// `type To`: a text object begins. pub(super) fn begin_text(&mut self, vals: &[V], hidden: bool) { self.end_path_quietly(); - let kind = num(vals, 0).map_or(0, |k| k as i64); + let kind = nums::<1>(vals).map_or(0, |[k]| k as i64); self.text = Some(LegacyText { kind, gs: self.gs.clone(), hidden, ..LegacyText::default() }); } /// `a b c d tx ty startPt Tp`: the text path begins. pub(super) fn begin_text_path(&mut self, vals: &[V]) { self.end_path_quietly(); - let n: Vec = vals.iter().filter_map(V::num).collect(); let Some(t) = self.text.as_mut() else { return }; - if let Some(m) = n.get(..6).and_then(|m| <[f64; 6]>::try_from(m).ok()) { + // Seven operands, or the matrix alone. + let (m, start) = match vals.len() { + 7 => (vals.get(..6).and_then(nums::<6>), vals.get(6).and_then(V::num)), + 6 => (nums::<6>(vals), None), + _ => (None, None), + }; + if let Some(m) = m { let m = Affine::new(m); let det = m.determinant(); - if m.as_coeffs().iter().all(|v| v.is_finite()) && det.is_finite() && det.abs() > 1e-12 { + if det.is_finite() && det.abs() > 1e-12 { t.matrix = Some(m); } } - t.start = n.get(6).copied().filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); + t.start = start.filter(|s| s.is_finite() && *s >= 0.0).unwrap_or(0.0); t.in_path = true; } @@ -150,56 +171,122 @@ impl Reader<'_> { } } - /// A character or paragraph attribute. + /// A character or paragraph attribute. An attribute whose operands are missing, are not + /// numbers, or are flags other than 0 and 1 stays as it was. pub(super) fn text_attr(&mut self, w: &str, vals: &[V]) { let st = &mut self.type_state; - let n0 = num(vals, 0); + let n0 = nums::<1>(vals).map(|[v]| v); match w { - "Tr" => st.render = n0.map_or(0, |v| v as i64), + "Tr" => { + if let Some(v) = n0 { + st.render = v as i64; + } + } "Tf" => { - if let Some(name) = vals.iter().find_map(|v| if let V::Name(n) = v { Some(n.clone()) } else { None }) { - let name = st - .fonts - .iter() - .find(|(new, _)| *new == name) - .map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); + // `/name size Tf`, or `/name size ascent descent Tf`. + let Some(at) = vals.iter().position(|v| matches!(v, V::Name(_))) else { return }; + if let Some(V::Name(name)) = vals.get(at) { + let name = + st.fonts.iter().find(|(new, _)| new == name).map_or_else(|| name.trim_start_matches('_').to_string(), |(_, old)| old.clone()); let (family, style) = super::super::super::text::family_style(&name); st.style.font_family = family; st.style.font_style = style; st.style.font_version = None; } - if let Some(size) = num(vals, 0).filter(|s| *s > 0.0) { + if let Some(size) = vals.get(at + 1).and_then(V::num).filter(|s| s.is_finite() && *s > 0.0) { st.style.size = size.min(MAX_SIZE); } } - "Ts" => st.style.baseline_shift = n0.unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE), - "Tz" => { - let scale = |v: f64| v.clamp(1.0, 10_000.0); - st.style.h_scale = n0.map_or(100.0, scale); - st.style.v_scale = num(vals, 1).map_or(100.0, scale); + "Ts" => { + if let Some(v) = n0 { + st.style.baseline_shift = v.clamp(-MAX_SIZE, MAX_SIZE); + } + } + "Tz" => { + // `parallelScale perpendicularScale Tz`; before version 7, `scale Tz`. + let scale = |v: f64| v.clamp(1.0, 10_000.0); + let scales = match vals.len() { + 2 => nums::<2>(vals), + 1 => n0.map(|h| [h, 100.0]), + _ => None, + }; + if let Some([h, v]) = scales { + (st.style.h_scale, st.style.v_scale) = (scale(h), scale(v)); + } + } + "Tt" => { + if let Some(v) = n0 { + st.style.tracking = v.clamp(-10_000.0, 10_000.0); + } + } + "TA" => { + if let Some(auto) = n0.and_then(flag) { + st.style.kerning = if auto { None } else { Some(0.0) }; + } } - "Tt" => st.style.tracking = n0.unwrap_or(0.0).clamp(-10_000.0, 10_000.0), - "TA" => st.style.kerning = if n0 == Some(0.0) { Some(0.0) } else { None }, "Tl" => { - if let Some(l) = n0 { + // `leading paragraphLeading Tl`; before version 7, `leading Tl`. + let leading = match vals.len() { + 2 => nums::<2>(vals), + 1 => n0.map(|l| [l, 0.0]), + _ => None, + }; + if let Some([l, before]) = leading { let l = l.clamp(0.0, MAX_SIZE); // The automatic leading, 120% of the size, stays automatic. st.style.leading = if (l - st.style.size * 1.2).abs() < 1e-3 { None } else { Some(l) }; + st.para.space_before = before.clamp(-MAX_SIZE, MAX_SIZE); } - st.para.space_before = num(vals, 1).unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE); } "Ta" => { - st.para.justify = match n0.map(|v| v as i64) { - Some(1) => Justify::Center, - Some(2) => Justify::Right, - Some(3) => Justify::JustifyLeft, - Some(4) => Justify::JustifyAll, - _ => Justify::Left, + let justify = match n0 { + Some(0.0) => Some(Justify::Left), + Some(1.0) => Some(Justify::Center), + Some(2.0) => Some(Justify::Right), + Some(3.0) => Some(Justify::JustifyLeft), + Some(4.0) => Some(Justify::JustifyAll), + _ => None, + }; + if let Some(j) = justify { + st.para.justify = j; } } "Ti" => { - let indent = |i: usize| num(vals, i).unwrap_or(0.0).clamp(-MAX_SIZE, MAX_SIZE); - (st.para.first_line_indent, st.para.left_indent, st.para.right_indent) = (indent(0), indent(1), indent(2)); + if let Some(i) = nums::<3>(vals) { + let [first, left, right] = i.map(|v| v.clamp(-MAX_SIZE, MAX_SIZE)); + (st.para.first_line_indent, st.para.left_indent, st.para.right_indent) = (first, left, right); + } + } + // `min opt max TC` (letter spacing) and `min opt max TW` (word spacing), in percent of + // a space's width, as the paragraph's Justification options take them. + "TC" | "TW" => { + if let Some(v) = nums::<3>(vals) { + let j = &mut st.para.justification; + if w == "TC" { + j.letter_spacing = v; + } else { + j.word_spacing = v; + } + j.keep_in_range(); + } + } + // `hangingQuotes Tq`. + "Tq" => { + if let Some(on) = n0.and_then(flag) { + st.para.roman_hanging = on; + } + } + // `hyphenate limitHyphLines minLeadHyphen minTailHyphen maxHyphLines Th`, kept to the + // ranges `text.setFormat` takes. + "Th" => { + let Some([on, limit, lead, tail, max]) = nums::<5>(vals) else { return }; + let (Some(on), Some(limit)) = (flag(on), flag(limit)) else { return }; + let letters = |v: f64, lo: f64, hi: f64| v.round().clamp(lo, hi) as u32; + st.para.hyphenate = on; + let h = &mut st.para.hyphenation; + h.after_first = letters(lead, 1.0, 15.0); + h.before_last = letters(tail, 1.0, 15.0); + h.hyphen_limit = if limit { letters(max, 0.0, 25.0) } else { 0 }; } _ => {} } @@ -222,9 +309,12 @@ impl Reader<'_> { t.pending_break = true; return; } - if st.chars >= MAX_CHARS { + // As many characters as the file's allowance has left. + let room = MAX_CHARS.saturating_sub(st.chars); + if room == 0 { return; } + let decoded: String = decoded.chars().take(room).collect(); st.chars += decoded.chars().count(); let gs = &self.gs; let mut style = st.style.clone(); diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 7e7b797468..f48a8df82a 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -276,15 +276,13 @@ impl<'a> Reader<'a> { "TP" => self.end_text_path(), "TO" => self.end_text(hidden)?, "Tx" | "Tj" | "TX" => self.text_body(w, &vals), - "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" => self.text_attr(w, &vals), - // Attributes the reader doesn't keep (kerning pairs, spacing, hanging punctuation, - // Far-Eastern type) and final-form positions (§15.3). - "Tk" | "TK" | "TC" | "TW" | "Tq" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" - | "Tu" | "Xu" => {} - // Hyphenation and tab-ruler attributes the reader doesn't keep either (§22): `Th` - // hyphen control, `XL` hyphenation language, `Xb`/`XB` a tab definition (and the `Xe` - // tab descriptions between them). - "Th" | "XL" | "Xb" | "XB" | "Xe" => {} + "Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" => self.text_attr(w, &vals), + // Attributes the reader doesn't keep (kerning pairs, Far-Eastern type) and final-form + // positions (§15.3). + "Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" | "Tu" | "Xu" => {} + // The hyphenation language and tab rulers, which the reader doesn't keep either (§22): `XL`, + // `Xb`/`XB` a tab definition (and the `Xe` tab descriptions between them). + "XL" | "Xb" | "XB" | "Xe" => {} "TE" => self.te(&vals), // An image whose samples follow in comment lines (read at `%AI5_EndRaster`). "XI" if self.raster.is_some() => { diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 4d3e5e01c3..c53209fbc8 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3149,3 +3149,110 @@ fn an_objects_on_path_group_in_versioned_content_opens_once() { assert_eq!(kids[0].children().unwrap().len(), 5); assert!(kids[0].extras().objects_on_path.is_some()); } + +/// A file in the legacy format (version 7) whose layer holds `art`, crop marks 0 0 200 100. +fn stream7(art: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 3.0\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n", + layer(art) + ) +} + +/// The text objects of a legacy-format file whose layer holds `art`. +fn legacy_texts(art: &str) -> Vec { + let doc = match read(stream7(art).as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc) +} + +fn art_texts(doc: &Document) -> Vec { + art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() +} + +/// Point type at (10, 50): `attrs`, then the characters `text`. +fn point_type(attrs: &str, text: &str) -> String { + format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") +} + +/// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging +/// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its +/// first character, and they last into the next text object. +#[test] +fn legacy_type_keeps_its_spacing_hanging_punctuation_and_hyphenation() { + let two_paragraphs = + point_type("10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th", "One\\r").replace("TO\n", "0 0 5 TC\n0 Tq\n0 0 4 5 6 Th\n(Two) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "Three"))); + assert_eq!(texts.len(), 2); + let one = texts[0].para_at(0); + assert_eq!(one.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(one.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(one.roman_hanging && one.hyphenate); + let h = &one.hyphenation; + assert_eq!((h.after_first, h.before_last, h.hyphen_limit), (2, 3, 4)); + assert_eq!(h.words_longer_than, vectorcraft_doc::text::HyphenationOptions::default().words_longer_than, "no operand sets it"); + let two = texts[0].para_at(1); + assert_eq!(two.justification.letter_spacing, [0.0, 0.0, 5.0]); + assert_eq!(two.justification.word_spacing, [70.0, 110.0, 140.0], "word spacing stays"); + assert!(!two.roman_hanging && !two.hyphenate); + // Without the limit flag, any number of hyphens in a row. + assert_eq!((two.hyphenation.after_first, two.hyphenation.before_last, two.hyphenation.hyphen_limit), (4, 5, 0)); + // The next text object keeps them. + assert_eq!(texts[1].para_at(0), two); +} + +/// A legacy attribute whose operands are missing, are not numbers, or are flags other than 0 and +/// 1 leaves the attribute as it was, and operands are read by their place. +#[test] +fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { + let set = "10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th\n2 Ta\n0 TA\n5 6 7 Ti"; + let bad = "/x 15 20 TC\n110 140 TW\n2 Tq\n1 2 2 3 4 Th\n1 1 (2) 3 4 Th\n/x Ta\n2 TA\n5 /x 7 Ti"; + let texts = legacy_texts(&point_type(&format!("{set}\n{bad}"), "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(p.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(p.roman_hanging && p.hyphenate); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 3, 4)); + assert_eq!(p.justify, vectorcraft_doc::Justify::Right); + assert_eq!((p.first_line_indent, p.left_indent, p.right_indent), (5.0, 6.0, 7.0)); + assert_eq!(texts[0].runs[0].style.kerning, Some(0.0), "kerning stays off"); + // A scale or leading pair with a bad operand leaves both as they were; one operand is the + // horizontal scale (or the leading) of the format before version 7. + let texts = legacy_texts(&point_type("50 80 Tz\n14 3 Tl\n/x 120 Tz\n/x 20 Tl", "Hi")); + let st = &texts[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale, st.leading), (50.0, 80.0, Some(14.0))); + assert_eq!(texts[0].para_at(0).space_before, 3.0); + let st = &legacy_texts(&point_type("50 80 Tz\n120 Tz", "Hi"))[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale), (120.0, 100.0)); + // A start point that isn't a number leaves the matrix. + let good = &legacy_texts(&point_type("", "Hi"))[0]; + let bad = &legacy_texts(&point_type("", "Hi").replace("10 50 0 Tp", "10 50 /x Tp"))[0]; + assert_eq!(bad.xf, good.xf); +} + +/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum +/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges +/// `text.setFormat` takes. +#[test] +fn legacy_type_spacing_and_hyphenation_are_kept_in_range() { + let texts = legacy_texts(&point_type("-500 0 900 TC\n0 2000 5000 TW\n1 1 0 40 99 Th", "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [-100.0, 0.0, 500.0]); + assert_eq!(p.justification.word_spacing, [0.0, 1000.0, 1000.0]); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (1, 15, 25)); + let texts = legacy_texts(&point_type("5 0 0 TC\n200 100 80 TW", "Hi")); + let j = &texts[0].para_at(0).justification; + let d = vectorcraft_doc::text::JustificationOptions::default(); + assert_eq!((j.letter_spacing, j.word_spacing), (d.letter_spacing, d.word_spacing)); +} + +/// A file's legacy type is read up to its allowance of characters, a single long run included. +#[test] +fn one_long_run_of_legacy_type_stops_at_the_allowance() { + // The reader's allowance, `MAX_CHARS`. + const ALLOWANCE: usize = 1 << 22; + let long = "a".repeat(ALLOWANCE + 10); + let texts = legacy_texts(&point_type("", &long)); + assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); +} diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 7543e51588..f83475638d 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -147,6 +147,17 @@ fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() { let r = import(src.as_bytes()).unwrap(); assert!(!r.preview, "read through the layers, not a fallback preview"); assert!(!r.warnings.iter().any(|w| w.contains("doesn't know") || w.contains("couldn't be read")), "{:?}", r.warnings); + // `Th` sets the paragraph's hyphenation: off, 2 letters before and after a hyphen, and the + // limit of 99 hyphens in a row kept to the 25 `text.setFormat` takes. + let mut texts = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + texts.push(t.para_at(0).clone()); + } + }); + let [p] = texts.as_slice() else { panic!("{texts:?}") }; + assert!(!p.hyphenate); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25)); } /// An Illustrator 3 file of paths alone, as image editors export their paths (storytold/photocraft#6036): diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 1f2f14bd81..98260d60a3 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -81,7 +81,8 @@ private editing data. VectorCraft: 14; #868: round trip with Illustrator 2018 loses layers and groups), guides and non-printing construction lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` - without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. + without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, with its paragraphs' letter + and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and hyphenation (`Th`). - Estimate: **~65%** for real exchange with Illustrator users (open: ~75%; save: PDF-compatible, or legacy version 7 with layers and groups; not yet tested by users who hand files back). Closing the open-side issues: 10–20 h with users' files. From c21ff5698eefa8c54899d2cfa96a9c6d222546e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 13:55:56 -0800 Subject: [PATCH 015/189] Tests: move the legacy type tests next to the text object tests The legacy type helpers and tests move from the end of crates/eps/src/import/ai/tests.rs to after text_objects_are_slots_named_after_their_story, and the helper stream7 is renamed type_stream7. --- crates/eps/src/import/ai/tests.rs | 214 +++++++++++++++--------------- 1 file changed, 107 insertions(+), 107 deletions(-) diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index c53209fbc8..92c9a46457 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1183,6 +1183,113 @@ fn text_objects_are_slots_named_after_their_story() { assert_eq!((a.len(), a[0].children().map(Vec::len), slot_of(a[1].name.as_deref())), (2, Some(1), Some(Some(7)))); } +/// A file in the legacy format (version 7) whose layer holds `art`, crop marks 0 0 200 100. +fn type_stream7(art: &str) -> String { + format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 3.0\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n", + layer(art) + ) +} + +/// The text objects of a legacy-format file whose layer holds `art`. +fn legacy_texts(art: &str) -> Vec { + let doc = match read(type_stream7(art).as_bytes()) { + Ok(r) => r.doc, + Err(e) => panic!("{e}"), + }; + art_texts(&doc) +} + +fn art_texts(doc: &Document) -> Vec { + art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() +} + +/// Point type at (10, 50): `attrs`, then the characters `text`. +fn point_type(attrs: &str, text: &str) -> String { + format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") +} + +/// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging +/// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its +/// first character, and they last into the next text object. +#[test] +fn legacy_type_keeps_its_spacing_hanging_punctuation_and_hyphenation() { + let two_paragraphs = + point_type("10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th", "One\\r").replace("TO\n", "0 0 5 TC\n0 Tq\n0 0 4 5 6 Th\n(Two) Tx\nTO\n"); + let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "Three"))); + assert_eq!(texts.len(), 2); + let one = texts[0].para_at(0); + assert_eq!(one.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(one.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(one.roman_hanging && one.hyphenate); + let h = &one.hyphenation; + assert_eq!((h.after_first, h.before_last, h.hyphen_limit), (2, 3, 4)); + assert_eq!(h.words_longer_than, vectorcraft_doc::text::HyphenationOptions::default().words_longer_than, "no operand sets it"); + let two = texts[0].para_at(1); + assert_eq!(two.justification.letter_spacing, [0.0, 0.0, 5.0]); + assert_eq!(two.justification.word_spacing, [70.0, 110.0, 140.0], "word spacing stays"); + assert!(!two.roman_hanging && !two.hyphenate); + // Without the limit flag, any number of hyphens in a row. + assert_eq!((two.hyphenation.after_first, two.hyphenation.before_last, two.hyphenation.hyphen_limit), (4, 5, 0)); + // The next text object keeps them. + assert_eq!(texts[1].para_at(0), two); +} + +/// A legacy attribute whose operands are missing, are not numbers, or are flags other than 0 and +/// 1 leaves the attribute as it was, and operands are read by their place. +#[test] +fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { + let set = "10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th\n2 Ta\n0 TA\n5 6 7 Ti"; + let bad = "/x 15 20 TC\n110 140 TW\n2 Tq\n1 2 2 3 4 Th\n1 1 (2) 3 4 Th\n/x Ta\n2 TA\n5 /x 7 Ti"; + let texts = legacy_texts(&point_type(&format!("{set}\n{bad}"), "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [10.0, 15.0, 20.0]); + assert_eq!(p.justification.word_spacing, [70.0, 110.0, 140.0]); + assert!(p.roman_hanging && p.hyphenate); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 3, 4)); + assert_eq!(p.justify, vectorcraft_doc::Justify::Right); + assert_eq!((p.first_line_indent, p.left_indent, p.right_indent), (5.0, 6.0, 7.0)); + assert_eq!(texts[0].runs[0].style.kerning, Some(0.0), "kerning stays off"); + // A scale or leading pair with a bad operand leaves both as they were; one operand is the + // horizontal scale (or the leading) of the format before version 7. + let texts = legacy_texts(&point_type("50 80 Tz\n14 3 Tl\n/x 120 Tz\n/x 20 Tl", "Hi")); + let st = &texts[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale, st.leading), (50.0, 80.0, Some(14.0))); + assert_eq!(texts[0].para_at(0).space_before, 3.0); + let st = &legacy_texts(&point_type("50 80 Tz\n120 Tz", "Hi"))[0].runs[0].style; + assert_eq!((st.h_scale, st.v_scale), (120.0, 100.0)); + // A start point that isn't a number leaves the matrix. + let good = &legacy_texts(&point_type("", "Hi"))[0]; + let bad = &legacy_texts(&point_type("", "Hi").replace("10 50 0 Tp", "10 50 /x Tp"))[0]; + assert_eq!(bad.xf, good.xf); +} + +/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum +/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges +/// `text.setFormat` takes. +#[test] +fn legacy_type_spacing_and_hyphenation_are_kept_in_range() { + let texts = legacy_texts(&point_type("-500 0 900 TC\n0 2000 5000 TW\n1 1 0 40 99 Th", "Hi")); + let p = texts[0].para_at(0); + assert_eq!(p.justification.letter_spacing, [-100.0, 0.0, 500.0]); + assert_eq!(p.justification.word_spacing, [0.0, 1000.0, 1000.0]); + assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (1, 15, 25)); + let texts = legacy_texts(&point_type("5 0 0 TC\n200 100 80 TW", "Hi")); + let j = &texts[0].para_at(0).justification; + let d = vectorcraft_doc::text::JustificationOptions::default(); + assert_eq!((j.letter_spacing, j.word_spacing), (d.letter_spacing, d.word_spacing)); +} + +/// A file's legacy type is read up to its allowance of characters, a single long run included. +#[test] +fn one_long_run_of_legacy_type_stops_at_the_allowance() { + // The reader's allowance, `MAX_CHARS`. + const ALLOWANCE: usize = 1 << 22; + let long = "a".repeat(ALLOWANCE + 10); + let texts = legacy_texts(&point_type("", &long)); + assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); +} + #[test] fn what_it_doesnt_read_is_an_error_where_it_shows() { let e = read(stream(&layer("1 2 frobnicate\n")).as_bytes()).unwrap_err(); @@ -3149,110 +3256,3 @@ fn an_objects_on_path_group_in_versioned_content_opens_once() { assert_eq!(kids[0].children().unwrap().len(), 5); assert!(kids[0].extras().objects_on_path.is_some()); } - -/// A file in the legacy format (version 7) whose layer holds `art`, crop marks 0 0 200 100. -fn stream7(art: &str) -> String { - format!( - "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 3.0\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n", - layer(art) - ) -} - -/// The text objects of a legacy-format file whose layer holds `art`. -fn legacy_texts(art: &str) -> Vec { - let doc = match read(stream7(art).as_bytes()) { - Ok(r) => r.doc, - Err(e) => panic!("{e}"), - }; - art_texts(&doc) -} - -fn art_texts(doc: &Document) -> Vec { - art(doc).iter().filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some((**t).clone()) } else { None }).collect() -} - -/// Point type at (10, 50): `attrs`, then the characters `text`. -fn point_type(attrs: &str, text: &str) -> String { - format!("0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n{attrs}\n({text}) Tx\nTO\n") -} - -/// `TC` and `TW` (§15.4.7) set the paragraph's letter and word spacing, `Tq` its hanging -/// punctuation and `Th` (§22) its hyphenation; each paragraph keeps the values in force at its -/// first character, and they last into the next text object. -#[test] -fn legacy_type_keeps_its_spacing_hanging_punctuation_and_hyphenation() { - let two_paragraphs = - point_type("10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th", "One\\r").replace("TO\n", "0 0 5 TC\n0 Tq\n0 0 4 5 6 Th\n(Two) Tx\nTO\n"); - let texts = legacy_texts(&format!("{two_paragraphs}{}", point_type("", "Three"))); - assert_eq!(texts.len(), 2); - let one = texts[0].para_at(0); - assert_eq!(one.justification.letter_spacing, [10.0, 15.0, 20.0]); - assert_eq!(one.justification.word_spacing, [70.0, 110.0, 140.0]); - assert!(one.roman_hanging && one.hyphenate); - let h = &one.hyphenation; - assert_eq!((h.after_first, h.before_last, h.hyphen_limit), (2, 3, 4)); - assert_eq!(h.words_longer_than, vectorcraft_doc::text::HyphenationOptions::default().words_longer_than, "no operand sets it"); - let two = texts[0].para_at(1); - assert_eq!(two.justification.letter_spacing, [0.0, 0.0, 5.0]); - assert_eq!(two.justification.word_spacing, [70.0, 110.0, 140.0], "word spacing stays"); - assert!(!two.roman_hanging && !two.hyphenate); - // Without the limit flag, any number of hyphens in a row. - assert_eq!((two.hyphenation.after_first, two.hyphenation.before_last, two.hyphenation.hyphen_limit), (4, 5, 0)); - // The next text object keeps them. - assert_eq!(texts[1].para_at(0), two); -} - -/// A legacy attribute whose operands are missing, are not numbers, or are flags other than 0 and -/// 1 leaves the attribute as it was, and operands are read by their place. -#[test] -fn legacy_type_attributes_with_bad_operands_stay_as_they_were() { - let set = "10 15 20 TC\n70 110 140 TW\n1 Tq\n1 1 2 3 4 Th\n2 Ta\n0 TA\n5 6 7 Ti"; - let bad = "/x 15 20 TC\n110 140 TW\n2 Tq\n1 2 2 3 4 Th\n1 1 (2) 3 4 Th\n/x Ta\n2 TA\n5 /x 7 Ti"; - let texts = legacy_texts(&point_type(&format!("{set}\n{bad}"), "Hi")); - let p = texts[0].para_at(0); - assert_eq!(p.justification.letter_spacing, [10.0, 15.0, 20.0]); - assert_eq!(p.justification.word_spacing, [70.0, 110.0, 140.0]); - assert!(p.roman_hanging && p.hyphenate); - assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 3, 4)); - assert_eq!(p.justify, vectorcraft_doc::Justify::Right); - assert_eq!((p.first_line_indent, p.left_indent, p.right_indent), (5.0, 6.0, 7.0)); - assert_eq!(texts[0].runs[0].style.kerning, Some(0.0), "kerning stays off"); - // A scale or leading pair with a bad operand leaves both as they were; one operand is the - // horizontal scale (or the leading) of the format before version 7. - let texts = legacy_texts(&point_type("50 80 Tz\n14 3 Tl\n/x 120 Tz\n/x 20 Tl", "Hi")); - let st = &texts[0].runs[0].style; - assert_eq!((st.h_scale, st.v_scale, st.leading), (50.0, 80.0, Some(14.0))); - assert_eq!(texts[0].para_at(0).space_before, 3.0); - let st = &legacy_texts(&point_type("50 80 Tz\n120 Tz", "Hi"))[0].runs[0].style; - assert_eq!((st.h_scale, st.v_scale), (120.0, 100.0)); - // A start point that isn't a number leaves the matrix. - let good = &legacy_texts(&point_type("", "Hi"))[0]; - let bad = &legacy_texts(&point_type("", "Hi").replace("10 50 0 Tp", "10 50 /x Tp"))[0]; - assert_eq!(bad.xf, good.xf); -} - -/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum -/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges -/// `text.setFormat` takes. -#[test] -fn legacy_type_spacing_and_hyphenation_are_kept_in_range() { - let texts = legacy_texts(&point_type("-500 0 900 TC\n0 2000 5000 TW\n1 1 0 40 99 Th", "Hi")); - let p = texts[0].para_at(0); - assert_eq!(p.justification.letter_spacing, [-100.0, 0.0, 500.0]); - assert_eq!(p.justification.word_spacing, [0.0, 1000.0, 1000.0]); - assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (1, 15, 25)); - let texts = legacy_texts(&point_type("5 0 0 TC\n200 100 80 TW", "Hi")); - let j = &texts[0].para_at(0).justification; - let d = vectorcraft_doc::text::JustificationOptions::default(); - assert_eq!((j.letter_spacing, j.word_spacing), (d.letter_spacing, d.word_spacing)); -} - -/// A file's legacy type is read up to its allowance of characters, a single long run included. -#[test] -fn one_long_run_of_legacy_type_stops_at_the_allowance() { - // The reader's allowance, `MAX_CHARS`. - const ALLOWANCE: usize = 1 << 22; - let long = "a".repeat(ALLOWANCE + 10); - let texts = legacy_texts(&point_type("", &long)); - assert_eq!(texts[0].plain_text().chars().count(), ALLOWANCE); -} From 0ccc6d9df55f0681acf97c9538ff2a6befcaea62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:03:21 +0700 Subject: [PATCH 016/189] .ai import: paths keep their notes and Show Center Squashed from #5129 onto main. --- crates/engine/tests/import_fuzz.rs | 11 ++- crates/eps/src/import/ai/lex.rs | 7 +- crates/eps/src/import/ai/read/art.rs | 5 + crates/eps/src/import/ai/read/directives.rs | 43 +++++++- crates/eps/src/import/ai/read/ops.rs | 7 ++ crates/eps/src/import/ai/read/types.rs | 11 ++- crates/eps/src/import/ai/tests.rs | 103 ++++++++++++++++++++ crates/eps/src/import/tests_illustrator.rs | 16 +++ docs/target-app-parity.md | 1 + 9 files changed, 198 insertions(+), 6 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index c54c8e1335..7ae7b1d634 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3117,7 +3117,7 @@ fn on_path_data( /// not included, so its program can't be run and its layers are read from it. const NAMED_PROLOG_AI: &str = "%!PS-Adobe-3.0\n%%BoundingBox: 0 0 200 100\n%%DocumentNeededResources: procset Adobe_packedarray 2.0 0\n%AI3_TemplateBox: 288 384 288 384\n%%EndComments\n\ %%BeginProlog\n%%IncludeResource: procset Adobe_packedarray 2.0 0\nAdobe_packedarray /initialize get exec\n%%EndProlog\n%%BeginSetup\n%AI5_Begin_NonPrinting\nNp\n%AI5_End_NonPrinting--\n%%EndSetup\n\ - %AI5_BeginLayer\n1 1 1 1 0 0 -1 191 63 255 Lb\n(A::B) Ln\n0 A\n0 R\n0 0 0 1 K\n0 i 1 J 1 j 0.8 w 4 M [2 1]0 d\n0 D\n10 10 m\n90 10 L\n90 90 L\n10 90 L\n10 10 L\nS\n\ + %AI5_BeginLayer\n1 1 1 1 0 0 -1 191 63 255 Lb\n(A::B) Ln\n0 A\n0 R\n0 0 0 1 K\n0 i 1 J 1 j 0.8 w 4 M [2 1]0 d\n0 D\n%AI3_Note:a (note)\n%AI5_NoteMore:more\n1 Ap\n10 10 m\n90 10 L\n90 90 L\n10 90 L\n10 10 L\nS\n%%Note:\n0 Ap\n\ u\n0.5 g\n20 20 m\n40 20 L\n40 40 L\nf\nU\n%AI5_BeginLayer\n0 1 1 1 0 0 3 0 0 0 Lb\n(Sub) Ln\n110 10 m\n190 90 L\nS\nLB\n%AI5_EndLayer--\nLB\n%AI5_EndLayer--\n\ %%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n"; @@ -3136,7 +3136,7 @@ proptest! { /// A `.ai` in PostScript form whose prolog is named, not included, damaged: read from its /// layers, or refused. #[test] - fn ps_form_ai_never_panics(cut in 0usize..1_200, edits in prop::collection::vec((0usize..1_200, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '%', 'u', 'U', 'L', 'b', 'B', 'i', 'A', 'K'])), 0..12)) { + fn ps_form_ai_never_panics(cut in 0usize..1_200, edits in prop::collection::vec((0usize..1_200, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', '[', ']', '%', 'u', 'U', 'L', 'b', 'B', 'i', 'A', 'K', 'p', ':', '\u{e9}'])), 0..12)) { let text = mutate_text(NAMED_PROLOG_AI, cut, &edits); survive("mutated PostScript-form .ai", || vectorcraft_engine::cmd::fileio::load("x.ai", text.as_bytes()).ok().map(|l| l.doc))?; } @@ -3211,6 +3211,13 @@ fn arb_ai_token() -> impl Strategy { "O", "R", "XR", + // A path's note and Show Center (version 7 §5.3.1, §12). + "Ap", + "1 Ap", + "\n%AI3_Note: a (note) \n", + "\n%AI3_Note:\n", + "\n%AI5_NoteMore:more\n", + "\n%%Note:old\n", "w", "J", "j", diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index 9b81e29a8d..c4a138cd81 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -42,6 +42,8 @@ pub(super) struct Token<'a> { const PREVIEW: (&[u8], &[u8]) = (b"%AI26_BeginPlacedObjectPreview", b"%AI26_EndPlacedObjectPreview"); /// A placed file's markers, which a hidden one has on `%_` lines. const PLACE: [&[u8]; 2] = [b"%AI5_BeginPlace", b"%AI5_EndPlace"]; +/// A path's note comments, also read on `%_` lines. +const NOTES: [&[u8]; 3] = [b"%AI3_Note:", b"%%Note:", b"%AI5_NoteMore:"]; /// A binary section skipped whole: (begin, end) markers. const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument"); @@ -144,8 +146,9 @@ impl<'a> Lexer<'a> { if start { return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: false }); } - // So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. - if prefixed && PLACE.iter().any(|m| line.starts_with(m)) { + // So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. And a + // hidden path's note. + if prefixed && PLACE.iter().chain(&NOTES).any(|m| line.starts_with(m)) { return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true }); } // A comment later in a line. diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 5e10d789f1..98412ff700 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -233,6 +233,11 @@ impl<'a> Reader<'a> { .into(); copy }); + // The note and Show Center are the path's, not its painted copy's. + node.edit_attrs(|a| { + a.note = gs.note.clone().unwrap_or_default(); + a.show_center = gs.show_center; + }); let unread_bounds = unread.then(|| node.visual_bounds()).flatten(); let unread_id = node.id; self.add(node, hidden)?; diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 1d5806a3cc..ce5bfa41dc 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,5 +1,5 @@ use super::art::{four, sane, two}; -use super::types::{FLIP, Kind, MAX_HEX, MAX_PATTERNS, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED}; +use super::types::{FLIP, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED}; use super::{Arc, Node, PatternDef, Reader, Rect, Tok, V, marker}; impl<'a> Reader<'a> { @@ -49,6 +49,9 @@ impl<'a> Reader<'a> { } return Ok(()); } + if self.note_comment(c) { + return Ok(()); + } let m = marker(line); // A pattern's definition (one inside another's isn't read). if m == "BeginPattern" && self.pattern.is_none() { @@ -157,6 +160,44 @@ impl<'a> Reader<'a> { Ok(()) } + /// `%AI3_Note:` (or `%%Note:`) sets the note of the paths that follow, an empty one clearing it, + /// and `%AI5_NoteMore:` adds a line to it. The text is kept as written, up to [`MAX_NOTE`] + /// characters. + fn note_comment(&mut self, c: &[u8]) -> bool { + let (text, more) = if let Some(t) = c.strip_prefix(b"AI3_Note:").or_else(|| c.strip_prefix(b"%Note:")) { + (t, false) + } else if let Some(t) = c.strip_prefix(b"AI5_NoteMore:") { + (t, true) + } else { + return false; + }; + // Only as much of the line as the note can keep is decoded; a UTF-8 character the cut + // splits is left out. + let mut head = text.get(..text.len().min(4 * MAX_NOTE)).unwrap_or(text); + if head.len() < text.len() + && let Err(e) = std::str::from_utf8(head) + && e.error_len().is_none() + { + head = head.get(..e.valid_up_to()).unwrap_or(head); + } + let text = super::obj::text(head); + match (&mut self.gs.note, more) { + (Some(note), true) => { + note.push('\n'); + note.push_str(&text); + } + // A continuation with no note to continue. + (None, true) => return true, + (note, false) => *note = Some(text), + } + if let Some(note) = self.gs.note.as_mut() + && let Some((at, _)) = note.char_indices().nth(MAX_NOTE) + { + note.truncate(at); + } + true + } + /// Skip to the comment with marker `end` (sections of the same kind nested in it count, and /// versioned content in an alternate). fn skip_to(&mut self, end: &str) -> Result<(), String> { diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index f48a8df82a..6e12e89b19 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -158,6 +158,13 @@ impl<'a> Reader<'a> { "O" => self.gs.overprint_fill = Self::nums(&vals).last() == Some(&1.0), "R" => self.gs.overprint_stroke = Self::nums(&vals).last() == Some(&1.0), "XR" => self.gs.rule = if Self::nums(&vals).last() == Some(&1.0) { FillRule::EvenOdd } else { FillRule::NonZero }, + // Show Center (§12): 1 shows the center point of the paths that follow, and 0 leaves + // them at their default, which hides it on an imported path. + "Ap" => match Self::nums(&vals).last().copied() { + Some(1.0) => self.gs.show_center = Some(true), + Some(0.0) => self.gs.show_center = None, + _ => {} + }, "w" => { if let Some(v) = Self::nums(&vals).last().filter(|v| v.is_finite() && **v >= 0.0) { self.gs.width = *v; diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 3857cbe625..784108fe9f 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -40,6 +40,9 @@ pub(crate) const FLIP: Affine = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); /// Most patterns read (others can't fill art). pub(super) const MAX_PATTERNS: usize = 4096; +/// Most characters of a path's note read (the version 7 specification allows 254, §5.3.1). +pub(super) const MAX_NOTE: usize = 1024; + #[derive(Clone, Debug)] pub(crate) struct GState { pub(crate) fill: Paint, @@ -59,6 +62,11 @@ pub(crate) struct GState { pub(crate) overprint_stroke: bool, pub(super) locked: bool, pub(super) hidden: bool, + /// The note (`%AI3_Note:`) the paths that follow get, until another replaces it (`None`: no + /// note comment yet; empty: none). + pub(super) note: Option, + /// Show Center (`1 Ap`) for the paths that follow (`None`: the path's default). + pub(super) show_center: Option, } impl Default for GState { @@ -82,6 +90,8 @@ impl Default for GState { overprint_stroke: false, locked: false, hidden: false, + note: None, + show_center: None, } } } @@ -222,7 +232,6 @@ pub(super) const LINKED_PREVIEWS: &str = pub(super) const IGNORED: &[&str] = &[ "Ae", "AE", - "Ap", "As", "Xd", "Xr", diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 92c9a46457..96d0ba9411 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -118,6 +118,109 @@ fn groups_names_hidden_and_locked() { assert!(!hidden.visible); } +/// A node's Attributes panel note (empty: none). +fn note(n: &Node) -> String { + n.extras().attrs.as_deref().map(|a| a.note.clone()).unwrap_or_default() +} + +/// The notes of the first layer's objects, in order. +fn notes(doc: &Document) -> Vec { + art(doc).iter().map(|n| note(n)).collect() +} + +/// A note comment names the paths after it until another one replaces it, and an empty one clears +/// it (§5.3.1: `%AI3_Note: `). +#[test] +fn a_note_comment_is_the_note_of_the_paths_after_it() { + let [a, b, c, d] = [0.0, 20.0, 40.0, 60.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let body = format!("%AI3_Note:hello\n{a}f\n{b}f\n%AI3_Note:\n{c}f\n%AI3_Note:world\n{d}f\n"); + assert_eq!(notes(&read_ok(&layer(&body)).doc), ["hello", "hello", "", "world"]); + // `%%Note:` sets it too. + assert_eq!(notes(&read_ok(&layer(&format!("%%Note:old style\n{a}f\n"))).doc), ["old style"]); + // A path without a note has no attributes. + assert!(art(&read_ok(&layer(&format!("{a}f\n"))).doc)[0].extras().attrs.is_none()); +} + +/// `%AI5_NoteMore:` adds a line to the note; the text is kept as written, and its bytes are read as +/// UTF-8, else Windows-1252. +#[test] +fn a_note_continues_on_more_lines_and_keeps_its_text() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let body = format!("%AI3_Note: two (words) caf@ \n%AI5_NoteMore:more\n{a}f\n"); + let data = stream(&layer(&body)).replace('@', "\u{1}").into_bytes(); + let data: Vec = data.into_iter().map(|b| if b == 1 { 0xE9 } else { b }).collect(); + assert_eq!(notes(&read(&data).unwrap().doc), [" two (words) café \nmore"]); + // A continuation of an empty note is its second line; one with no note before it is ignored. + assert_eq!(notes(&read_ok(&layer(&format!("%AI3_Note:\n%AI5_NoteMore:x\n{a}f\n"))).doc), ["\nx"]); + assert_eq!(notes(&read_ok(&layer(&format!("%AI5_NoteMore:x\n{a}f\n"))).doc), [""]); + // A note too long is cut at 1,024 characters, however many lines it has. + let long = format!("%AI3_Note:{}\n{}{a}f\n", "x".repeat(5000), "%AI5_NoteMore:yy\n".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc)[0].chars().count(), 1024); + let long = format!("%AI3_Note:x\n{}{a}f\n", "%AI5_NoteMore:yy\n".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc)[0].chars().count(), 1024); + // A long UTF-8 line stays UTF-8 where it is cut. + let long = format!("%AI3_Note:{}\n{a}f\n", "é".repeat(3000)); + assert_eq!(notes(&read_ok(&layer(&long)).doc), ["é".repeat(1024)]); + // A note on a `%_` line is read too. + assert_eq!(notes(&read_ok(&layer(&format!("%_%AI3_Note:hidden\n{a}f\n"))).doc), ["hidden"]); +} + +/// A note before a group or a compound path isn't theirs: their paths keep their own. +#[test] +fn a_note_before_a_group_or_compound_path_is_not_theirs() { + let [a, b] = [0.0, 20.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + for (open, close) in [("u", "U"), ("*u", "*U")] { + let body = format!("%AI3_Note:outer\n0 Ae\n{open}\n%AI3_Note:inner\n{a}f\n{b}f\n{close}\n"); + let doc = read_ok(&layer(&body)).doc; + let top = &art(&doc)[0]; + assert_eq!(note(top), "", "{open}"); + let kids: Vec = top.children().unwrap().iter().map(|k| note(k)).collect(); + assert_eq!(kids, ["inner", "inner"], "{open}"); + } +} + +/// A clipping path's note is its own, not that of the copy that paints its fill. +#[test] +fn a_clipping_paths_note_is_not_copied_to_its_painted_fill() { + let body = + format!("0 Ae\nq\n{RED}%AI3_Note:clip\n{}W\nf\n%AI3_Note:\n{}f\nQ\n", rect_path(5.0, 5.0, 25.0, 25.0), rect_path(0.0, 0.0, 30.0, 30.0)); + let doc = read_ok(&layer(&body)).doc; + fn walk(nodes: &[Arc], out: &mut Vec<(bool, String)>) { + for n in nodes { + out.push((matches!(n.kind, NodeKind::Path { clipping: true, .. }), note(n))); + walk(n.children().map(Vec::as_slice).unwrap_or_default(), out); + } + } + let mut all = Vec::new(); + walk(&art(&doc), &mut all); + let noted: Vec<_> = all.iter().filter(|(_, n)| n == "clip").collect(); + assert_eq!(noted, [&(true, "clip".to_string())], "{all:?}"); + assert!(all.len() >= 3, "the painted copy is there: {all:?}"); +} + +/// `1 Ap` shows the center point of the paths after it until `0 Ap` (§12, showCenter), which leaves +/// them at an imported path's default: hidden. +#[test] +fn ap_shows_the_center_of_the_paths_after_it() { + let [a, b, c] = [0.0, 20.0, 40.0].map(|x| rect_path(x, 0.0, x + 10.0, 10.0)); + let ellipse = "50 0 m\n50 5.5 45.5 10 40 10 c\n34.5 10 30 5.5 30 0 c\n30 -5.5 34.5 -10 40 -10 c\n45.5 -10 50 -5.5 50 0 c\n"; + let body = format!("1 Ap\n{a}f\n{b}f\n0 Ap\n{c}f\n{ellipse}f\n2 Ap\n{a}f\n"); + let doc = read_ok(&layer(&body)).doc; + let shown: Vec<_> = art(&doc).iter().map(|n| (n.extras().attrs.as_deref().and_then(|a| a.show_center), n.shows_center())).collect(); + assert_eq!(shown, [(Some(true), true), (Some(true), true), (None, false), (None, false), (None, false)]); +} + +/// What a skipped section sets doesn't reach the art after it. +#[test] +fn a_note_or_ap_in_a_skipped_section_does_not_reach_the_art_after_it() { + let a = rect_path(0.0, 0.0, 10.0, 10.0); + let body = format!("%AI3_BeginBrushPattern\n1 Ap\n%AI3_Note:brush\n{a}f\n%AI3_EndBrushPattern\n{}", layer(&format!("{a}f\n"))); + let doc = read_ok(&body).doc; + let n = &art(&doc)[0]; + assert_eq!(note(n), ""); + assert!(!n.shows_center()); +} + #[test] fn paths_colours_and_strokes() { let art_ = format!( diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index f83475638d..ebb8275b5c 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -257,6 +257,22 @@ fn a_version_7_palette_keeps_its_swatches_without_names() { assert_eq!(d.swatch("Gray K=0").unwrap().paint.color(), Some(Color::gray(0.0)), "1 g is white"); } +/// A version 8 file's paths keep their notes and Show Center. +#[test] +fn a_legacy_files_paths_keep_their_notes_and_show_center() { + let body = format!( + "%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Notes) Ln\n0 A\n%AI3_Note:first\n%AI5_NoteMore:second line\n1 Ap\n0 0 0 1 k\n{}\n\ + %AI3_Note:\n0 Ap\n{}\nLB\n%AI5_EndLayer--\n", + tri(10), + tri(40) + ); + let r = import(&ai(AI8, "", &body)).unwrap(); + let kids = r.document.layers[0].children().unwrap(); + let attrs: Vec<_> = kids.iter().map(|n| n.extras().attrs.as_deref().map(|a| (a.note.clone(), a.show_center))).collect(); + assert_eq!(attrs, [Some(("first\nsecond line".into(), Some(true))), None], "{:?}", r.warnings); + assert!(kids[0].shows_center() && !kids[1].shows_center()); +} + #[test] fn unbalanced_and_runaway_groups_are_read_safely() { // Ends without a beginning end nothing; groups left open hold the rest. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a340f6476a..4736272d74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,6 +1079,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + `.ai` and EPS editing-data import keeps each path's Attributes panel note (`%AI3_Note:`, `%%Note:`, more lines in `%AI5_NoteMore:`, up to 1,024 characters) and Show Center (`1 Ap`); a note or Show Center applies to every path after it until the next one, and a note before a group or compound path is not theirs (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_illustrator.rs`). A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part; CCITT Group 3 and planar files with extra channels are not read); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). From adb446049b131a6943f2cdca4b3338defc6b6b77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:54:14 -0800 Subject: [PATCH 017/189] Variables: Undo and Redo clear a highlight that names no variable Undo, Redo and a canceled undo group put back an earlier document but left the Variables panel highlight as it was. After renaming the highlighted variable and undoing, the highlight still named the new name: a variable defined later under that name showed highlighted without a click, and Delete removed it. Each of these paths now clears a highlight whose variable the restored document does not define, as Delete Variables and Load Variable Library already did. --- crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/cmd/variablecmds.rs | 4 +- crates/engine/src/cmd/variablecmds/library.rs | 4 +- crates/engine/src/doc_state.rs | 8 ++++ crates/engine/src/session/execute.rs | 1 + crates/engine/src/session/undo.rs | 2 + crates/engine/src/tests/variables.rs | 43 +++++++++++++++++++ 7 files changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 62a17bda3b..f252d09ff9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -498,6 +498,7 @@ fn undo(s: &mut Session, _: &Value) -> Result { super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); Ok(json!({ "undone": label })) } @@ -525,6 +526,7 @@ fn redo(s: &mut Session, _: &Value) -> Result { super::symboledit::follow_history(st, editing_symbol.as_ref()); leave_isolation_if_gone(st); super::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); Ok(json!({ "redone": label })) } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 9e589e8839..33799bc857 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -231,9 +231,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { let n = s.edit("Delete Variables", |d, _| Ok(d.variables.prune(&names)))?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; - if st.variables_highlight.as_ref().is_some_and(|h| st.doc.variables.variable(h).is_none()) { - st.variables_highlight = None; - } + st.drop_stale_variables_highlight(); st.revision += 1; Ok(json!({"deleted": n})) } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 937d4155e2..b410af042f 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -277,9 +277,7 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { })?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; - if st.variables_highlight.as_ref().is_some_and(|h| st.doc.variables.variable(h).is_none()) { - st.variables_highlight = None; - } + st.drop_stale_variables_highlight(); st.revision += 1; let skipped: Vec = lib.other.iter().map(|(name, t)| json!({"name": name, "trait": t})).collect(); let mut out = json!({ diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 30cf1e7e8d..dc1df88bed 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -352,6 +352,14 @@ impl DocState { self.revision += 1; } } + /// Clear the Variables panel highlight when the document defines no variable of that name + /// (deleted, or taken out by Undo or Redo), so a variable defined later under that name is + /// not highlighted without a click. + pub(crate) fn drop_stale_variables_highlight(&mut self) { + if self.variables_highlight.as_ref().is_some_and(|h| self.doc.variables.variable(h).is_none()) { + self.variables_highlight = None; + } + } /// Count the document as modified, as if never saved (a document restored by Data Recovery). pub fn mark_unsaved(&mut self) { self.saved_doc = Arc::new(Document::new(1.0, 1.0)); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index d3ffe41631..f4ebd87c42 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -219,6 +219,7 @@ impl Session { st.interaction = interaction; st.history = history; cmd::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); st.revision += 1; } if let Some(i) = active.and_then(|uid| self.docs.iter().position(|d| d.uid == uid)) { diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index 2f750dc13c..c5f3f1595e 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -102,6 +102,7 @@ impl Session { deselect_hidden(&self.menu, &st.doc, &mut st.selection); st.sync_new_art(); cmd::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); st.revision += 1; // The journal drops only the canceled groups' own entries and keeps the ones made in other documents meanwhile. journal.extend(g.journal); @@ -230,6 +231,7 @@ impl Session { st.doc = doc; st.selection = selection; cmd::globaledit::follow_history(st); + st.drop_stale_variables_highlight(); deselect_hidden(&menu, &st.doc, &mut st.selection); st.history.recost_last(&st.doc); st.revision += 1; diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index e1bfd3e2f2..5e0176f70c 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -893,6 +893,49 @@ fn highlight_follows_rename_and_clears_with_delete() { assert!(s.doc().unwrap().variables_highlight.is_none(), "a highlight of a deleted variable highlights nothing"); } +/// Undo of a rename takes the new name away, so the highlight that followed the rename goes +/// too: a variable defined later under that name is not highlighted, and Delete without names +/// does not delete it. +#[test] +fn undoing_a_rename_clears_the_highlight_of_the_new_name() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "A", "kind": "text"})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "A"})).unwrap(); + s.execute("variable.rename", &json!({"name": "A", "newName": "B"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none()); + s.execute("variable.define", &json!({"name": "B", "kind": "visibility"})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none(), "B was never clicked"); + assert!(s.execute("variable.delete", &json!({})).is_err(), "no variable highlighted"); + let vars = s.execute("variable.list", &json!({})).unwrap(); + assert_eq!(vars["variables"].as_array().unwrap().len(), 2); +} + +/// Undo of New Variable, Redo of Delete Variables and a canceled undo group each leave the +/// highlighted name undefined, and the highlight goes with it. +#[test] +fn undo_redo_and_a_canceled_group_clear_a_highlight_of_a_variable_they_remove() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "N", "kind": "text"})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "N"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none(), "undo of New Variable"); + + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("variable.delete", &json!({"names": ["N"]})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "N"})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().variables_highlight.is_none(), "redo of Delete Variables"); + + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + s.execute("variable.define", &json!({"name": "G", "kind": "text"})).unwrap(); + s.execute("variable.highlight", &json!({"variable": "G"})).unwrap(); + s.execute("edit.undoGroup.end", &json!({"cancel": true})).unwrap(); + assert!(s.doc().unwrap().doc.variables.variable("G").is_none(), "the cancel took G back"); + assert!(s.doc().unwrap().variables_highlight.is_none(), "a canceled undo group"); +} + /// A row that hides an object must be able to show it again, and hiding it on the artboard /// (as the Layers panel does) is what a capture records: a visibility variable reads and /// writes its object's own visibility, which therefore never makes the object off limits. From 1be658c88cd6cedd4e0bf685b976451a2e7cd0da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 06:58:18 -0800 Subject: [PATCH 018/189] Variables: Export Data Sets refuses more data sets or variables than Import Data Sets reads dataset.export checked only the 1 MiB size, so a document with more than 1000 data sets or 256 variables exported a CSV that dataset.import then refused. Export now refuses such a document with a message naming the limit, and the messages have rows in every complete-message catalog. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/cmd/variablecmds/csv.rs | 8 ++++++ crates/engine/src/tests/variables.rs | 27 +++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 2 ++ crates/ui-egui/src/i18n/cs.tsv | 2 ++ crates/ui-egui/src/i18n/de.tsv | 2 ++ crates/ui-egui/src/i18n/el.tsv | 2 ++ crates/ui-egui/src/i18n/es.tsv | 2 ++ crates/ui-egui/src/i18n/fi.tsv | 2 ++ crates/ui-egui/src/i18n/fr.tsv | 2 ++ crates/ui-egui/src/i18n/hu.tsv | 2 ++ crates/ui-egui/src/i18n/it.tsv | 2 ++ crates/ui-egui/src/i18n/ja.tsv | 2 ++ crates/ui-egui/src/i18n/ka.tsv | 2 ++ crates/ui-egui/src/i18n/ko.tsv | 2 ++ crates/ui-egui/src/i18n/pl.tsv | 2 ++ crates/ui-egui/src/i18n/pt-br.tsv | 2 ++ crates/ui-egui/src/i18n/ru.tsv | 2 ++ crates/ui-egui/src/i18n/sv.tsv | 2 ++ crates/ui-egui/src/i18n/tests.rs | 33 +++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 2 ++ crates/ui-egui/src/i18n/uk.tsv | 2 ++ crates/ui-egui/src/i18n/vi.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 2 ++ 25 files changed, 111 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 33799bc857..6416c8eb16 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -740,7 +740,7 @@ pub fn specs() -> Vec { "Export Data Sets…", ["Window", "Variables"], None, - "{path?} write every dataset as CSV (header: name, then variables); without path → {csv, datasets}", + "{path?} write every dataset as CSV (header: name, then variables); without path → {csv, datasets}. Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads", has_doc, dataset_export ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index bf60c95085..65388fb16d 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -341,12 +341,20 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { } /// Export every dataset as CSV (`name` then variables). With `path`, write the file; else return `{csv}`. +/// A document with more data sets or variables than [`dataset_import`] reads is refused. pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.export"; let st = s.doc()?; if st.doc.variables.variables.is_empty() { return Err(bad(C, "define a variable first")); } + if st.doc.variables.datasets.len() > MAX_CSV_ROWS { + return Err(bad(C, format!("more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS}"))); + } + // The name column comes first, so the import's column cap leaves room for this many variables. + if st.doc.variables.variables.len() > MAX_CSV_COLS { + return Err(bad(C, format!("more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS}"))); + } let csv = datasets_to_csv(&st.doc.variables); if csv.len() > MAX_CSV_BYTES { return Err(bad(C, format!("CSV would be larger than {MAX_CSV_BYTES} bytes"))); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 5e0176f70c..f57f8a5972 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1325,6 +1325,33 @@ fn datasets_csv_keeps_spaces_in_quoted_cells() { assert_eq!(value("C"), text_value(" quoted ")); } +/// Export refuses a document with more data sets or variables than `dataset.import` reads, so +/// every file it writes imports back: 1,000 data sets and 256 variables export and import, and +/// one more of either is refused. +#[test] +fn datasets_export_refuses_more_than_import_reads() { + let mut s = session(); + let header: Vec = (1..=256).map(|i| format!("V{i}")).collect(); + let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect(); + s.execute("dataset.import", &json!({"csv": format!("name,{}\n{rows}", header.join(","))})).unwrap(); + let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + + s.execute("dataset.new", &json!({"name": "Set 1001"})).unwrap(); + let err = s.execute("dataset.export", &json!({})).unwrap_err().to_string(); + assert!(err.contains("more than 1000 data sets"), "{err}"); + s.execute("dataset.delete", &json!({"names": ["Set 1001"]})).unwrap(); + s.execute("dataset.export", &json!({})).unwrap(); + + s.execute("variable.define", &json!({"name": "V257", "kind": "text"})).unwrap(); + let err = s.execute("dataset.export", &json!({})).unwrap_err().to_string(); + assert!(err.contains("more than 256 variables"), "{err}"); + let dir = Folder::new("vars-csv-caps"); + let out = dir.file("sets.csv"); + assert!(s.execute("dataset.export", &json!({"path": out})).is_err()); + assert!(!std::path::Path::new(&out).exists(), "no file is written"); +} + /// A header row with a tab and no comma outside quotes makes tabs the separator; a quoted cell /// may then hold tabs and commas. A header row with a comma outside quotes keeps commas, even /// when a cell holds a tab. A tab-separated header with an unclosed quote fails with the reason. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index cd6172d6a6..21b2ff53fa 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5597,6 +5597,8 @@ digits Malayalam Malaiàlam @msg unsupported native docking operation operació d’acoblament nadiua no compatible @msg unsupported: {0} no compatible: {0} @msg variables are locked les variables estan blocades +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} més de {MAX_CSV_ROWS} conjunts de dades: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} més de {MAX_CSV_COLS} variables: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft no cerca a les carpetes d’altres aplicacions ni del sistema: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft no cerca a la carpeta Shared o Public d’Usuaris: {path} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 34c7f4e035..b1742b59bf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4786,6 +4786,8 @@ imageTrace Outline Obrys @msg unknown workspace (one of {_1}) neznámý pracovní prostor (jeden z {_1}) @msg unsupported: {0} nepodporováno: {0} @msg variables are locked proměnné jsou zamčené +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} více než {MAX_CSV_ROWS} sad dat: Importovat sady dat načte nejvýše {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} více než {MAX_CSV_COLS} proměnných: Importovat sady dat načte nejvýše {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} proměnné, které nejsou textové, byly vynechány: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` a `options.{key}: {inner}` si odporují: zadejte volbu jen jednou @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files soubory verze {0} nelze komprimovat: komprimované soubory otevírá až verze {COMPRESSED_SINCE} a novější diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 101bbefac6..d850991b15 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4395,6 +4395,8 @@ theme Appearance Erscheinungsbild @msg unknown workspace (one of {_1}) unbekannter Arbeitsbereich (einer von {_1}) @msg unsupported: {0} nicht unterstützt: {0} @msg variables are locked die Variablen sind gesperrt +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mehr als {MAX_CSV_ROWS} Datensätze: „Datensätze importieren“ liest höchstens {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mehr als {MAX_CSV_COLS} Variablen: „Datensätze importieren“ liest höchstens {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} die Variablen, die kein Text sind, wurden ausgelassen: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` und `options.{key}: {inner}` widersprechen sich: Option nur einmal angeben @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files Dateien der Version {0} können nicht komprimiert werden: Erst Version {COMPRESSED_SINCE} und neuer öffnen komprimierte Dateien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e704faade5..ca944e5e9e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4428,6 +4428,8 @@ digits Malayalam Μαλαγιάλαμ @msg unknown workspace (one of {_1}) άγνωστος χώρος εργασίας (ένας από τους {_1}) @msg unsupported: {0} δεν υποστηρίζεται: {0} @msg variables are locked οι μεταβλητές είναι κλειδωμένες +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} περισσότερα από {MAX_CSV_ROWS} σύνολα δεδομένων: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} περισσότερες από {MAX_CSV_COLS} μεταβλητές: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} οι μεταβλητές που δεν είναι κειμένου παραλείφθηκαν: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once τα `{key}: {top}` και `options.{key}: {inner}` διαφέρουν: δώστε την επιλογή μόνο μία φορά @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files τα αρχεία έκδοσης {0} δεν μπορούν να συμπιεστούν: μόνο η έκδοση {COMPRESSED_SINCE} και νεότερες ανοίγουν συμπιεσμένα αρχεία diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4ebddbe9a9..bc2b918aa3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4480,6 +4480,8 @@ axis Both Ambos @msg unknown workspace (one of {_1}) espacio de trabajo desconocido (uno de estos: {_1}) @msg unsupported: {0} no compatible: {0} @msg variables are locked las variables están bloqueadas +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} más de {MAX_CSV_ROWS} conjuntos de datos: Importar conjuntos de datos lee como máximo {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} más de {MAX_CSV_COLS} variables: Importar conjuntos de datos lee como máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} se omitieron las variables que no son de texto: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` y `options.{key}: {inner}` no coinciden: indique la opción una sola vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files los archivos de la versión {0} no se pueden comprimir: solo la versión {COMPRESSED_SINCE} y posteriores abren archivos comprimidos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7042b21f22..3d75fc5d75 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4688,6 +4688,8 @@ imageTrace Outline Ääriviiva @msg unknown workspace (one of {_1}) tuntematon työtila (jokin seuraavista: {_1}) @msg unsupported: {0} ei tuettu: {0} @msg variables are locked muuttujat on lukittu +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} yli {MAX_CSV_ROWS} tietojoukkoa: Tuo tietojoukot lukee enintään {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} yli {MAX_CSV_COLS} muuttujaa: Tuo tietojoukot lukee enintään {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} muut kuin tekstimuuttujat jätettiin pois: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` ja `options.{key}: {inner}` ovat ristiriidassa: anna asetus vain kerran @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files version {0} tiedostoja ei voi pakata: pakattuja tiedostoja voi avata vain versiosta {COMPRESSED_SINCE} alkaen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 48eb621eb9..c5b62d657b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4470,6 +4470,8 @@ axis Both Les deux @msg unknown workspace (one of {_1}) espace de travail inconnu (valeurs possibles : {_1}) @msg unsupported: {0} non pris en charge : {0} @msg variables are locked les variables sont verrouillées +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ({kinds}) ont été ignorées @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` et `options.{key}: {inner}` ne concordent pas. Indiquez l’option une seule fois @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files les fichiers de version {0} ne peuvent pas être compressés : seules les versions {COMPRESSED_SINCE} et ultérieures ouvrent les fichiers compressés diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 81f9482631..bdcbfa9925 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5250,6 +5250,8 @@ imageTrace Outline Körvonal @msg unsupported native docking operation nem támogatott natív dokkolási művelet @msg unsupported: {0} nem támogatott: {0} @msg variables are locked a változók zárolva vannak +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} több mint {MAX_CSV_ROWS} adatkészlet: az Adatkészletek importálása legfeljebb {MAX_CSV_ROWS} adatkészletet olvas be +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} több mint {MAX_CSV_COLS} változó: az Adatkészletek importálása legfeljebb {MAX_CSV_COLS} változót olvas be @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} a VectorCraft nem keres más alkalmazások és a rendszer mappáiban: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} a VectorCraft nem keres a Users alatti Shared és Public mappában: {path} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6acfaf3c9a..b912c4e8f5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4521,6 +4521,8 @@ axis Both Entrambi @msg unknown workspace (one of {_1}) area di lavoro sconosciuta (una delle seguenti: {_1}) @msg unsupported: {0} non supportato: {0} @msg variables are locked le variabili sono bloccate +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} più di {MAX_CSV_ROWS} set di dati: Importa set di dati ne legge al massimo {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} più di {MAX_CSV_COLS} variabili: Importa set di dati ne legge al massimo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} le variabili che non sono di testo sono state escluse: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` non coincidono: indicare l'opzione una sola volta @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files i file della versione {0} non possono essere compressi: solo la versione {COMPRESSED_SINCE} e successive aprono file compressi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bf3cd6bd1..0380bf4977 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4076,6 +4076,8 @@ swatch Bright Violet ビビッドバイオレット @msg Make Guides: select paths ガイドを作成: パスを選択してください @msg Release Guides: no guides ガイドを解除: ガイドがありません @msg variables are locked 変数がロックされています +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} データセットが {MAX_CSV_ROWS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_ROWS} 個までです +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 変数が {MAX_CSV_COLS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_COLS} 個までです @msg variables that aren't text were left out: {kinds} テキスト以外の変数は除外されました: {kinds} @msg guides are locked ガイドがロックされています @msg handle must be in or out handle には in または out を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cf411b072c..296a233f83 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5417,6 +5417,8 @@ imageTrace Outline კონტური @msg too many changed shortcuts ზედმეტად ბევრი შეცვლილი მალსახმობი @msg too many library panels were opened in this session ამ სესიაში ზედმეტად ბევრი ბიბლიოთეკის პანელი გაიხსნა @msg variables are locked ცვლადები ჩაკეტილია +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS}-ზე მეტი მონაცემთა ნაკრები: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_ROWS}-ს +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS}-ზე მეტი ცვლადი: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_COLS}-ს @msg variables that aren't text were left out: {kinds} ცვლადები, რომლებიც ტექსტი არ არის, გამოტოვებულია: {kinds} @msg x and y must be finite x და y სასრული უნდა იყოს @msg {id} opens another app: only the person at the keyboard can run it {id} სხვა აპს ხსნის: მისი გაშვება მხოლოდ კლავიატურასთან მყოფ ადამიანს შეუძლია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81f6c600c6..59baeea9f1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4003,6 +4003,8 @@ theme Appearance 외관 @msg Make Guides: select paths 안내선 만들기: 패스를 선택하세요 @msg Release Guides: no guides 안내선 해제: 안내선이 없습니다 @msg variables are locked 변수가 잠겨 있습니다 +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 데이터 세트가 {MAX_CSV_ROWS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_ROWS}개를 읽습니다 +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 변수가 {MAX_CSV_COLS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_COLS}개를 읽습니다 @msg variables that aren't text were left out: {kinds} 텍스트가 아닌 변수는 제외되었습니다: {kinds} @msg guides are locked 안내선이 잠겨 있습니다 @msg handle must be in or out handle은 in 또는 out이어야 합니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 14825f83cf..8f292c0d9c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4612,6 +4612,8 @@ imageTrace Outline Kontur @msg unknown workspace (one of {_1}) nieznany obszar roboczy (jeden z: {_1}) @msg unsupported: {0} nieobsługiwane: {0} @msg variables are locked zmienne są zablokowane +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} więcej niż {MAX_CSV_ROWS} zestawów danych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} więcej niż {MAX_CSV_COLS} zmiennych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} pominięto zmienne, które nie są tekstowe: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` i `options.{key}: {inner}` są sprzeczne: podaj opcję tylko raz @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files plików w wersji {0} nie można kompresować: skompresowane pliki otwierają tylko wersje {COMPRESSED_SINCE} i nowsze diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 96a31c3e57..f4c43bdb8a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4052,6 +4052,8 @@ axis Both Ambos @msg unknown workspace (one of {_1}) espaço de trabalho desconhecido (um de {_1}) @msg unsupported: {0} não suportado: {0} @msg variables are locked as variáveis estão bloqueadas +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mais de {MAX_CSV_ROWS} conjuntos de dados: Importar Conjuntos de Dados lê no máximo {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mais de {MAX_CSV_COLS} variáveis: Importar Conjuntos de Dados lê no máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} as variáveis que não são de texto foram omitidas: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` não coincidem: informe a opção uma só vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files arquivos da versão {0} não podem ser compactados: somente a versão {COMPRESSED_SINCE} e posteriores abrem arquivos compactados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fdb51b80df..9798ffe64e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4516,6 +4516,8 @@ axis Both Оба @msg unknown workspace (one of {_1}) неизвестная рабочая среда (одна из: {_1}) @msg unsupported: {0} не поддерживается: {0} @msg variables are locked переменные заблокированы +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} больше {MAX_CSV_ROWS} наборов данных: «Импортировать наборы данных» читает не более {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} больше {MAX_CSV_COLS} переменных: «Импортировать наборы данных» читает не более {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} переменные, которые не являются текстовыми, пропущены: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` и `options.{key}: {inner}` противоречат друг другу: укажите параметр только один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файлы версии {0} не могут быть сжаты: только версия {COMPRESSED_SINCE} и новее открывают сжатые файлы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e2dddf022b..1b6429b628 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4379,6 +4379,8 @@ axis Both Båda @msg unknown workspace (one of {_1}) okänd arbetslayout (en av {_1}) @msg unsupported: {0} stöds inte: {0} @msg variables are locked variablerna är låsta +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} fler än {MAX_CSV_ROWS} datauppsättningar: Importera datauppsättningar läser högst {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} fler än {MAX_CSV_COLS} variabler: Importera datauppsättningar läser högst {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} variabler som inte är text utelämnades: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` och `options.{key}: {inner}` stämmer inte överens: ange alternativet bara en gång @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files filer i version {0} kan inte komprimeras: endast version {COMPRESSED_SINCE} och senare kan öppna komprimerade filer diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7e5ca938c6..b0da961f07 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1736,6 +1736,39 @@ fn saved_tracing_preset_errors_are_translated() { } } +/// Export Data Sets' refusals of more data sets or variables than Import Data Sets reads are +/// translated in every language that translates every message. +#[test] +fn dataset_export_limit_errors_are_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let rows: String = (1..=1000).map(|i| format!("Set {i},x\n")).collect(); + s.execute("dataset.import", &json!({"csv": format!("name,V1\n{rows}")})).unwrap(); + s.execute("dataset.new", &json!({"name": "Set 1001"})).unwrap(); + let mut errors = vec![]; + let e = s.execute("dataset.export", &json!({})).unwrap_err(); + let want = "more than 1000 data sets: Import Data Sets reads at most 1000"; + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + errors.push((e.to_string(), want)); + s.execute("dataset.delete", &json!({"names": ["Set 1001"]})).unwrap(); + for i in 2..=257 { + s.execute("variable.define", &json!({"name": format!("V{i}"), "kind": "text"})).unwrap(); + } + let e = s.execute("dataset.export", &json!({})).unwrap_err(); + let want = "more than 256 variables: Import Data Sets reads at most 256"; + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + errors.push((e.to_string(), want)); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, want) in &errors { + let shown = message(lang, e); + assert!(!shown.contains(want), "{code}: {shown}"); + } + } +} + /// The status bar's line for an EPS file whose PostScript stops on an error, opened partly or /// refused, and the refusal's dialog keep the error's name as PostScript spells it and its meaning, /// which each language shows as its catalog translates the meaning. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9ecf2ccf93..66e00165b4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5334,6 +5334,8 @@ theme Appearance Görünüm @msg the spine has no segments omurganın segmenti yok @msg too many library panels were opened in this session bu oturumda çok fazla kütüphane paneli açıldı @msg variables are locked değişkenler kilitli +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS} veri setinden fazla: Veri Kümelerini İçe Aktar en fazla {MAX_CSV_ROWS} tane okur +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS} değişkenden fazla: Veri Kümelerini İçe Aktar en fazla {MAX_CSV_COLS} tane okur @msg x and y must be finite x ve y sonlu olmalıdır @msg aiVersion 7 writes legacy .ai files; a .ait template is always PDF-compatible aiVersion 7 eski .ai dosyalarını yazar; bir .ait şablonu her zaman PDF uyumludur @msg Edit Original opens image and document files only; “{name}” is not one Özgünü Düzenle yalnızca görüntü ve belge dosyalarını açar; “{name}” bunlardan biri değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d348440a2c..ce992f29ab 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4505,6 +4505,8 @@ axis Both Обидві @msg unknown workspace (one of {_1}) невідоме робоче середовище (одна з: {_1}) @msg unsupported: {0} не підтримується: {0} @msg variables are locked змінні заблоковані +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} більше ніж {MAX_CSV_ROWS} наборів даних: «Імпортувати набори даних» читає не більше {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} більше ніж {MAX_CSV_COLS} змінних: «Імпортувати набори даних» читає не більше {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} змінні, що не є текстовими, пропущено: {kinds} @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` і `options.{key}: {inner}` суперечать одне одному: вкажіть параметр лише один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файли версії {0} не можуть бути стиснуті: тільки версія {COMPRESSED_SINCE} і новіші відкривають стислі файли diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 09652ede2b..9bb1c58a82 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4912,6 +4912,8 @@ theme Appearance Giao diện @msg unsupported native docking operation thao tác neo gốc không được hỗ trợ @msg unsupported: {0} không được hỗ trợ: {0} @msg variables are locked biến số bị khóa +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} hơn {MAX_CSV_ROWS} tập dữ liệu: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} hơn {MAX_CSV_COLS} biến số: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft không tìm kiếm trong thư mục của ứng dụng khác hoặc hệ thống: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft không tìm kiếm thư mục Shared hoặc Public trong Users: {path} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 841bd4528a..027d9c29d1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3471,6 +3471,8 @@ digits Malayalam 马拉雅拉姆数字 Lock Variables 锁定变量 Unlock Variables 解锁变量 @msg variables are locked 变量已锁定 +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 数据集超过 {MAX_CSV_ROWS} 个:“导入数据集”最多读取 {MAX_CSV_ROWS} 个 +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 变量超过 {MAX_CSV_COLS} 个:“导入数据集”最多读取 {MAX_CSV_COLS} 个 @msg variables that aren't text were left out: {kinds} 已省略非文本变量:{kinds} List Variables 列出变量 Bind Variable 绑定变量 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a515d59a74..ce25e4b0dc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4459,6 +4459,8 @@ digits Malayalam 馬來亞拉姆數字 Lock Variables 鎖定變數 Unlock Variables 解除鎖定變數 @msg variables are locked 變數已鎖定 +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 資料集超過 {MAX_CSV_ROWS} 個:「匯入資料集」最多讀取 {MAX_CSV_ROWS} 個 +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 變數超過 {MAX_CSV_COLS} 個:「匯入資料集」最多讀取 {MAX_CSV_COLS} 個 @msg variables that aren't text were left out: {kinds} 已略過非文字變數:{kinds} List Variables 列出變數 Bind Variable 綁定變數 From 660102064f449c19a16d2b67207900c85d328f06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:59:49 -0800 Subject: [PATCH 019/189] Variables: Import Data Sets reports why a cell was refused dataset.import replaced the reason for a refused cell with "value for `X` must match its variable kind", so a visibility value such as maybe and a graph value over 262,144 bytes gave the same message. The error now keeps the line and gives the reason, and both messages have a row in every complete-message catalog. --- crates/engine/src/cmd/variablecmds/csv.rs | 24 +++++++++---------- crates/engine/src/tests/variables.rs | 17 ++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 2 ++ crates/ui-egui/src/i18n/cs.tsv | 2 ++ crates/ui-egui/src/i18n/de.tsv | 2 ++ crates/ui-egui/src/i18n/el.tsv | 2 ++ crates/ui-egui/src/i18n/es.tsv | 2 ++ crates/ui-egui/src/i18n/fi.tsv | 2 ++ crates/ui-egui/src/i18n/fr.tsv | 2 ++ crates/ui-egui/src/i18n/hu.tsv | 2 ++ crates/ui-egui/src/i18n/it.tsv | 2 ++ crates/ui-egui/src/i18n/ja.tsv | 2 ++ crates/ui-egui/src/i18n/ka.tsv | 2 ++ crates/ui-egui/src/i18n/ko.tsv | 2 ++ crates/ui-egui/src/i18n/pl.tsv | 2 ++ crates/ui-egui/src/i18n/pt-br.tsv | 2 ++ crates/ui-egui/src/i18n/ru.tsv | 2 ++ crates/ui-egui/src/i18n/sv.tsv | 2 ++ crates/ui-egui/src/i18n/tests.rs | 28 +++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 2 ++ crates/ui-egui/src/i18n/uk.tsv | 2 ++ crates/ui-egui/src/i18n/vi.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 2 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 2 ++ docs/mcp.md | 3 ++- 25 files changed, 100 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 65388fb16d..ee61436fac 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -152,17 +152,19 @@ fn csv_escape(s: &str) -> String { if s.is_empty() || s.contains([',', '"', '\n', '\r']) || s != s.trim() { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() } } -/// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). -fn parse_visible_cell(s: &str, var: &str, cmd: &str) -> Result { +/// A visibility cell: true/false, 1/0, yes/no (ASCII, case-insensitive). An error names the +/// file line `line`. +fn parse_visible_cell(s: &str, var: &str, line: usize, cmd: &str) -> Result { match s.trim().to_ascii_lowercase().as_str() { "true" | "1" | "yes" => Ok(true), "false" | "0" | "no" => Ok(false), - _ => Err(bad(cmd, format!("value for `{var}` must be true or false"))), + _ => Err(bad(cmd, format!("line {line}: value for `{var}` must be true or false"))), } } -/// The value of a cell. A quoted empty text cell is an empty text value; any other empty cell is no value. -fn cell_to_value(kind: VariableKind, cell: &str, quoted: bool, var: &str, cmd: &str) -> Result> { +/// The value of a cell on file line `line`. A quoted empty text cell is an empty text value; any +/// other empty cell is no value. An error names the line and the reason. +fn cell_to_value(kind: VariableKind, cell: &str, quoted: bool, var: &str, line: usize, cmd: &str) -> Result> { // A text cell is not trimmed here (the parser trims unquoted cells); image, graph and // visibility cells are trimmed. let t = if kind == VariableKind::Text { cell } else { cell.trim() }; @@ -173,8 +175,8 @@ fn cell_to_value(kind: VariableKind, cell: &str, quoted: bool, var: &str, cmd: & VariableKind::Text => DataValue::Text(t.to_string()), VariableKind::Image => DataValue::Image(t.to_string()), VariableKind::Graph if t.len() <= MAX_GRAPH_CSV => DataValue::Graph(t.to_string()), - VariableKind::Graph => return Err(bad(cmd, format!("value for `{var}` is longer than {MAX_GRAPH_CSV} bytes"))), - VariableKind::Visibility => DataValue::Visible(parse_visible_cell(t, var, cmd)?), + VariableKind::Graph => return Err(bad(cmd, format!("line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes"))), + VariableKind::Visibility => DataValue::Visible(parse_visible_cell(t, var, line, cmd)?), })) } @@ -310,12 +312,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { for &(col, ref var, kind) in &columns { let cell = row.get(col).map(String::as_str).unwrap_or(""); let was_quoted = quoted.get(col).copied().unwrap_or(false); - match cell_to_value(kind, cell, was_quoted, var, C) { - Ok(Some(v)) => { - values.insert(var.clone(), v); - } - Ok(None) => {} - Err(_) => return Err(bad(C, format!("line {line}: value for `{var}` must match its variable kind"))), + if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? { + values.insert(var.clone(), v); } } parsed.push(DataSet { name, values }); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index f57f8a5972..7650df6a2e 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1416,6 +1416,23 @@ fn datasets_csv_row_errors_name_the_file_line() { assert!(long.contains("line 3:") && long.contains("longer than 255"), "{long}"); } +/// A refused cell's error gives its line and why the value was refused: a visibility value that +/// isn't true or false, or a graph value longer than the graph data limit. +#[test] +fn datasets_csv_cell_errors_say_why() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); + let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); + let maybe = error(&mut s, "name,Show\nX,maybe"); + let want = "line 2: value for `Show` must be true or false"; + assert!(matches!(&maybe, EngineError::BadParams { msg, .. } if msg == want), "{maybe}"); + let long = error(&mut s, &format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000))); + let want = "line 2: value for `Sales` is longer than 262144 bytes"; + assert!(matches!(&long, EngineError::BadParams { msg, .. } if msg == want), "{long}"); + assert!(s.doc().unwrap().doc.variables.datasets.is_empty()); +} + /// A header cell that names no variable defines one, unbound, in the import's undo step: `#` /// defines a visibility variable, `@` defines an image variable, and a cell without a prefix /// defines a text variable. Importing the file again finds them; a prefix of the other kind, a diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 21b2ff53fa..6564f158d2 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5086,6 +5086,8 @@ digits Malayalam Malaiàlam @msg lang must be one of {_1} lang ha de ser un de {_1} @msg larger than 256 MB més gran de 256 MB @msg layers can't be wrap objects les capes no poden ser objectes d’embolcall +@msg line {line}: value for `{var}` must be true or false línia {line}: el valor de `{var}` ha de ser true o false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes línia {line}: el valor de `{var}` ocupa més de {MAX_GRAPH_CSV} bytes @msg library panel `{given}` isn't missing its library al panell de biblioteca `{given}` no li falta la biblioteca @msg library panel `{given}` isn't open el panell de biblioteca `{given}` no està obert @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les imatges enllaçades mostren la previsualització de baixa resolució desada al fitxer fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b1742b59bf..eb9709c6f5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4472,6 +4472,8 @@ imageTrace Outline Obrys @msg join needs open paths spojení vyžaduje otevřené cesty @msg lang must be one of {_1} lang musí být jedno z {_1} @msg layers can't be wrap objects vrstvy nemohou být objekty obtékání +@msg line {line}: value for `{var}` must be true or false řádek {line}: hodnota pro `{var}` musí být true nebo false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes řádek {line}: hodnota pro `{var}` je delší než {MAX_GRAPH_CSV} bajtů @msg missing `folder` chybí `folder` @msg missing `id` (see plugin.list) chybí `id` (viz plugin.list) @msg missing `name` chybí `name` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d850991b15..789baa3dd3 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4079,6 +4079,8 @@ theme Appearance Erscheinungsbild @msg join needs open paths zum Zusammenfügen sind offene Pfade nötig @msg lang must be one of {_1} lang muss einer der folgenden Werte sein: {_1} @msg layers can't be wrap objects Ebenen können keine Umflussobjekte sein +@msg line {line}: value for `{var}` must be true or false Zeile {line}: der Wert für `{var}` muss true oder false sein +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes Zeile {line}: der Wert für `{var}` ist länger als {MAX_GRAPH_CSV} Byte @msg missing `folder` `folder` fehlt @msg missing `id` (see plugin.list) `id` fehlt (siehe plugin.list) @msg missing `name` `name` fehlt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ca944e5e9e..521e8761ac 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4119,6 +4119,8 @@ digits Malayalam Μαλαγιάλαμ @msg join needs open paths η ένωση απαιτεί ανοιχτές διαδρομές @msg lang must be one of {_1} η γλώσσα πρέπει να είναι μία από τις {_1} @msg layers can't be wrap objects τα επίπεδα δεν μπορούν να είναι αντικείμενα αναδίπλωσης +@msg line {line}: value for `{var}` must be true or false γραμμή {line}: η τιμή για το `{var}` πρέπει να είναι true ή false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes γραμμή {line}: η τιμή για το `{var}` είναι μεγαλύτερη από {MAX_GRAPH_CSV} byte @msg missing `folder` λείπει το `folder` @msg missing `id` (see plugin.list) λείπει το `id` (δείτε plugin.list) @msg missing `name` λείπει το `name` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index bc2b918aa3..a262f90b6f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4165,6 +4165,8 @@ axis Both Ambos @msg join needs open paths unir necesita trazados abiertos @msg lang must be one of {_1} lang debe ser uno de estos: {_1} @msg layers can't be wrap objects las capas no pueden ser objetos para ceñir +@msg line {line}: value for `{var}` must be true or false línea {line}: el valor de `{var}` debe ser true o false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes línea {line}: el valor de `{var}` ocupa más de {MAX_GRAPH_CSV} bytes @msg missing `folder` falta `folder` @msg missing `id` (see plugin.list) falta `id` (consulta plugin.list) @msg missing `name` falta `name` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3d75fc5d75..764b84f2db 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4380,6 +4380,8 @@ imageTrace Outline Ääriviiva @msg join needs open paths liittäminen vaatii avoimia polkuja @msg lang must be one of {_1} lang-arvon on oltava jokin seuraavista: {_1} @msg layers can't be wrap objects tasot eivät voi olla rivitysobjekteja +@msg line {line}: value for `{var}` must be true or false rivi {line}: muuttujan `{var}` arvon on oltava true tai false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes rivi {line}: muuttujan `{var}` arvo on pidempi kuin {MAX_GRAPH_CSV} tavua @msg missing `folder` `folder` puuttuu @msg missing `id` (see plugin.list) `id` puuttuu (ks. plugin.list) @msg missing `name` `name` puuttuu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c5b62d657b..c9625a8730 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4155,6 +4155,8 @@ axis Both Les deux @msg join needs open paths la jonction nécessite des tracés ouverts @msg lang must be one of {_1} lang doit valoir l’une de ces valeurs : {_1} @msg layers can't be wrap objects les calques ne peuvent pas être des objets d’habillage +@msg line {line}: value for `{var}` must be true or false ligne {line} : la valeur de `{var}` doit valoir true ou false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes ligne {line} : la valeur de `{var}` dépasse {MAX_GRAPH_CSV} octets @msg missing `folder` `folder` manquant @msg missing `id` (see plugin.list) `id` manquant (voir plugin.list) @msg missing `name` `name` manquant diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index bdcbfa9925..fc7937377a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4810,6 +4810,8 @@ imageTrace Outline Körvonal @msg lang must be one of {_1} a lang értéke ezek egyike lehet: {_1} @msg larger than 256 MB nagyobb 256 MB-nál @msg layers can't be wrap objects réteg nem lehet körbefuttató objektum +@msg line {line}: value for `{var}` must be true or false {line}. sor: a(z) `{var}` értéke csak true vagy false lehet +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes {line}. sor: a(z) `{var}` értéke hosszabb {MAX_GRAPH_CSV} bájtnál @msg Live Paint Merge: select a Live Paint group and the paths to add Élő festés egyesítése: jelölj ki egy élőfestés-csoportot és a hozzáadandó útvonalakat @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first Az élő festés útvonalakat és összetett útvonalakat fogad: előbb alakítsd útvonallá a szöveget, a képeket és a többi objektumot @msg Live Paint: select paths or compound paths Élő festés: jelölj ki útvonalakat vagy összetett útvonalakat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b912c4e8f5..0cc2f2d912 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4206,6 +4206,8 @@ axis Both Entrambi @msg join needs open paths per unire servono tracciati aperti @msg lang must be one of {_1} lang deve essere uno dei seguenti: {_1} @msg layers can't be wrap objects i livelli non possono essere oggetti di avvolgimento +@msg line {line}: value for `{var}` must be true or false riga {line}: il valore di `{var}` deve essere true o false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes riga {line}: il valore di `{var}` supera i {MAX_GRAPH_CSV} byte @msg missing `folder` manca `folder` @msg missing `id` (see plugin.list) manca `id` (vedi plugin.list) @msg missing `name` manca `name` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0380bf4977..eb24f7595c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4285,6 +4285,8 @@ swatch Bright Violet ビビッドバイオレット @msg node {_1} is not text ノード {_1} はテキストではありません @msg Text Wrap: select a wrap object テキストの回り込み: 回り込みオブジェクトを選択してください @msg layers can't be wrap objects レイヤーは回り込みオブジェクトにできません +@msg line {line}: value for `{var}` must be true or false {line} 行目: `{var}` の値には true または false を指定してください +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes {line} 行目: `{var}` の値が {MAX_GRAPH_CSV} バイトを超えています @msg no threaded text selected スレッドテキストが選択されていません @msg Create Outlines: select text objects アウトラインを作成: テキストオブジェクトを選択してください @msg paste unavailable 貼り付けを使用できません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 296a233f83..883e00dcac 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3938,6 +3938,8 @@ font-technology Variable ცვლადი @msg join needs open paths შეერთებას ღია ტრაექტორიები სჭირდება @msg lang must be one of {_1} lang უნდა იყოს ერთ-ერთი: {_1} @msg layers can't be wrap objects შრეები შემოსავლელი ობიექტები ვერ იქნება +@msg line {line}: value for `{var}` must be true or false სტრიქონი {line}: `{var}`-ის მნიშვნელობა უნდა იყოს true ან false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes სტრიქონი {line}: `{var}`-ის მნიშვნელობა {MAX_GRAPH_CSV} ბაიტზე გრძელია @msg missing `folder` აკლია `folder` @msg missing `id` (see plugin.list) აკლია `id` (იხ. plugin.list) @msg missing `name` აკლია `name` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 59baeea9f1..0164762a5e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4212,6 +4212,8 @@ theme Appearance 외관 @msg node {_1} is not text 노드 {_1}은(는) 텍스트가 아닙니다 @msg Text Wrap: select a wrap object 텍스트 감싸기: 감싸기 개체를 선택하세요 @msg layers can't be wrap objects 레이어는 감싸기 개체가 될 수 없습니다 +@msg line {line}: value for `{var}` must be true or false {line}행: `{var}`의 값은 true 또는 false여야 합니다 +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes {line}행: `{var}`의 값이 {MAX_GRAPH_CSV}바이트보다 깁니다 @msg no threaded text selected 선택한 연결 텍스트가 없습니다 @msg Create Outlines: select text objects 윤곽선 만들기: 텍스트 개체를 선택하세요 @msg paste unavailable 붙여넣을 수 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8f292c0d9c..5d57e77cf8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4295,6 +4295,8 @@ imageTrace Outline Kontur @msg join needs open paths łączenie wymaga otwartych ścieżek @msg lang must be one of {_1} lang musi mieć jedną z wartości: {_1} @msg layers can't be wrap objects warstwy nie mogą być obiektami oblewanymi +@msg line {line}: value for `{var}` must be true or false wiersz {line}: wartość `{var}` musi być true lub false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes wiersz {line}: wartość `{var}` jest dłuższa niż {MAX_GRAPH_CSV} bajtów @msg missing `folder` brak `folder` @msg missing `id` (see plugin.list) brak `id` (patrz plugin.list) @msg missing `name` brak `name` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f4c43bdb8a..c725ba6c6c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3739,6 +3739,8 @@ axis Both Ambos @msg join needs open paths unir exige traçados abertos @msg lang must be one of {_1} lang deve ser um de {_1} @msg layers can't be wrap objects camadas não podem ser objetos de quebra +@msg line {line}: value for `{var}` must be true or false linha {line}: o valor de `{var}` deve ser true ou false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes linha {line}: o valor de `{var}` tem mais de {MAX_GRAPH_CSV} bytes @msg missing `folder` falta `folder` @msg missing `id` (see plugin.list) falta `id` (veja plugin.list) @msg missing `name` falta `name` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9798ffe64e..f28fa3fca2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4201,6 +4201,8 @@ axis Both Оба @msg join needs open paths соединение требует открытых контуров @msg lang must be one of {_1} lang должен быть одним из: {_1} @msg layers can't be wrap objects слои не могут быть объектами обтекания +@msg line {line}: value for `{var}` must be true or false строка {line}: значение `{var}` должно быть true или false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes строка {line}: значение `{var}` длиннее {MAX_GRAPH_CSV} байт @msg missing `folder` отсутствует `folder` @msg missing `id` (see plugin.list) отсутствует `id` (см. plugin.list) @msg missing `name` отсутствует `name` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1b6429b628..6f30ec2e0c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4070,6 +4070,8 @@ axis Both Båda @msg join needs open paths foga samman kräver öppna banor @msg lang must be one of {_1} lang måste vara något av {_1} @msg layers can't be wrap objects lager kan inte vara radbrytningsobjekt +@msg line {line}: value for `{var}` must be true or false rad {line}: värdet för `{var}` måste vara true eller false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes rad {line}: värdet för `{var}` är längre än {MAX_GRAPH_CSV} byte @msg missing `folder` `folder` saknas @msg missing `id` (see plugin.list) `id` saknas (se plugin.list) @msg missing `name` `name` saknas diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b0da961f07..6bbfb107b2 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1796,6 +1796,34 @@ fn postscript_errors_keep_their_name_and_meaning() { } } +/// Import Data Sets' errors for a refused cell are translated in every language that translates +/// every message, with the line and the variable kept. +#[test] +fn dataset_import_cell_errors_are_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); + let mut errors = vec![]; + for (csv, want) in [ + ("name,Show\nX,maybe".to_string(), "line 2: value for `Show` must be true or false"), + (format!("name,Sales\nX,\"{}\"", "1,".repeat(140_000)), "line 2: value for `Sales` is longer than 262144 bytes"), + ] { + let e = s.execute("dataset.import", &json!({"csv": csv})).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + errors.push((e.to_string(), want)); + } + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, want) in &errors { + let shown = message(lang, e); + assert!(!shown.contains(want) && shown.contains('2') && shown.contains('`'), "{code}: {shown}"); + } + } +} + /// The errors of the parameter checks that many commands share (a number given as text, a missing /// number or index, a fraction for a whole number, `ids` that aren't a list of object ids, an /// object id that is negative or names no object, a date that isn't Unix seconds) fill their diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 66e00165b4..8f6e7c4911 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3932,6 +3932,8 @@ axis Both Her İkisi @msg join needs open paths katılmak için açık yollara ihtiyaç var @msg lang must be one of {_1} dil {_1}'den biri olmalıdır @msg layers can't be wrap objects katmanlar sarma nesneleri olamaz +@msg line {line}: value for `{var}` must be true or false satır {line}: `{var}` değeri true veya false olmalıdır +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes satır {line}: `{var}` değeri {MAX_GRAPH_CSV} bayttan uzun @msg missing `folder` 'klasör' eksik @msg missing `id` (see plugin.list) `kimlik` eksik (bkz. eklenti.liste) @msg missing `name` "isim" eksik diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ce992f29ab..86a10d0d46 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4190,6 +4190,8 @@ axis Both Обидві @msg join needs open paths з’єднання вимагає відкритих контурів @msg lang must be one of {_1} lang має бути одним з: {_1} @msg layers can't be wrap objects шари не можуть бути об’єктами обтікання +@msg line {line}: value for `{var}` must be true or false рядок {line}: значення `{var}` має бути true або false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes рядок {line}: значення `{var}` довше за {MAX_GRAPH_CSV} байтів @msg missing `folder` відсутня `folder` @msg missing `id` (see plugin.list) відсутня `id` (див. plugin.list) @msg missing `name` відсутня `name` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9bb1c58a82..deb4955613 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4460,6 +4460,8 @@ theme Appearance Giao diện @msg lang must be one of {_1} lang phải là một trong {_1} @msg larger than 256 MB lớn hơn 256 MB @msg layers can't be wrap objects lớp không thể là đối tượng bọc +@msg line {line}: value for `{var}` must be true or false dòng {line}: giá trị của `{var}` phải là true hoặc false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes dòng {line}: giá trị của `{var}` dài hơn {MAX_GRAPH_CSV} byte @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel ảnh liên kết hiển thị bản xem trước độ phân giải thấp đã lưu trong tệp cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết @msg Live Paint Merge: select a Live Paint group and the paths to add Hợp nhất tô trực tiếp: chọn nhóm tô trực tiếp và các đường dẫn để thêm @msg Live Paint takes paths and compound paths: convert type, images and other objects to paths first Tô trực tiếp nhận đường dẫn và đường dẫn phức: hãy chuyển văn bản, hình ảnh và các đối tượng khác thành đường dẫn trước diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 027d9c29d1..305c4c5995 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4010,6 +4010,8 @@ imageTrace Outline 轮廓 @msg node {_1} is not text 节点 {_1} 不是文字 @msg Text Wrap: select a wrap object 文本绕排:请选择一个绕排对象 @msg layers can't be wrap objects 图层不能作为绕排对象 +@msg line {line}: value for `{var}` must be true or false 第 {line} 行:`{var}` 的值必须是 true 或 false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes 第 {line} 行:`{var}` 的值超过 {MAX_GRAPH_CSV} 字节 @msg no threaded text selected 未选择串接文本 @msg Create Outlines: select text objects 创建轮廓:请选择文本对象 @msg paste unavailable 无法粘贴 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ce25e4b0dc..3ba21bee0b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1931,6 +1931,8 @@ file-filter Templates 範本 @msg node {_1} is not text 節點 {_1} 不是文字 @msg Text Wrap: select a wrap object 文字繞圖:請選取繞圖物件 @msg layers can't be wrap objects 圖層不能作為繞圖物件 +@msg line {line}: value for `{var}` must be true or false 第 {line} 行:`{var}` 的值必須是 true 或 false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes 第 {line} 行:`{var}` 的值超過 {MAX_GRAPH_CSV} 位元組 @msg no threaded text selected 未選取串連文字 @msg Create Outlines: select text objects 建立外框:請選取文字物件 @msg paste unavailable 無法貼上 diff --git a/docs/mcp.md b/docs/mcp.md index 50f73e7b70..5a080ea972 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1644,7 +1644,8 @@ already walks Image Trace. Short agent entry points: `dataset.export {path?}` (CSV: `name`, then one column per variable). `dataset.import` also reads tab-separated files, and files whose first header cell isn't `name`: every header cell is then a variable, and the rows take the first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file - line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the + line the row starts on, and an error about a value says why it was refused: a visibility value other than true, + false, 1, 0, yes or no, or a graph value longer than 262,144 bytes. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph From 386bfc881e50ae696c48091f141d5535320770db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 11:51:18 -0800 Subject: [PATCH 020/189] Docs: move the import value error note next to the data set warning --- docs/mcp.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 5a080ea972..aa997a323d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1644,8 +1644,7 @@ already walks Image Trace. Short agent entry points: `dataset.export {path?}` (CSV: `name`, then one column per variable). `dataset.import` also reads tab-separated files, and files whose first header cell isn't `name`: every header cell is then a variable, and the rows take the first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file - line the row starts on, and an error about a value says why it was refused: a visibility value other than true, - false, 1, 0, yes or no, or a graph value longer than 262,144 bytes. A header cell that names no variable defines one, unbound, in the same undo step as the + line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph @@ -1776,6 +1775,9 @@ new variables without binding them, `dataset.select`, `dataset.next` and `datase has a value for". A data set with a value for a bound variable gives no warning even when every object bound to it is locked; `skipped` counts those objects. +A `dataset.import` error about a value says why it was refused: a visibility value other than true, false, 1, 0, yes +or no, or a graph value longer than 262,144 bytes. + `dataset.update {all?}` writes what the bound objects hold now into the active data set, for each variable that the data set holds. A variable whose objects report no value, because they are locked, inside a locked layer or group, or deleted, keeps the data set's value. With `all: true` it also adds every other variable that the From 06221ce545ff1ab73697c0a2d1c938286284b993 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 07:22:15 -0800 Subject: [PATCH 021/189] Variables: a CSV header that names one variable twice is refused dataset.import read two header cells that named one variable (City and City, or Shown and #Shown) into the same column, so each row kept only the last non-blank cell and the other value was dropped without a word. The import is now refused with the two column numbers, and the message has a row in every complete-message catalog. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/cmd/variablecmds/csv.rs | 8 ++++++-- crates/engine/src/tests/variables.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 3 ++- 26 files changed, 71 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 6416c8eb16..03636d11f0 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -731,7 +731,7 @@ pub fn specs() -> Vec { "Import Data Sets…", ["Window", "Variables"], None, - "{path? | data? | dataBase64? | csv?} load datasets from CSV, comma- or tab-separated (header: name, then variable names; one row per dataset; without the name column every header is a variable and the rows take the first free names Data Set 1, 2…). A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so is a header that would define a variable while the variables are locked. Rows whose name already exists are replaced → {imported, updated, names, defined}", + "{path? | data? | dataBase64? | csv?} load datasets from CSV, comma- or tab-separated (header: name, then variable names; one row per dataset; without the name column every header is a variable and the rows take the first free names Data Set 1, 2…). A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. Rows whose name already exists are replaced → {imported, updated, names, defined}", has_doc, dataset_import ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index ee61436fac..8f23772a3f 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -252,8 +252,8 @@ fn header_variable( /// names; the other headers name variables, as [`header_variable`] reads them, and the /// variables the document doesn't define yet are defined, unbound. Without the `name` column, /// every header names a variable and the rows take the first free names "Data Set 1", "Data -/// Set 2" and so on. Existing rows of the same name are replaced; new names are appended. One -/// undo step. +/// Set 2" and so on. Two headers that name one variable are refused. Existing rows of the same +/// name are replaced; new names are appended. One undo step. pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.import"; let bytes = datasets_csv_bytes(p, C)?; @@ -277,6 +277,10 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("empty header in column {}", i + 1))); } let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?; + if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) { + let (first, column) = (first + 1, i + 1); + return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`"))); + } columns.push((i, name, kind)); } // Lock Variables refuses New Variable, so the import is refused when a header would define one. diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 7650df6a2e..776cf19785 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1519,6 +1519,28 @@ fn datasets_csv_refuses_graph_data_file_columns() { assert!(vars.variables.is_empty() && vars.datasets.is_empty()); } +/// Two header cells that name one variable, by the same name or by a name and its prefix, are +/// refused with both columns, and the import changes nothing. +#[test] +fn datasets_csv_refuses_two_columns_for_one_variable() { + let mut s = session(); + s.execute("variable.define", &json!({"name": "Shown", "kind": "visibility"})).unwrap(); + let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); + for (csv, first, second, var) in [ + ("name,City,City\nR,Paris,Rome", 2, 3, "City"), + ("name,City,City\nR,Paris,", 2, 3, "City"), + ("City,Title,City\nParis,x,Rome", 1, 3, "City"), + ("name,Shown,#Shown\nR,true,false", 2, 3, "Shown"), + ("Title\t@Photo\t@ Photo\nx\ta.png\tb.png", 2, 3, "Photo"), + ] { + let err = error(&mut s, csv); + assert!(err.contains(&format!("columns {first} and {second} both name the variable `{var}`")), "{csv}: {err}"); + } + let vars = &s.doc().unwrap().doc.variables; + assert_eq!(vars.variables.len(), 1); + assert!(vars.datasets.is_empty()); +} + /// While the variables are locked, an import is refused when a header cell would define a /// variable, as New Variable is, and a file whose headers all name variables imports. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 6564f158d2..f1b7faf27b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5248,6 +5248,7 @@ digits Malayalam Malaiàlam @msg not found no s’ha trobat @msg not in pattern editing mode no esteu en mode d’edició de motius @msg finish editing the pattern first acabeu primer l’edició del motiu +@msg columns {first} and {column} both name the variable `{name}` les columnes {first} i {column} anomenen totes dues la variable `{name}` @msg nothing encoded no s’ha codificat res @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no s’ha aplicat res del conjunt de dades {name}: cap objecte està vinculat a una variable per a la qual tingui un valor @msg nothing selected no hi ha res seleccionat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index eb9709c6f5..4c9139f121 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5473,6 +5473,7 @@ mark-style Japanese Japonské @msg Batch: {count} processed, {failed} failed Dávka: zpracováno {count}, selhalo {failed} @msg choose a destination folder vyberte cílovou složku @msg choose a source folder vyberte zdrojovou složku +@msg columns {first} and {column} both name the variable `{name}` sloupce {first} a {column} uvádějí stejnou proměnnou `{name}` @msg open a document with data sets otevřete dokument se sadami dat @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ze sady dat {name} se nic nepoužilo: žádný objekt není svázán s proměnnou, pro kterou má hodnotu @msg the action has no steps akce nemá žádné kroky diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 789baa3dd3..7bd2983cd5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5050,6 +5050,7 @@ effect Soft Weich @msg Batch: {count} processed, {failed} failed Stapelverarbeitung: {count} verarbeitet, {failed} fehlgeschlagen @msg choose a destination folder wählen Sie einen Zielordner @msg choose a source folder wählen Sie einen Quellordner +@msg columns {first} and {column} both name the variable `{name}` die Spalten {first} und {column} nennen beide die Variable `{name}` @msg open a document with data sets öffnen Sie ein Dokument mit Datensätzen @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for aus dem Datensatz {name} wurde nichts angewendet: kein Objekt ist an eine Variable gebunden, für die er einen Wert hat @msg the action has no steps die Aktion hat keine Schritte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 521e8761ac..20bd8c7eea 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5404,6 +5404,7 @@ effect Points Σημεία @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης +@msg columns {first} and {column} both name the variable `{name}` οι στήλες {first} και {column} ονομάζουν και οι δύο τη μεταβλητή `{name}` @msg open a document with data sets ανοίξτε ένα έγγραφο με σύνολα δεδομένων @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for δεν εφαρμόστηκε τίποτα από το σύνολο δεδομένων {name}: κανένα αντικείμενο δεν είναι συνδεδεμένο με μεταβλητή για την οποία έχει τιμή @msg select an Intertwine group επιλέξτε μια ομάδα διαπλοκής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a262f90b6f..26a13dddeb 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5414,6 +5414,7 @@ mark-style Japanese Japonesas @msg Batch: {count} processed, {failed} failed Lote: {count} procesados, {failed} con error @msg choose a destination folder elija una carpeta de destino @msg choose a source folder elija una carpeta de origen +@msg columns {first} and {column} both name the variable `{name}` las columnas {first} y {column} nombran la misma variable `{name}` @msg open a document with data sets abra un documento con conjuntos de datos @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no se aplicó nada del conjunto de datos {name}: ningún objeto está vinculado a una variable para la que tenga un valor @msg the action has no steps la acción no tiene pasos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 764b84f2db..12edcafb73 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5416,6 +5416,7 @@ mark-style Japanese Japanilainen @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio +@msg columns {first} and {column} both name the variable `{name}` sarakkeet {first} ja {column} nimeävät molemmat muuttujan `{name}` @msg open a document with data sets avaa asiakirja, jossa on tietojoukkoja @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for tietojoukosta {name} ei käytetty mitään: mitään objektia ei ole sidottu muuttujaan, jolle siinä on arvo @msg select an Intertwine group valitse lomitusryhmä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c9625a8730..6e8e1eeb2f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5470,6 +5470,7 @@ theme Appearance Apparence @msg Batch: {count} processed, {failed} failed Traitement par lots : {count} traités, {failed} en échec @msg choose a destination folder choisissez un dossier de destination @msg choose a source folder choisissez un dossier source +@msg columns {first} and {column} both name the variable `{name}` les colonnes {first} et {column} nomment toutes deux la variable `{name}` @msg open a document with data sets ouvrez un document avec des jeux de données @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for rien du jeu de données {name} n’a été appliqué, car aucun objet n’est lié à une variable pour laquelle il a une valeur @msg the action has no steps l'action n'a aucune étape diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fc7937377a..c028358a39 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5458,6 +5458,7 @@ imageTrace Outline Körvonal @msg Batch: {count} processed, {failed} failed Kötegelt feldolgozás: {count} feldolgozva, {failed} sikertelen @msg choose a destination folder válasszon célmappát @msg choose a source folder válasszon forrásmappát +@msg columns {first} and {column} both name the variable `{name}` a(z) {first}. és a(z) {column}. oszlop ugyanazt a változót nevezi meg: `{name}` @msg open a document with data sets nyisson meg egy adatkészleteket tartalmazó dokumentumot @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ebből az adatkészletből semmi sem lett alkalmazva: {name}; egyetlen objektum sincs olyan változóhoz kötve, amelynek értéke van benne @msg the action has no steps a műveletnek nincsenek lépései diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0cc2f2d912..8f2f93c212 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5085,6 +5085,7 @@ lighting Light Luce @msg Batch: {count} processed, {failed} failed Elaborazione batch: {count} elaborati, {failed} non riusciti @msg choose a destination folder scegli una cartella di destinazione @msg choose a source folder scegli una cartella di origine +@msg columns {first} and {column} both name the variable `{name}` le colonne {first} e {column} indicano entrambe la variabile `{name}` @msg open a document with data sets apri un documento con set di dati @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for non è stato applicato nulla del set di dati {name}: nessun oggetto è associato a una variabile per cui ha un valore @msg the action has no steps l'azione non ha passaggi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index eb24f7595c..4767449f19 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5130,6 +5130,7 @@ lighting Light ライト @msg Batch: {count} processed, {failed} failed バッチ: {count} 件を処理、{failed} 件が失敗しました @msg choose a destination folder 出力先フォルダーを選択してください @msg choose a source folder ソースフォルダーを選択してください +@msg columns {first} and {column} both name the variable `{name}` 列 {first} と列 {column} が同じ変数 `{name}` を指定しています @msg open a document with data sets データセットのあるドキュメントを開いてください @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for データセット {name} から何も適用されませんでした: 値のある変数にバインドされたオブジェクトがありません @msg the action has no steps アクションにステップがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 883e00dcac..dd7083cc9b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5121,6 +5121,7 @@ imageTrace Outline კონტური @msg Batch: {count} processed, {failed} failed პაკეტური დამუშავება: დამუშავდა {count}, ვერ დამუშავდა {failed} @msg choose a destination folder აირჩიეთ დანიშნულების საქაღალდე @msg choose a source folder აირჩიეთ წყარო საქაღალდე +@msg columns {first} and {column} both name the variable `{name}` სვეტები {first} და {column} ორივე ასახელებს ცვლადს `{name}` @msg open a document with data sets გახსენით დოკუმენტი მონაცემთა ნაკრებებით @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for მონაცემთა ნაკრები {name}: არაფერი გამოყენებულა; არცერთი ობიექტი არ არის მიბმული ცვლადზე, რომელსაც მასში მნიშვნელობა აქვს @msg the action has no steps მოქმედებას ნაბიჯები არ აქვს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0164762a5e..af51f5883e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5048,6 +5048,7 @@ lighting Light 광원 @msg Batch: {count} processed, {failed} failed 일괄 처리: {count}개 처리됨, {failed}개 실패 @msg choose a destination folder 대상 폴더를 선택하세요 @msg choose a source folder 소스 폴더를 선택하세요 +@msg columns {first} and {column} both name the variable `{name}` {first}열과 {column}열이 모두 같은 변수 `{name}`을(를) 가리킵니다 @msg open a document with data sets 데이터 세트가 있는 문서를 여세요 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 데이터 세트 {name}에서 적용된 항목이 없습니다: 값이 있는 변수에 연결된 개체가 없습니다 @msg the action has no steps 액션에 단계가 없습니다 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5d57e77cf8..ed0396deac 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5325,6 +5325,7 @@ mark-style Japanese Japońskie @msg Batch: {count} processed, {failed} failed Przetwarzanie wsadowe: przetworzono {count}, niepowodzenia: {failed} @msg choose a destination folder wybierz folder docelowy @msg choose a source folder wybierz folder źródłowy +@msg columns {first} and {column} both name the variable `{name}` kolumny {first} i {column} wskazują tę samą zmienną `{name}` @msg open a document with data sets otwórz dokument z zestawami danych @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for z zestawu danych {name} nic nie zastosowano: żaden obiekt nie jest powiązany ze zmienną, dla której ma on wartość @msg the action has no steps operacja nie ma kroków diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index c725ba6c6c..19d52c9814 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5347,6 +5347,7 @@ mark-style Japanese Japonesas @msg Batch: {count} processed, {failed} failed Lote: {count} processados, {failed} com falha @msg choose a destination folder escolha uma pasta de destino @msg choose a source folder escolha uma pasta de origem +@msg columns {first} and {column} both name the variable `{name}` as colunas {first} e {column} nomeiam a mesma variável `{name}` @msg open a document with data sets abra um documento com conjuntos de dados @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for nada do conjunto de dados {name} foi aplicado: nenhum objeto está vinculado a uma variável para a qual ele tem um valor @msg the action has no steps a ação não tem etapas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f28fa3fca2..a8407da965 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5080,6 +5080,7 @@ lighting Light Свет @msg Batch: {count} processed, {failed} failed Пакетная обработка: обработано {count}, с ошибкой {failed} @msg choose a destination folder выберите папку назначения @msg choose a source folder выберите исходную папку +@msg columns {first} and {column} both name the variable `{name}` столбцы {first} и {column} указывают одну и ту же переменную `{name}` @msg open a document with data sets откройте документ с наборами данных @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for из набора данных {name} ничего не применено: ни один объект не привязан к переменной, для которой в нём есть значение @msg the action has no steps в действии нет шагов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6f30ec2e0c..2382ce365d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5408,6 +5408,7 @@ theme Appearance Utseende @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp +@msg columns {first} and {column} both name the variable `{name}` kolumnerna {first} och {column} anger båda variabeln `{name}` @msg open a document with data sets öppna ett dokument med datauppsättningar @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for inget i datauppsättningen {name} användes: inget objekt är bundet till en variabel som den har ett värde för @msg select an Intertwine group markera en sammanflätningsgrupp diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 6bbfb107b2..e6dcf53c53 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1705,6 +1705,25 @@ fn blend_spine_param_errors_say_what_is_wrong() { assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == "select a blend or give `id`"), "{e}"); } +/// Import Data Sets' refusal of two header cells that name one variable is translated in every +/// language that translates every message. +#[test] +fn dataset_import_repeated_column_error_is_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s.execute("dataset.import", &json!({"csv": "name,City,City\nR,Paris,Rome"})).unwrap_err(); + let want = "columns 2 and 3 both name the variable `City`"; + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{e}"); + let e = e.to_string(); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &e); + assert!(!shown.contains(want), "{code}: {shown}"); + } +} + /// The errors of saving, renaming and deleting a tracing preset are translated in every language /// that translates every message. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8f6e7c4911..b8f648a0c5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5359,6 +5359,7 @@ theme Appearance Görünüm @msg its zlib compression is damaged zlib sıkıştırması hasarlı @msg its Zstandard compression is damaged Zstandard sıkıştırması hasarlı @msg it decompresses to more than {_1} MB açıldığında {_1} MB'tan fazla alan kaplıyor +@msg columns {first} and {column} both name the variable `{name}` {first} ve {column} numaralı sütunların ikisi de `{name}` değişkenini adlandırıyor @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them dosyanın değişkenleri ve veri kümeleri okunmadı (değişkenler: {variables}, veri kümeleri: {data_sets}): Değişkenler paneli bunları listelemiyor @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for {name} veri kümesinden hiçbir şey uygulanmadı: değer içerdiği bir değişkene bağlı hiçbir nesne yok @msg select an Objects on Path group bir Yol Üzerindeki Nesneler grubu seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 86a10d0d46..ecb2074931 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5065,6 +5065,7 @@ lighting Light Світло @msg Batch: {count} processed, {failed} failed Пакетна обробка: оброблено {count}, з помилкою {failed} @msg choose a destination folder виберіть папку призначення @msg choose a source folder виберіть вихідну папку +@msg columns {first} and {column} both name the variable `{name}` стовпці {first} і {column} вказують одну й ту саму змінну `{name}` @msg open a document with data sets відкрийте документ із наборами даних @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for з набору даних {name} нічого не застосовано: жоден об’єкт не прив’язано до змінної, для якої в ньому є значення @msg the action has no steps у дії немає кроків diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index deb4955613..8a6a9935ce 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5068,6 +5068,7 @@ theme Appearance Giao diện @msg Batch: {count} processed, {failed} failed Hàng loạt: đã xử lý {count}, lỗi {failed} @msg choose a destination folder hãy chọn thư mục đích @msg choose a source folder hãy chọn thư mục nguồn +@msg columns {first} and {column} both name the variable `{name}` cột {first} và cột {column} cùng chỉ định biến số `{name}` @msg open a document with data sets hãy mở một tài liệu có tập dữ liệu @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for không có gì trong tập dữ liệu {name} được áp dụng: không có đối tượng nào được gắn với biến số mà tập dữ liệu có giá trị @msg the action has no steps hành động không có bước nào diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 305c4c5995..5903547021 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4532,6 +4532,7 @@ imageTrace Outline 轮廓 @msg Batch: {count} processed, {failed} failed 批处理:已处理 {count} 个,失败 {failed} 个 @msg choose a destination folder 请选择目标文件夹 @msg choose a source folder 请选择源文件夹 +@msg columns {first} and {column} both name the variable `{name}` 第 {first} 列和第 {column} 列都指定了变量 `{name}` @msg open a document with data sets 请打开包含数据集的文档 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 数据集 {name} 未应用任何内容:没有对象绑定到该数据集中有值的变量 @msg the action has no steps 该动作没有步骤 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3ba21bee0b..e4a439e9bc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2448,6 +2448,7 @@ file-filter Templates 範本 @msg Batch: {count} processed, {failed} failed 批次:已處理 {count} 個,失敗 {failed} 個 @msg choose a destination folder 請選擇目的地資料夾 @msg choose a source folder 請選擇來源資料夾 +@msg columns {first} and {column} both name the variable `{name}` 第 {first} 欄和第 {column} 欄都指定了變數 `{name}` @msg open a document with data sets 請開啟含有資料集的文件 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 資料集 {name} 未套用任何內容:沒有物件綁定到該資料集中有值的變數 @msg the action has no steps 動作沒有步驟 diff --git a/docs/mcp.md b/docs/mcp.md index aa997a323d..77a079b4b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1648,7 +1648,8 @@ already walks Image Trace. Short agent entry points: rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph - data files) is refused. The reply's `defined` lists the variables the import defined. While the variables are + data files) is refused, and so are two cells that name one variable (`City` twice, or `Shown` and `#Shown`). The + reply's `defined` lists the variables the import defined. While the variables are locked, an import whose header would define a variable fails with "variables are locked". - Variable libraries: `variable.loadLibrary {path|xml|dataBase64}` (the Variables panel menu's Load Variable Library…) replaces the document's variables and data sets with a variable library's in one undo step. The library From d9024f9c3125d7b1c59ff33c752656056f52e3e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:03:53 +0700 Subject: [PATCH 022/189] Variables: a command that changes nothing adds no undo step Squashed from #5130 onto main. --- crates/engine/src/cmd/graph/data.rs | 8 +- crates/engine/src/cmd/variablecmds.rs | 98 +++++++++++++++---- crates/engine/src/tests/variables.rs | 130 ++++++++++++++++++++++++++ docs/mcp.md | 5 + 4 files changed, 220 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 0e69e0240e..913d52522e 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -87,16 +87,20 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { } /// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with -/// `csv` does. +/// `csv` does. Data the graph already holds leaves the graph as it is. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { let Some(node) = d.node(id) else { return Err(EngineError::NoNode(id)); }; - let Some(mut spec) = node.extras().graph.as_deref().cloned() else { + let Some(current) = node.extras().graph.as_deref() else { return Err(bad("graph.applyCsv", format!("node {} is not a graph", id.0))); }; + let mut spec = current.clone(); apply_data(&mut spec, &json!({ "csv": csv })); keep_right_series(&mut spec); + if spec == *current { + return Ok(()); + } regenerate(d, id, spec) } diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 03636d11f0..873a694e29 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -14,7 +14,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{DataSet, DataValue, NodeId, NodeKind, Variable, VariableKind, Variables}; +use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection, Variable, VariableKind, Variables}; use super::edit::selected_roots; use super::fileio::{absolute_path, read_file_head, write_file}; @@ -44,6 +44,66 @@ fn selection_and_unlocked(s: &Session) -> std::result::Result<(), String> { variables_unlocked(s) } +/// Ends a typing session as [`Session::edit`] would, before a helper below compares the document, +/// so the typing is its own undo step whether or not the command then changes anything. +fn settle_typing(s: &mut Session) -> Result<()> { + if !s.previewing && super::typing_in_progress(s) { + super::settle_interaction(s)?; + } + Ok(()) +} + +/// [`Session::edit`] for a command that changes only the variables and data sets and may change +/// nothing, such as binding art to the variable it already has: `f` runs on a copy of them, and +/// only a copy that differs becomes an undo step. When nothing changed, the undo and redo steps and +/// the saved state stay as they were. +fn edit_variables(s: &mut Session, label: &str, f: impl FnOnce(&mut Variables) -> Result) -> Result { + settle_typing(s)?; + let st = s.doc()?; + let mut vars = st.doc.variables.clone(); + let v = f(&mut vars)?; + if vars != st.doc.variables { + s.edit(label, |d, _| { + d.variables = vars; + Ok(()) + })?; + } + Ok(v) +} + +/// [`Session::edit`] for applying a data set, which may change nothing when the art already shows +/// the active row: `f` runs on a copy of the document and the selection, and only a document that +/// differs becomes an undo step, with the selection `f` left. When the document did not change, the +/// undo and redo steps and the saved state stay as they were, and a selection `f` changed is set +/// without an undo step. When the active row is applied again and the art already shows it, +/// threaded type is compared after its story flows through its frames, as [`Session::edit`] flows +/// it; any other change is an undo step without that extra flow. +fn edit_if_changed(s: &mut Session, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result) -> Result { + settle_typing(s)?; + let st = s.doc()?; + let mut doc = (*st.doc).clone(); + let mut sel = st.selection.clone(); + let v = f(&mut doc, &mut sel)?; + let vars = &st.doc.variables; + if doc != *st.doc + && !doc.text_threads.is_empty() + && doc.variables == *vars + && vars.active_dataset.as_deref().and_then(|n| vars.dataset(n)).is_some_and(|ds| ds.matches(&st.doc.captured_values())) + { + super::threads::reflow(&st.doc, &mut doc); + } + if doc != *st.doc { + s.edit(label, |d, selection| { + *d = doc; + *selection = sel; + Ok(()) + })?; + } else if sel != st.selection { + s.select(|_, selection| *selection = sel)?; + } + Ok(v) +} + fn var_name(p: &Value, cmd: &str) -> Result { named(str_param(p, "name"), "name", cmd) } @@ -228,7 +288,7 @@ fn delete(s: &mut Session, p: &Value) -> Result { // Without `names`, the highlighted variable: what the panel's bin and the menu item delete. let highlighted = s.doc()?.variables_highlight.clone(); let names = names_param(p, "variable.delete", highlighted, "no variable highlighted")?; - let n = s.edit("Delete Variables", |d, _| Ok(d.variables.prune(&names)))?; + let n = edit_variables(s, "Delete Variables", |v| Ok(v.prune(&names)))?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; st.drop_stale_variables_highlight(); @@ -277,7 +337,7 @@ fn bind(s: &mut Session, p: &Value) -> Result { check_bindable(doc, &ids, kind, C)?; // Binding again is not a second binding, and says so rather than counting as a change. let already: Vec = ids.iter().filter(|id| doc.variables.objects_of(&name).contains(id)).map(|id| id.0).collect(); - let n = s.edit("Bind Variable", |d, _| Ok(ids.iter().filter(|id| d.variables.bind(**id, &name)).count()))?; + let n = edit_variables(s, "Bind Variable", |v| Ok(ids.iter().filter(|id| v.bind(**id, &name)).count()))?; Ok(json!({"variable": name, "ids": ids.iter().map(|i| i.0).collect::>(), "bound": n, "already": already})) } @@ -285,13 +345,13 @@ fn unbind(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.unbind"; let ids = checked_ids_or_selection(s, p, C)?; let name = defined_variable(s, p, C)?; - let n = s.edit("Unbind Variable", |d, _| { + let n = edit_variables(s, "Unbind Variable", |vars| { let mut n = 0; for id in &ids { // With `variable` only that one binding goes; without it, every one the object has. match &name { - Some(v) => n += usize::from(d.variables.unbind(*id, v)), - None => n += usize::from(d.variables.bindings.remove(id).is_some()), + Some(v) => n += usize::from(vars.unbind(*id, v)), + None => n += usize::from(vars.bindings.remove(id).is_some()), } } Ok(n) @@ -344,8 +404,8 @@ fn dataset_set(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.set"; let name = var_name(p, C)?; let values = values_param(&s.doc()?.doc.variables, p, C)?; - let (set, removed) = s.edit("Edit Data Set", |d, _| { - let ds = d.variables.datasets.iter_mut().find(|x| x.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; + let (set, removed) = edit_variables(s, "Edit Data Set", |v| { + let ds = v.datasets.iter_mut().find(|x| x.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; let removed: Vec = ds.values.keys().filter(|k| !values.contains_key(*k)).cloned().collect(); ds.values = values.clone(); Ok((values.len(), removed)) @@ -415,8 +475,8 @@ fn dataset_update(s: &mut Session, p: &Value) -> Result { if values.is_empty() { return Err(bad(C, "bind something to a variable first")); } - let (written, left) = s.edit("Update Data Set", |d, _| { - let ds = d.variables.datasets.iter_mut().find(|d| d.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; + let (written, left) = edit_variables(s, "Update Data Set", |vars| { + let ds = vars.datasets.iter_mut().find(|d| d.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; let mut written = BTreeSet::new(); for (var, value) in &values { if all || ds.values.contains_key(var) { @@ -424,7 +484,7 @@ fn dataset_update(s: &mut Session, p: &Value) -> Result { written.insert(var.as_str()); } } - let left: Vec = d.variables.variables.iter().filter(|v| !written.contains(v.name.as_str())).map(|v| v.name.clone()).collect(); + let left: Vec = vars.variables.iter().filter(|v| !written.contains(v.name.as_str())).map(|v| v.name.clone()).collect(); Ok((written.len(), left)) })?; Ok(json!({"name": name, "values": written, "left": left})) @@ -434,14 +494,14 @@ fn dataset_delete(s: &mut Session, p: &Value) -> Result { // Without `names`, the active dataset: what the panel's Delete Data Set deletes. let active = s.doc()?.doc.variables.active_dataset.clone(); let names = names_param(p, "dataset.delete", active, "no active data set")?; - let n = s.edit("Delete Data Sets", |d, _| { - let before = d.variables.datasets.len(); - d.variables.datasets.retain(|d| !names.contains(&d.name)); + let n = edit_variables(s, "Delete Data Sets", |v| { + let before = v.datasets.len(); + v.datasets.retain(|d| !names.contains(&d.name)); // The active dataset's own name is the one that goes, not a variable's. - if d.variables.active_dataset.as_ref().is_some_and(|a| names.contains(a)) { - d.variables.active_dataset = None; + if v.active_dataset.as_ref().is_some_and(|a| names.contains(a)) { + v.active_dataset = None; } - Ok(before - d.variables.datasets.len()) + Ok(before - v.datasets.len()) })?; Ok(json!({"deleted": n})) } @@ -464,7 +524,7 @@ fn dataset_list(s: &mut Session, _p: &Value) -> Result { fn apply_dataset(s: &mut Session, name: &str) -> Result { const C: &str = "dataset.select"; let doc_path = s.doc()?.path.clone(); - let (applied, skipped, mut typed, bound) = s.edit("Apply Data Set", |d, sel| { + let (applied, skipped, mut typed, bound) = edit_if_changed(s, "Apply Data Set", |d, sel| { let ds = d.variables.dataset(name).cloned().ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; // One object may be driven by several variables; walk them in definition order, so two // text variables on the same object land the later one's value and both are counted. @@ -714,7 +774,7 @@ pub fn specs() -> Vec { "Select Data Set", ["Window", "Variables"], None, - "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too); a text value bound to a frame of threaded text replaces the whole story → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits, the story's last frame for threaded text; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}", + "{name} apply a dataset in one undo step (none when it leaves the document as it was), deselecting every selected object left hidden or locked (the key object too); a text value bound to a frame of threaded text replaces the whole story → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits, the story's last frame for threaded text; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}", has_doc, dataset_select ), diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 776cf19785..f470242ded 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1936,3 +1936,133 @@ fn graph_variable_applies_csv_and_captures() { let r = rect(&mut s); assert!(s.execute("variable.bind", &json!({"variable": name, "ids": [r.0]})).is_err()); } + +/// A Variables command that leaves the document as it was (binding art to the variable it already +/// has, unbinding art that has none, deleting a variable or data set that does not exist, writing a +/// row's own values back, applying the active data set again) records no undo step: the step to +/// redo stays, and the document stays unmodified. +#[test] +fn a_variables_command_that_changes_nothing_records_no_undo_step() { + let dir = Folder::new("vars-noop"); + let red_path = dir.file("red.png"); + write(&red_path, &png(8, 8, RED)); + let mut s = session(); + let t = text(&mut s, "Alice"); + let r = rect(&mut s); + let img = place(&mut s, &red_path); + let other = rect(&mut s); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Photo", "ids": [img.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Bob", "Show": false, "Photo": red_path}})).unwrap(); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + let a = json!({"name": "A", "values": {"Name": "Bob", "Show": false, "Photo": red_path}}); + let calls = [ + ("variable.bind", json!({"variable": "Show", "ids": [r.0]})), + ("variable.unbind", json!({"ids": [other.0]})), + ("variable.unbind", json!({"variable": "Name", "ids": [r.0]})), + ("variable.delete", json!({"names": ["Nope"]})), + ("dataset.delete", json!({"names": ["Nope"]})), + ("dataset.set", a), + ("dataset.update", json!({})), + ("dataset.update", json!({"all": true})), + ("dataset.select", json!({"name": "A"})), + ("dataset.next", json!({})), + ("dataset.prev", json!({})), + ]; + for (cmd, p) in calls { + super::select_with_a_step_to_redo(&mut s, &[other]); + let before = super::history(&s); + assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); + s.execute(cmd, &p).unwrap(); + assert_eq!(super::history(&s), before, "{cmd} {p}"); + } + assert_eq!(plain(&s, t), "Bob"); + // Applying the row again still deselects the art it leaves hidden, without an undo step. + s.execute("select.set", &json!({"ids": [r.0, other.0]})).unwrap(); + assert!(s.doc().unwrap().selection.objects.contains(&r), "the hidden rectangle is selected"); + let before = super::history(&s); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + assert_eq!((super::history(&s), s.doc().unwrap().selection.objects.clone()), (before, vec![other])); + // A command that changes something is still one undo step, and it clears Redo. + super::select_with_a_step_to_redo(&mut s, &[other]); + let undo = super::history(&s).0; + s.execute("variable.bind", &json!({"variable": "Show", "ids": [other.0]})).unwrap(); + assert_eq!(super::history(&s), (undo + 1, 0, true)); + s.execute("dataset.new", &json!({"name": "B", "values": {"Name": "Cy"}})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + let undo = super::history(&s).0; + s.execute("dataset.next", &json!({})).unwrap(); + assert_eq!((super::history(&s), plain(&s, t)), ((undo + 1, 0, true), "Cy".to_string())); +} + +/// A Variables command that changes nothing, run while the Type tool is typing, still ends the +/// typing session as one that changes something does: the typing is its own undo step, and the +/// next keystroke starts a new one. +#[test] +fn a_variables_command_that_changes_nothing_ends_the_typing() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let v = ViewInfo::default(); + let t = text(&mut s, "Hello"); + let r = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 50, "height": 40})).unwrap(); + let r = NodeId(r["id"].as_u64().unwrap()); + s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "A", "values": {"Show": true}})).unwrap(); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + for (cmd, p) in [("variable.bind", json!({"variable": "Show", "ids": [r.0]})), ("dataset.select", json!({"name": "A"}))] { + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("!", v).unwrap(); + assert!(crate::cmd::typing_in_progress(&s), "{cmd}"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute(cmd, &p).unwrap(); + assert!(!crate::cmd::typing_in_progress(&s), "{cmd}"); + let labels: Vec = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing")), "{cmd}"); + } +} + +/// Applying the active data set again to threaded type that already holds the row's story records +/// no undo step. +#[test] +fn applying_a_story_row_again_records_no_undo_step() { + let (mut s, a, b, _) = threaded(200); + s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Name", "ids": [a.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Orig"})).unwrap(); + s.execute("dataset.select", &json!({"name": "Orig"})).unwrap(); + assert!(!plain(&s, b).is_empty()); + super::select_with_a_step_to_redo(&mut s, &[a]); + let before = super::history(&s); + s.execute("dataset.select", &json!({"name": "Orig"})).unwrap(); + assert_eq!(super::history(&s), before); +} + +/// Applying the active data set again to a graph whose data already matches the row records no +/// undo step, and a row with other data still rebuilds the graph in one. +#[test] +fn applying_a_graph_row_again_records_no_undo_step() { + let mut s = session(); + let graph = json!({"type": "column", "x": 10, "y": 10, "width": 120, "height": 80, "csv": ",Sales\nA,1\nB,2"}); + let id = s.execute("graph.create", &graph).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("variable.makeGraphDynamic", &json!({})).unwrap(); + let name = s.execute("variable.list", &json!({})).unwrap()["variables"][0]["name"].as_str().unwrap().to_string(); + s.execute("dataset.new", &json!({"name": "A", "values": {name.clone(): ",Sales\nA,10\nB,20"}})).unwrap(); + s.execute("dataset.new", &json!({"name": "B", "values": {name: ",Sales\nA,3\nB,4"}})).unwrap(); + s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[NodeId(id)]); + let before = super::history(&s); + let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + assert_eq!((v["applied"].as_u64(), super::history(&s)), (Some(1), before)); + s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!(super::history(&s), (before.0 + 1, 0, true)); +} diff --git a/docs/mcp.md b/docs/mcp.md index 77a079b4b8..7b9c59a14f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1743,6 +1743,11 @@ Brushes panel's New Brush button, its menu's New Brush… and art dropped on the Brush Options for the new brush; for a scatter, art or pattern brush they preview the art from `brush.selectionArt`. Their OK runs `brush.new {type, name, params, ids?}`, and Cancel adds no brush. +`variable.bind`, `variable.unbind`, `variable.delete`, `dataset.set`, `dataset.update`, `dataset.delete`, +`dataset.select`, `dataset.next` and `dataset.prev` add no undo step when they leave the document as it was, such as +binding art to a variable it already has or applying the active data set again: the steps to redo stay, and a saved +document stays unmodified. + `dataset.select`, `dataset.next` and `dataset.prev` reply `{name, applied, skipped}`. They add `overflow: [id…]` when area type or type on a path whose text they rewrote doesn't fit, as `text.setText` does (see [Fitting area type](#fitting-area-type-auto-size-shrink-text-to-fit-overflow)). They skip an object that is From d0749dde4116bfcd4c9780e25a9354e7085c9e2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:07:45 +0700 Subject: [PATCH 023/189] Variables: Update Data Set keeps a row's values when every bound object is locked Squashed from #5126 onto main. --- crates/engine/src/cmd/variablecmds.rs | 35 ++++++++++++++++----------- crates/engine/src/tests/variables.rs | 34 ++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 3 ++- 24 files changed, 78 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 873a694e29..70a5af9381 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -442,6 +442,9 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let values = st.doc.captured_values(); if values.is_empty() { + if anything_bound(&st.doc) { + return Err(bad(C, "no bound object reports a value (locked objects and embedded images report none)")); + } return Err(bad(C, "bind something to a variable first")); } let name = match optional_name(p, "name", C)? { @@ -464,32 +467,36 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { /// variable the row holds. A variable whose objects report no value (locked, inside a locked /// layer or group, or gone) keeps the row's value. With `all`, every other variable the /// objects report a value for is added to the row. Without an active row there is nothing to -/// update, so say so rather than picking one. +/// update, so say so rather than picking one. With every bound object locked, no value is +/// written; an update that writes no value adds no undo step. fn dataset_update(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.update"; let all = bool_or(p, "all", false); - let values = s.doc()?.doc.captured_values(); - let Some(name) = s.doc()?.doc.variables.active_dataset.clone() else { + let st = s.doc()?; + let Some(name) = st.doc.variables.active_dataset.clone() else { return Err(bad(C, "no active data set")); }; - if values.is_empty() { + if !anything_bound(&st.doc) { return Err(bad(C, "bind something to a variable first")); } - let (written, left) = edit_variables(s, "Update Data Set", |vars| { + let ds = st.doc.variables.dataset(&name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; + let writes: BTreeMap = st.doc.captured_values().into_iter().filter(|(var, _)| all || ds.values.contains_key(var)).collect(); + let left: Vec = st.doc.variables.variables.iter().filter(|v| !writes.contains_key(&v.name)).map(|v| v.name.clone()).collect(); + let written = writes.len(); + edit_variables(s, "Update Data Set", |vars| { let ds = vars.datasets.iter_mut().find(|d| d.name == name).ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; - let mut written = BTreeSet::new(); - for (var, value) in &values { - if all || ds.values.contains_key(var) { - ds.values.insert(var.clone(), value.clone()); - written.insert(var.as_str()); - } - } - let left: Vec = vars.variables.iter().filter(|v| !written.contains(v.name.as_str())).map(|v| v.name.clone()).collect(); - Ok((written.len(), left)) + ds.values.extend(writes); + Ok(()) })?; Ok(json!({"name": name, "values": written, "left": left})) } +/// Whether any object in the document is bound to a variable. A locked one counts: it is +/// bound, though it reports no value. +fn anything_bound(doc: &Document) -> bool { + doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some()) +} + fn dataset_delete(s: &mut Session, p: &Value) -> Result { // Without `names`, the active dataset: what the panel's Delete Data Set deletes. let active = s.doc()?.doc.variables.active_dataset.clone(); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index f470242ded..84a2779775 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -709,6 +709,40 @@ fn updating_keeps_a_value_the_art_does_not_report() { } } +/// With every bound object locked, Update keeps the whole row and adds no undo step, and +/// Capture says the bound objects report no value rather than asking for a binding. +#[test] +fn updating_with_every_bound_object_locked_keeps_the_row() { + let mut s = session(); + let t = text(&mut s, "First"); + s.execute("variable.define", &json!({"name": "Label", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Label", "ids": [t.0]})).unwrap(); + s.execute("dataset.new", &json!({"name": "Row", "values": {"Label": "Second"}})).unwrap(); + s.execute("dataset.select", &json!({"name": "Row"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [t.0], "locked": true})).unwrap(); + + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + for params in [json!({}), json!({"all": true})] { + let v = s.execute("dataset.update", ¶ms).unwrap(); + assert_eq!((v["values"].clone(), v["left"].clone()), (json!(0), json!(["Label"])), "{params}: {v}"); + let sets = s.execute("dataset.list", &json!({})).unwrap(); + assert_eq!(sets["datasets"][0]["values"], json!({"Label": {"text": "Second"}}), "{params}: {sets}"); + } + assert_eq!(steps(&s), before, "an update that writes nothing is not a step"); + + let e = s.execute("dataset.capture", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no bound object reports a value"), "{e}"); + assert_eq!(s.execute("dataset.list", &json!({})).unwrap()["datasets"].as_array().unwrap().len(), 1); + + // With nothing bound at all, both still ask for a binding. + s.execute("variable.unbind", &json!({"ids": [t.0]})).unwrap(); + for cmd in ["dataset.update", "dataset.capture"] { + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains("bind something to a variable first"), "{cmd}: {e}"); + } +} + /// A variable defined after a row was captured stays out of that row on Update, and joins it /// with `all: true`. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f1b7faf27b..205991cbce 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5251,6 +5251,7 @@ digits Malayalam Malaiàlam @msg columns {first} and {column} both name the variable `{name}` les columnes {first} i {column} anomenen totes dues la variable `{name}` @msg nothing encoded no s’ha codificat res @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no s’ha aplicat res del conjunt de dades {name}: cap objecte està vinculat a una variable per a la qual tingui un valor +@msg no bound object reports a value (locked objects and embedded images report none) cap objecte vinculat no informa d’un valor (els objectes bloquejats i les imatges incrustades no n’informen cap) @msg nothing selected no hi ha res seleccionat @msg nothing to align no hi ha res per alinear @msg nothing to distort no hi ha res per distorsionar diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4c9139f121..a6d23ba3cd 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5476,6 +5476,7 @@ mark-style Japanese Japonské @msg columns {first} and {column} both name the variable `{name}` sloupce {first} a {column} uvádějí stejnou proměnnou `{name}` @msg open a document with data sets otevřete dokument se sadami dat @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ze sady dat {name} se nic nepoužilo: žádný objekt není svázán s proměnnou, pro kterou má hodnotu +@msg no bound object reports a value (locked objects and embedded images report none) žádný svázaný objekt nevrací hodnotu (zamčené objekty a vložené obrazy žádnou nevracejí) @msg the action has no steps akce nemá žádné kroky # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7bd2983cd5..1433e9d1cb 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5053,6 +5053,7 @@ effect Soft Weich @msg columns {first} and {column} both name the variable `{name}` die Spalten {first} und {column} nennen beide die Variable `{name}` @msg open a document with data sets öffnen Sie ein Dokument mit Datensätzen @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for aus dem Datensatz {name} wurde nichts angewendet: kein Objekt ist an eine Variable gebunden, für die er einen Wert hat +@msg no bound object reports a value (locked objects and embedded images report none) kein gebundenes Objekt liefert einen Wert (gesperrte Objekte und eingebettete Bilder liefern keinen) @msg the action has no steps die Aktion hat keine Schritte # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 20bd8c7eea..f28611c541 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5407,6 +5407,7 @@ effect Points Σημεία @msg columns {first} and {column} both name the variable `{name}` οι στήλες {first} και {column} ονομάζουν και οι δύο τη μεταβλητή `{name}` @msg open a document with data sets ανοίξτε ένα έγγραφο με σύνολα δεδομένων @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for δεν εφαρμόστηκε τίποτα από το σύνολο δεδομένων {name}: κανένα αντικείμενο δεν είναι συνδεδεμένο με μεταβλητή για την οποία έχει τιμή +@msg no bound object reports a value (locked objects and embedded images report none) κανένα συνδεδεμένο αντικείμενο δεν αναφέρει τιμή (τα κλειδωμένα αντικείμενα και οι ενσωματωμένες εικόνες δεν αναφέρουν καμία) @msg select an Intertwine group επιλέξτε μια ομάδα διαπλοκής @msg select an Objects on Path group επιλέξτε μια ομάδα αντικειμένων σε διαδρομή @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects μια διαδρομή μέσα σε σύνθετη διαδρομή, ανάμειξη, περίβλημα, επανάληψη ή ομάδα διαπλοκής δεν μπορεί να δεχτεί αντικείμενα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 26a13dddeb..dbd5dfb238 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5417,6 +5417,7 @@ mark-style Japanese Japonesas @msg columns {first} and {column} both name the variable `{name}` las columnas {first} y {column} nombran la misma variable `{name}` @msg open a document with data sets abra un documento con conjuntos de datos @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no se aplicó nada del conjunto de datos {name}: ningún objeto está vinculado a una variable para la que tenga un valor +@msg no bound object reports a value (locked objects and embedded images report none) ningún objeto vinculado informa de un valor (los objetos bloqueados y las imágenes incrustadas no informan de ninguno) @msg the action has no steps la acción no tiene pasos # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 12edcafb73..e232c972a8 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5419,6 +5419,7 @@ mark-style Japanese Japanilainen @msg columns {first} and {column} both name the variable `{name}` sarakkeet {first} ja {column} nimeävät molemmat muuttujan `{name}` @msg open a document with data sets avaa asiakirja, jossa on tietojoukkoja @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for tietojoukosta {name} ei käytetty mitään: mitään objektia ei ole sidottu muuttujaan, jolle siinä on arvo +@msg no bound object reports a value (locked objects and embedded images report none) mikään sidottu objekti ei ilmoita arvoa (lukitut objektit ja upotetut kuvat eivät ilmoita arvoa) @msg select an Intertwine group valitse lomitusryhmä @msg select an Objects on Path group valitse Objektit polulla -ryhmä @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects yhdistelmäpolun, sulautuksen, vääristyskuoren, toiston tai lomitusryhmän sisällä olevaan polkuun ei voi kiinnittää objekteja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6e8e1eeb2f..789e40c815 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5473,6 +5473,7 @@ theme Appearance Apparence @msg columns {first} and {column} both name the variable `{name}` les colonnes {first} et {column} nomment toutes deux la variable `{name}` @msg open a document with data sets ouvrez un document avec des jeux de données @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for rien du jeu de données {name} n’a été appliqué, car aucun objet n’est lié à une variable pour laquelle il a une valeur +@msg no bound object reports a value (locked objects and embedded images report none) aucun objet lié ne fournit de valeur (les objets verrouillés et les images incorporées n’en fournissent aucune) @msg the action has no steps l'action n'a aucune étape # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c028358a39..76dc225e81 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5461,6 +5461,7 @@ imageTrace Outline Körvonal @msg columns {first} and {column} both name the variable `{name}` a(z) {first}. és a(z) {column}. oszlop ugyanazt a változót nevezi meg: `{name}` @msg open a document with data sets nyisson meg egy adatkészleteket tartalmazó dokumentumot @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ebből az adatkészletből semmi sem lett alkalmazva: {name}; egyetlen objektum sincs olyan változóhoz kötve, amelynek értéke van benne +@msg no bound object reports a value (locked objects and embedded images report none) egyetlen kötött objektum sem ad értéket (a zárolt objektumok és a beágyazott képek nem adnak értéket) @msg the action has no steps a műveletnek nincsenek lépései # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2f93c212..ad25ad87c4 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5088,6 +5088,7 @@ lighting Light Luce @msg columns {first} and {column} both name the variable `{name}` le colonne {first} e {column} indicano entrambe la variabile `{name}` @msg open a document with data sets apri un documento con set di dati @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for non è stato applicato nulla del set di dati {name}: nessun oggetto è associato a una variabile per cui ha un valore +@msg no bound object reports a value (locked objects and embedded images report none) nessun oggetto associato restituisce un valore (gli oggetti bloccati e le immagini incorporate non ne restituiscono) @msg the action has no steps l'azione non ha passaggi # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4767449f19..804186dd67 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5133,6 +5133,7 @@ lighting Light ライト @msg columns {first} and {column} both name the variable `{name}` 列 {first} と列 {column} が同じ変数 `{name}` を指定しています @msg open a document with data sets データセットのあるドキュメントを開いてください @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for データセット {name} から何も適用されませんでした: 値のある変数にバインドされたオブジェクトがありません +@msg no bound object reports a value (locked objects and embedded images report none) 値を返すバインドされたオブジェクトがありません (ロックされたオブジェクトと埋め込み画像は値を返しません) @msg the action has no steps アクションにステップがありません # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index dd7083cc9b..250e0f384e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5124,6 +5124,7 @@ imageTrace Outline კონტური @msg columns {first} and {column} both name the variable `{name}` სვეტები {first} და {column} ორივე ასახელებს ცვლადს `{name}` @msg open a document with data sets გახსენით დოკუმენტი მონაცემთა ნაკრებებით @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for მონაცემთა ნაკრები {name}: არაფერი გამოყენებულა; არცერთი ობიექტი არ არის მიბმული ცვლადზე, რომელსაც მასში მნიშვნელობა აქვს +@msg no bound object reports a value (locked objects and embedded images report none) არცერთი მიბმული ობიექტი არ აბრუნებს მნიშვნელობას (ჩაკეტილი ობიექტები და ჩაშენებული გამოსახულებები მნიშვნელობას არ აბრუნებს) @msg the action has no steps მოქმედებას ნაბიჯები არ აქვს Convert to Straight Lines სწორ ხაზებად გარდაქმნა Corner Point Angle Threshold: კუთხოვანი წერტილის კუთხის ზღვარი: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index af51f5883e..3ee9cb9d4c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5051,6 +5051,7 @@ lighting Light 광원 @msg columns {first} and {column} both name the variable `{name}` {first}열과 {column}열이 모두 같은 변수 `{name}`을(를) 가리킵니다 @msg open a document with data sets 데이터 세트가 있는 문서를 여세요 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 데이터 세트 {name}에서 적용된 항목이 없습니다: 값이 있는 변수에 연결된 개체가 없습니다 +@msg no bound object reports a value (locked objects and embedded images report none) 값을 보고하는 연결된 개체가 없습니다(잠긴 개체와 포함된 이미지는 값을 보고하지 않습니다) @msg the action has no steps 액션에 단계가 없습니다 # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ed0396deac..5830a1b6ab 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5328,6 +5328,7 @@ mark-style Japanese Japońskie @msg columns {first} and {column} both name the variable `{name}` kolumny {first} i {column} wskazują tę samą zmienną `{name}` @msg open a document with data sets otwórz dokument z zestawami danych @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for z zestawu danych {name} nic nie zastosowano: żaden obiekt nie jest powiązany ze zmienną, dla której ma on wartość +@msg no bound object reports a value (locked objects and embedded images report none) żaden powiązany obiekt nie zwraca wartości (zablokowane obiekty i osadzone obrazy nie zwracają żadnej) @msg the action has no steps operacja nie ma kroków # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 19d52c9814..00c6192224 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5350,6 +5350,7 @@ mark-style Japanese Japonesas @msg columns {first} and {column} both name the variable `{name}` as colunas {first} e {column} nomeiam a mesma variável `{name}` @msg open a document with data sets abra um documento com conjuntos de dados @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for nada do conjunto de dados {name} foi aplicado: nenhum objeto está vinculado a uma variável para a qual ele tem um valor +@msg no bound object reports a value (locked objects and embedded images report none) nenhum objeto vinculado informa um valor (objetos bloqueados e imagens incorporadas não informam nenhum) @msg the action has no steps a ação não tem etapas @msg Angles require two straight segments Ângulos exigem dois segmentos retos @msg Choose a circle or a perfect arc Escolha um círculo ou um arco perfeito diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a8407da965..50d1ca1bdd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5083,6 +5083,7 @@ lighting Light Свет @msg columns {first} and {column} both name the variable `{name}` столбцы {first} и {column} указывают одну и ту же переменную `{name}` @msg open a document with data sets откройте документ с наборами данных @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for из набора данных {name} ничего не применено: ни один объект не привязан к переменной, для которой в нём есть значение +@msg no bound object reports a value (locked objects and embedded images report none) ни один привязанный объект не сообщает значение (заблокированные объекты и внедрённые изображения не сообщают значений) @msg the action has no steps в действии нет шагов # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2382ce365d..8ca7a39271 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5411,6 +5411,7 @@ theme Appearance Utseende @msg columns {first} and {column} both name the variable `{name}` kolumnerna {first} och {column} anger båda variabeln `{name}` @msg open a document with data sets öppna ett dokument med datauppsättningar @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for inget i datauppsättningen {name} användes: inget objekt är bundet till en variabel som den har ett värde för +@msg no bound object reports a value (locked objects and embedded images report none) inget bundet objekt rapporterar ett värde (låsta objekt och inbäddade bilder rapporterar inget) @msg select an Intertwine group markera en sammanflätningsgrupp @msg select an Objects on Path group markera en grupp med objekt på bana @msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects en bana inuti en sammansatt bana, en blandning, ett kuvert, en upprepning eller en sammanflätningsgrupp kan inte ta emot objekt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b8f648a0c5..c893d81f38 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5362,6 +5362,7 @@ theme Appearance Görünüm @msg columns {first} and {column} both name the variable `{name}` {first} ve {column} numaralı sütunların ikisi de `{name}` değişkenini adlandırıyor @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them dosyanın değişkenleri ve veri kümeleri okunmadı (değişkenler: {variables}, veri kümeleri: {data_sets}): Değişkenler paneli bunları listelemiyor @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for {name} veri kümesinden hiçbir şey uygulanmadı: değer içerdiği bir değişkene bağlı hiçbir nesne yok +@msg no bound object reports a value (locked objects and embedded images report none) bağlı hiçbir nesne bir değer bildirmiyor (kilitli nesneler ve gömülü görüntüler değer bildirmez) @msg select an Objects on Path group bir Yol Üzerindeki Nesneler grubu seçin @msg the Simplify slider is not open Basitleştirme kaydırıcısı açık değil @msg the Smooth slider is not open Düzgünleştirme kaydırıcısı açık değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ecb2074931..2676d107e6 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5068,6 +5068,7 @@ lighting Light Світло @msg columns {first} and {column} both name the variable `{name}` стовпці {first} і {column} вказують одну й ту саму змінну `{name}` @msg open a document with data sets відкрийте документ із наборами даних @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for з набору даних {name} нічого не застосовано: жоден об’єкт не прив’язано до змінної, для якої в ньому є значення +@msg no bound object reports a value (locked objects and embedded images report none) жоден прив’язаний об’єкт не повідомляє значення (заблоковані об’єкти та вбудовані зображення не повідомляють значень) @msg the action has no steps у дії немає кроків # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8a6a9935ce..42de855e0c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5071,6 +5071,7 @@ theme Appearance Giao diện @msg columns {first} and {column} both name the variable `{name}` cột {first} và cột {column} cùng chỉ định biến số `{name}` @msg open a document with data sets hãy mở một tài liệu có tập dữ liệu @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for không có gì trong tập dữ liệu {name} được áp dụng: không có đối tượng nào được gắn với biến số mà tập dữ liệu có giá trị +@msg no bound object reports a value (locked objects and embedded images report none) không có đối tượng được gắn nào báo cáo giá trị (đối tượng bị khóa và hình ảnh nhúng không báo cáo giá trị nào) @msg the action has no steps hành động không có bước nào # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5903547021..53a2e2847d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4535,6 +4535,7 @@ imageTrace Outline 轮廓 @msg columns {first} and {column} both name the variable `{name}` 第 {first} 列和第 {column} 列都指定了变量 `{name}` @msg open a document with data sets 请打开包含数据集的文档 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 数据集 {name} 未应用任何内容:没有对象绑定到该数据集中有值的变量 +@msg no bound object reports a value (locked objects and embedded images report none) 没有绑定的对象报告值 (锁定的对象和嵌入的图像不报告值) @msg the action has no steps 该动作没有步骤 # Import Shortcut Set (Keyboard Shortcuts › Import…, File › Open of a .kys file) and its commands. Import Shortcut Set 导入快捷键组 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e4a439e9bc..0e9c6b5f29 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2451,6 +2451,7 @@ file-filter Templates 範本 @msg columns {first} and {column} both name the variable `{name}` 第 {first} 欄和第 {column} 欄都指定了變數 `{name}` @msg open a document with data sets 請開啟含有資料集的文件 @msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 資料集 {name} 未套用任何內容:沒有物件綁定到該資料集中有值的變數 +@msg no bound object reports a value (locked objects and embedded images report none) 沒有綁定的物件回報值 (鎖定的物件和內嵌的影像不回報值) @msg the action has no steps 動作沒有步驟 @msg cancelled; nothing was changed 已取消;未做任何變更 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 「儲存」會寫入 {_1},而非 {_2}:若要寫入該格式,請使用 file.saveAsTemplate diff --git a/docs/mcp.md b/docs/mcp.md index 7b9c59a14f..ca9b00379d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1788,7 +1788,8 @@ or no, or a graph value longer than 262,144 bytes. data set holds. A variable whose objects report no value, because they are locked, inside a locked layer or group, or deleted, keeps the data set's value. With `all: true` it also adds every other variable that the objects report a value for. The reply gives `values`, the number of values it wrote, and `left`, the variables it -did not write. +did not write. When every bound object is locked, it writes no value and adds no undo step, and `dataset.capture` +returns the error "no bound object reports a value (locked objects and embedded images report none)". ## Graphic styles From a6ce22da5cc9c32680b0b68a8bdbdb89d9ae3cdb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 10:02:06 -0800 Subject: [PATCH 024/189] Variables: an import or library load that changes nothing adds no undo step dataset.import and variable.loadLibrary added an undo step, cleared Redo and marked a saved document modified even when the variables and data sets came out as they were, such as the same CSV or library loaded again. Both now build the new variables on a copy and record a step only when it differs. variable.loadLibrary's params text and docs/mcp.md say so. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/cmd/variablecmds/csv.rs | 33 +++++++----- crates/engine/src/cmd/variablecmds/library.rs | 22 +++++--- crates/engine/src/tests/variables.rs | 53 +++++++++++++++++++ docs/mcp.md | 3 +- 5 files changed, 89 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 70a5af9381..66948e692e 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -816,7 +816,7 @@ pub fn specs() -> Vec { "Load Variable Library…", ["Window", "Variables"], None, - "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step. Every variable of the document is deleted with its bindings and values, and every data set is deleted; then variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}", + "{path? | xml? | dataBase64?} replace the document's variables and data sets with a variable library's (XML: `variableSets` › `variableSet` › `variables` of `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements with `dataSetName`) in one undo step (none when the document already holds what the library gives). Every variable of the document is deleted with its bindings and values, and every data set is deleted; then variables whose `trait` is `textcontent` are defined as text variables, unbound, and each data set takes a value for a variable from the `p` elements of the element named after it, one paragraph each. Variables of other kinds are left out and named in `skipped` and `warning`. Refused while the variables are locked when it would delete or define a variable → {variables, deleted, deletedDataSets, names, skipped, warning?}", has_doc, load_library ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 8f23772a3f..f9e170c596 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -324,21 +324,26 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { } let names: Vec = parsed.iter().map(|d| d.name.clone()).collect(); let new_variables: Vec = defined.iter().map(|v| v.name.clone()).collect(); - let (imported, updated) = s.edit("Import Data Sets", |d, _| { - d.variables.variables.extend(defined); - let mut imported = 0usize; - let mut updated = 0usize; - for row in parsed { - if let Some(existing) = d.variables.datasets.iter_mut().find(|x| x.name == row.name) { - *existing = row; - updated += 1; - } else { - d.variables.datasets.push(row); - imported += 1; - } + let mut vars = s.doc()?.doc.variables.clone(); + vars.variables.extend(defined); + let (mut imported, mut updated) = (0usize, 0usize); + for row in parsed { + if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) { + *existing = row; + updated += 1; + } else { + vars.datasets.push(row); + imported += 1; } - Ok((imported, updated)) - })?; + } + // The import is one undo step, and an import that leaves the variables and data sets as they + // were adds none. + if vars != s.doc()?.doc.variables { + s.edit("Import Data Sets", |d, _| { + d.variables = vars; + Ok(()) + })?; + } Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables})) } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index b410af042f..cdd2ba4d0c 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -249,7 +249,8 @@ fn parse_library(xml: &str, cmd: &str) -> Result { } /// Load Variable Library: replace the document's variables and data sets with a variable library's -/// ([`parse_library`]) in one undo step. Every variable of the document is deleted with its bindings +/// ([`parse_library`]) in one undo step, or none when the document already holds what the library +/// gives. Every variable of the document is deleted with its bindings /// and values, and every data set is deleted. The library's text variables are then defined, /// unbound, and its data sets are added. The library's variables of other kinds are left out, named /// in `skipped` and in a warning. @@ -268,13 +269,18 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { } let added: Vec = lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(); let names: Vec = lib.datasets.iter().map(|d| d.name.clone()).collect(); - s.edit("Load Variable Library", |d, _| { - d.variables.prune(&deleted); - d.variables.variables.extend(added); - d.variables.datasets = lib.datasets; - d.variables.active_dataset = None; - Ok(()) - })?; + let mut vars = s.doc()?.doc.variables.clone(); + vars.prune(&deleted); + vars.variables.extend(added); + vars.datasets = lib.datasets; + vars.active_dataset = None; + // A load that leaves the variables and data sets as they were adds no undo step. + if vars != s.doc()?.doc.variables { + s.edit("Load Variable Library", |d, _| { + d.variables = vars; + Ok(()) + })?; + } // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; st.drop_stale_variables_highlight(); diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 84a2779775..1844d9f20d 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1762,6 +1762,59 @@ fn a_variable_library_replaces_every_variable_and_data_set() { assert_eq!(s.doc().unwrap().doc.variables, before, "one undo step brings everything back"); } +/// An import or a library load that leaves the variables and data sets as they were (the same CSV +/// imported again, a row rewritten with its own values, the same library loaded again) records no +/// undo step: the step to redo stays, and the document stays unmodified. An import or load that +/// changes something is still one undo step. +#[test] +fn an_import_or_library_load_that_changes_nothing_records_no_undo_step() { + let mut s = session(); + let t = text(&mut s, "Alice"); + let csv = "name,Name,#Shown\nA,Ann,true\nB,Bob,false\n"; + s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + for csv in [csv, "name\tName\t#Shown\nB\tBob\tfalse\n", "Name,#Shown\nAnn,true\n"] { + super::select_with_a_step_to_redo(&mut s, &[t]); + let before = super::history(&s); + assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); + let r = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); + if csv.starts_with("name") { + assert_eq!((super::history(&s), r["imported"].clone()), (before, json!(0)), "{csv}"); + } else { + // Without a name column the row is a new data set, which is a change. + assert_eq!((super::history(&s), r["imported"].clone()), ((before.0 + 1, 0, true), json!(1)), "{csv}"); + } + } + super::select_with_a_step_to_redo(&mut s, &[t]); + let undo = super::history(&s).0; + s.execute("dataset.import", &json!({"csv": "name,Name\nB,Cy\n"})).unwrap(); + assert_eq!(super::history(&s), (undo + 1, 0, true)); + + let xml = library(&[("Name", "textcontent")], &[("A", &[("Name", &["Ann"])]), ("B", &[("Name", &["Bob"])])]); + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[t]); + let before = super::history(&s); + let r = s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!((super::history(&s), r["names"].clone()), (before, json!(["A", "B"]))); + // Binding the variable makes the next load a change: it deletes the binding. + s.execute("variable.bind", &json!({"variable": "Name", "ids": [t.0]})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[t]); + let undo = super::history(&s).0; + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(super::history(&s), (undo + 1, 0, true)); + + // While the variables are locked, a library without text variables still loads its data sets, + // and loading it again changes nothing. + let mut s = session(); + let t = text(&mut s, "Alice"); + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + let xml = library(&[("Shown", "other")], &[("B", &[])]); + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + super::select_with_a_step_to_redo(&mut s, &[t]); + let before = super::history(&s); + s.execute("variable.loadLibrary", &json!({"xml": xml})).unwrap(); + assert_eq!(super::history(&s), before); +} + /// A library that is refused leaves the document's variables and data sets as they were. #[test] fn a_refused_variable_library_deletes_nothing() { diff --git a/docs/mcp.md b/docs/mcp.md index ca9b00379d..f98195ed33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1652,7 +1652,8 @@ already walks Image Trace. Short agent entry points: reply's `defined` lists the variables the import defined. While the variables are locked, an import whose header would define a variable fails with "variables are locked". - Variable libraries: `variable.loadLibrary {path|xml|dataBase64}` (the Variables panel menu's Load Variable - Library…) replaces the document's variables and data sets with a variable library's in one undo step. The library + Library…) replaces the document's variables and data sets with a variable library's in one undo step. A load, like a + `dataset.import`, adds no undo step when it leaves the variables and data sets as they were. The library is XML whose `variableSets` element holds `variableSet` elements, each with a `variables` element of `variable` elements (`varName`, `trait`) and a `sampleDataSets` element of `sampleDataSet` elements (`dataSetName`). Every variable of the document is deleted with its bindings and values, and every data set is deleted. Then the library's From 78014a1b436f0de44b35cca9cc55f3e6753b4576 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:08:28 +0700 Subject: [PATCH 025/189] Variables: Import Data Sets and Load Variable Library record their step through edit_variables --- crates/engine/src/cmd/variablecmds/csv.rs | 32 ++++++++----------- crates/engine/src/cmd/variablecmds/library.rs | 18 ++++------- 2 files changed, 21 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index f9e170c596..47376d78f1 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -324,26 +324,22 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { } let names: Vec = parsed.iter().map(|d| d.name.clone()).collect(); let new_variables: Vec = defined.iter().map(|v| v.name.clone()).collect(); - let mut vars = s.doc()?.doc.variables.clone(); - vars.variables.extend(defined); - let (mut imported, mut updated) = (0usize, 0usize); - for row in parsed { - if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) { - *existing = row; - updated += 1; - } else { - vars.datasets.push(row); - imported += 1; - } - } // The import is one undo step, and an import that leaves the variables and data sets as they // were adds none. - if vars != s.doc()?.doc.variables { - s.edit("Import Data Sets", |d, _| { - d.variables = vars; - Ok(()) - })?; - } + let (imported, updated) = super::edit_variables(s, "Import Data Sets", |vars| { + vars.variables.extend(defined); + let (mut imported, mut updated) = (0usize, 0usize); + for row in parsed { + if let Some(existing) = vars.datasets.iter_mut().find(|x| x.name == row.name) { + *existing = row; + updated += 1; + } else { + vars.datasets.push(row); + imported += 1; + } + } + Ok((imported, updated)) + })?; Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables})) } diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index cdd2ba4d0c..7e57b23754 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -269,18 +269,14 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { } let added: Vec = lib.text.iter().map(|n| Variable { name: n.clone(), kind: VariableKind::Text }).collect(); let names: Vec = lib.datasets.iter().map(|d| d.name.clone()).collect(); - let mut vars = s.doc()?.doc.variables.clone(); - vars.prune(&deleted); - vars.variables.extend(added); - vars.datasets = lib.datasets; - vars.active_dataset = None; // A load that leaves the variables and data sets as they were adds no undo step. - if vars != s.doc()?.doc.variables { - s.edit("Load Variable Library", |d, _| { - d.variables = vars; - Ok(()) - })?; - } + super::edit_variables(s, "Load Variable Library", |vars| { + vars.prune(&deleted); + vars.variables.extend(added); + vars.datasets = lib.datasets; + vars.active_dataset = None; + Ok(()) + })?; // A highlight of a variable that is gone highlights nothing. let st = s.doc_mut()?; st.drop_stale_variables_highlight(); From f024f5a5f258b9028a79269bddb63876b513d048 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:10:05 +0700 Subject: [PATCH 026/189] Variables: Export Data Sets marks visibility and image columns with # and @ Squashed from #5141 onto main. --- crates/engine/src/cmd/variablecmds.rs | 5 +- crates/engine/src/cmd/variablecmds/csv.rs | 85 ++++++++++++++++++--- crates/engine/src/tests/variables.rs | 91 +++++++++++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/variables.rs | 37 +++++++++ docs/mcp.md | 8 +- 31 files changed, 287 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 66948e692e..96b3c2a7a4 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -5,7 +5,8 @@ //! variable, or a graph root to a `graph` variable (CSV data), put a row of values in //! each dataset, and `dataset.select` swaps the whole document to that row in one undo //! step. `dataset.import` / `dataset.export` move those rows as CSV (header: `name` -//! then variable names); import also reads tab-separated files, files without the +//! then variable names, which export writes with `#` before a visibility variable and `@` +//! before an image variable); import also reads tab-separated files, files without the //! `name` column, and header cells that define new variables (`#` for visibility, `@` for //! image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the //! text variables and data sets of a variable library, the XML file of the reference app's Save @@ -807,7 +808,7 @@ pub fn specs() -> Vec { "Export Data Sets…", ["Window", "Variables"], None, - "{path?} write every dataset as CSV (header: name, then variables); without path → {csv, datasets}. Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads", + "{path?} write every dataset as CSV (header: name, then one column per variable: `#Name` for a visibility variable, `@Name` for an image variable, and the name alone for a text or graph variable, as dataset.import reads them). Refused when the document has more than 1000 data sets or 256 variables, the most dataset.import reads, or when a variable's header is another variable's name (a visibility variable `Show` next to a text variable `#Show`) → {path, datasets, warning?}; without path → {csv, datasets, warning?}. `warning` names the variables whose header or values make a document without them refuse the file (a % header, a # header whose values aren't true or false); otherwise it names the variables such a document doesn't read back with their kind (text variables whose names start with # or @, graph variables)", has_doc, dataset_export ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 47376d78f1..507c153f8e 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -187,12 +187,66 @@ fn value_to_cell(v: &DataValue) -> String { } } -/// Build the CSV of every dataset (header `name` then variables in definition order). -fn datasets_to_csv(vars: &Variables) -> String { +/// The header cell that [`datasets_to_csv`] writes for `v`, as [`header_variable`] reads it: `#` +/// before a visibility variable's name, `@` before an image variable's name, and the name alone +/// for a text or graph variable. +fn export_header(v: &Variable) -> String { + match v.kind { + VariableKind::Visibility => format!("#{}", v.name), + VariableKind::Image => format!("@{}", v.name), + VariableKind::Text | VariableKind::Graph => v.name.clone(), + } +} + +/// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`] +/// writes, in a document without the variables: the first list names the variables whose header +/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values +/// aren't true or false, a header that names a variable an earlier column named), and the second +/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`, +/// and a graph variable, which no header cell defines). +fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { + const C: &str = "dataset.import"; + let none = BTreeMap::new(); + let mut defined = Vec::new(); + let (mut refused, mut other) = (Vec::new(), Vec::new()); + let mut seen = BTreeSet::new(); + for (i, v) in vars.variables.iter().enumerate() { + let header = export_header(v); + let cell = header.trim(); + // Column 1 holds the dataset names. + let read = if cell.is_empty() { None } else { header_variable(cell, i + 2, &none, &mut defined, C).ok() }; + // The import refuses a header that names a variable an earlier column named. + let Some((name, kind)) = read.filter(|(name, _)| seen.insert(name.clone())) else { + refused.push(v.name.as_str()); + continue; + }; + let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| { + let cell = value_to_cell(val); + cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() + }); + if !cells_read { + refused.push(v.name.as_str()); + } else if name != v.name || kind != v.kind { + other.push(v.name.as_str()); + } + } + (refused, other) +} + +/// Build the CSV of every dataset (header `name` then each variable's [`export_header`] in +/// definition order). Refused when a variable's header is another variable's name, which the +/// import reads as that variable (a visibility variable `Show` next to a text variable `#Show`). +fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result { + let names: BTreeSet<&str> = vars.variables.iter().map(|v| v.name.as_str()).collect(); let mut out = String::from("name"); for v in &vars.variables { + let header = export_header(v); + if header != v.name && names.contains(header.as_str()) { + let (name, other) = (&v.name, &header); + return Err(bad(cmd, format!("the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them"))); + } out.push(','); - out.push_str(&csv_escape(&v.name)); + out.push_str(&csv_escape(&header)); } out.push('\n'); for ds in &vars.datasets { @@ -205,7 +259,7 @@ fn datasets_to_csv(vars: &Variables) -> String { } out.push('\n'); } - out + Ok(out) } /// The variable that a datasets CSV header cell (trimmed, not empty) in 1-based `column` names, @@ -343,7 +397,10 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { Ok(json!({"imported": imported, "updated": updated, "names": names, "defined": new_variables})) } -/// Export every dataset as CSV (`name` then variables). With `path`, write the file; else return `{csv}`. +/// Export every dataset as CSV ([`datasets_to_csv`]). With `path`, write the file; else return +/// `{csv}`. The reply's `warning` names the variables whose column makes a document without them +/// refuse the file, or else the variables it doesn't read back with their kind +/// ([`kinds_a_new_document_loses`]); the app shows it in its status bar. /// A document with more data sets or variables than [`dataset_import`] reads is refused. pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.export"; @@ -358,16 +415,26 @@ pub(super) fn dataset_export(s: &mut Session, p: &Value) -> Result { if st.doc.variables.variables.len() > MAX_CSV_COLS { return Err(bad(C, format!("more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS}"))); } - let csv = datasets_to_csv(&st.doc.variables); + let csv = datasets_to_csv(&st.doc.variables, C)?; if csv.len() > MAX_CSV_BYTES { return Err(bad(C, format!("CSV would be larger than {MAX_CSV_BYTES} bytes"))); } - match str_param(p, "path") { + let mut out = match str_param(p, "path") { Some(path) => { let path = absolute_path(path); write_file(&path, csv.as_bytes())?; - Ok(json!({"path": path, "datasets": st.doc.variables.datasets.len()})) + json!({"path": path, "datasets": st.doc.variables.datasets.len()}) } - None => Ok(json!({"csv": csv, "datasets": st.doc.variables.datasets.len()})), + None => json!({"csv": csv, "datasets": st.doc.variables.datasets.len()}), + }; + let (refused, lost) = kinds_a_new_document_loses(&st.doc.variables); + let list = |vars: &[&str]| vars.iter().map(|n| format!("`{n}`")).collect::>().join(", "); + if !refused.is_empty() { + let names = list(&refused); + out["warning"] = json!(format!("a new document refuses this file because of these variables: {names}")); + } else if !lost.is_empty() { + let names = list(&lost); + out["warning"] = json!(format!("a new document won't read these variables back with their kind: {names}")); } + Ok(out) } diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 1844d9f20d..c54350cc9a 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1521,13 +1521,13 @@ fn datasets_csv_header_prefixes_define_variables() { #[test] fn datasets_csv_exact_names_win_over_prefixes() { let mut s = session(); - for (name, kind) in [("#Shown", "text"), ("@Photo", "visibility"), ("%Chart", "graph"), ("Shown", "visibility")] { + for (name, kind) in [("#Shown", "text"), ("@Photo", "visibility"), ("%Chart", "graph"), ("Shown", "image")] { s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); } - let values = json!({"#Shown": "hello", "@Photo": true, "%Chart": ",Q\nX,3", "Shown": false}); + let values = json!({"#Shown": "hello", "@Photo": true, "%Chart": ",Q\nX,3", "Shown": "s.png"}); s.execute("dataset.new", &json!({"name": "A", "values": values})).unwrap(); let csv = s.execute("dataset.export", &json!({})).unwrap()["csv"].as_str().unwrap().to_string(); - assert!(csv.starts_with("name,#Shown,@Photo,%Chart,Shown\n"), "{csv}"); + assert!(csv.starts_with("name,#Shown,#@Photo,%Chart,@Shown\n"), "{csv}"); s.execute("dataset.delete", &json!({"names": ["A"]})).unwrap(); let imp = s.execute("dataset.import", &json!({"csv": csv})).unwrap(); assert_eq!((imp["imported"].as_u64(), imp["defined"].clone()), (Some(1), json!([]))); @@ -1535,10 +1535,91 @@ fn datasets_csv_exact_names_win_over_prefixes() { assert_eq!(value("#Shown"), Some(vectorcraft_doc::DataValue::Text("hello".into()))); assert_eq!(value("@Photo"), Some(vectorcraft_doc::DataValue::Visible(true))); assert_eq!(value("%Chart"), Some(vectorcraft_doc::DataValue::Graph(",Q\nX,3".into()))); - assert_eq!(value("Shown"), Some(vectorcraft_doc::DataValue::Visible(false))); + assert_eq!(value("Shown"), Some(vectorcraft_doc::DataValue::Image("s.png".into()))); assert_eq!(s.doc().unwrap().doc.variables.variables.len(), 4); } +/// `dataset.export` writes `#` before a visibility variable's header and `@` before an image +/// variable's, so a document without the variables reads the file back with their kinds. The +/// reply's `warning` names the variables it doesn't: a text variable whose name starts with `#`, +/// `@` or `%`, and a graph variable. +#[test] +fn datasets_csv_export_marks_visibility_and_image_columns() { + let mut s = session(); + for (name, kind) in [("Name", "text"), ("Show", "visibility"), ("Photo", "image")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + s.execute("dataset.new", &json!({"name": "A", "values": {"Name": "Ann", "Show": false, "Photo": "a.png"}})).unwrap(); + let out = s.execute("dataset.export", &json!({})).unwrap(); + assert_eq!(out["csv"], "name,Name,#Show,@Photo\nA,Ann,false,a.png\n"); + assert!(out.get("warning").is_none(), "{out}"); + + let mut fresh = session(); + let imp = fresh.execute("dataset.import", &json!({"csv": out["csv"]})).unwrap(); + assert_eq!(imp["defined"], json!(["Name", "Show", "Photo"])); + let listed = fresh.execute("variable.list", &json!({})).unwrap(); + let kinds: Vec<_> = listed["variables"].as_array().unwrap().iter().map(|v| v["kind"].clone()).collect(); + assert_eq!(kinds, [json!("text"), json!("visibility"), json!("image")]); + let value = |var: &str| fresh.doc().unwrap().doc.variables.dataset("A").and_then(|d| d.values.get(var)).cloned(); + assert_eq!(value("Show"), Some(vectorcraft_doc::DataValue::Visible(false))); + assert_eq!(value("Photo"), Some(vectorcraft_doc::DataValue::Image("a.png".into()))); + + for (name, kind) in [("#Tag", "text"), ("Chart", "graph"), ("@Note", "text")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let out = s.execute("dataset.export", &json!({})).unwrap(); + assert_eq!(out["warning"], "a new document won't read these variables back with their kind: `#Tag`, `Chart`, `@Note`"); + assert!(out["csv"].as_str().unwrap().starts_with("name,Name,#Show,@Photo,#Tag,Chart,@Note\n"), "{out}"); +} + +/// The export's `warning` names the variables whose column a document without the variables +/// refuses, so it doesn't import the file: a `%` header, a `#` header whose values aren't true or +/// false, and a header that names a variable an earlier column defined with another kind. A +/// header that names such a variable with its kind is read with that kind, and is listed as one +/// read back with another kind. +#[test] +fn datasets_csv_export_warns_of_headers_a_new_document_refuses() { + let export = |vars: &[(&str, &str)], values: Value| { + let mut s = session(); + for (name, kind) in vars { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + s.execute("dataset.new", &json!({"name": "A", "values": values})).unwrap(); + let out = s.execute("dataset.export", &json!({})).unwrap(); + let refused = session().execute("dataset.import", &json!({"csv": out["csv"]})).is_err(); + (out["warning"].as_str().unwrap_or("").to_string(), refused) + }; + let refuses = |names: &str| format!("a new document refuses this file because of these variables: {names}"); + let loses = |names: &str| format!("a new document won't read these variables back with their kind: {names}"); + + assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (refuses("`%Rate`"), true)); + assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "hello"})), (refuses("`#Tag`"), true)); + assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "yes"})), (loses("`#Tag`"), false)); + assert_eq!(export(&[("#Seen", "text"), ("Seen", "image")], json!({})), (refuses("`Seen`"), true)); + assert_eq!(export(&[("#Seen", "text"), ("Seen", "text")], json!({})), (refuses("`Seen`"), true)); +} + +/// `dataset.export` is refused, naming both variables, when a variable's header is another +/// variable's name, which an import reads as that variable; with `path`, no file is written. +#[test] +fn datasets_csv_export_refuses_a_header_that_names_another_variable() { + let dir = Folder::new("vars-csv-header"); + for (first, second) in + [(("Show", "visibility"), ("#Show", "text")), (("Photo", "image"), ("@Photo", "graph")), (("X", "visibility"), ("#X", "image"))] + { + let mut s = session(); + for (name, kind) in [first, second] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let e = s.execute("dataset.export", &json!({})).unwrap_err().to_string(); + let (name, other) = (first.0, second.0); + assert!(e.contains(&format!("for `{name}` would read back as the variable `{other}`")), "{e}"); + let out = dir.file("sets.csv"); + assert!(s.execute("dataset.export", &json!({"path": out})).is_err()); + assert!(!std::path::Path::new(&out).exists(), "{out}"); + } +} + /// A `%` header cell that isn't a variable's name (graph data files) is refused with its column, /// and the import defines nothing. #[test] @@ -1621,7 +1702,7 @@ fn datasets_csv_round_trips_and_rejects_bad_input() { let exported = s.execute("dataset.export", &json!({})).unwrap(); let csv = exported["csv"].as_str().unwrap().to_string(); - assert!(csv.starts_with("name,Name,Show,Photo\n"), "{csv}"); + assert!(csv.starts_with("name,Name,#Show,@Photo\n"), "{csv}"); assert!(csv.contains("Alice") && csv.contains("Bob") && csv.contains("false"), "{csv}"); // Clear rows, import again, apply B. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f3f6cbfbb6..367da9cb33 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4348,6 +4348,9 @@ axis Both И двете @msg unsupported: {0} не се поддържа: {0} @msg variables are locked променливите са заключени @msg variables that aren't text were left out: {kinds} променливите, които не са текстови, бяха пропуснати: {kinds} +@msg a new document won't read these variables back with their kind: {names} нов документ няма да прочете тези променливи обратно с техния вид: {names} +@msg a new document refuses this file because of these variables: {names} нов документ отказва този файл заради тези променливи: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заглавието `{header}` за `{name}` ще бъде прочетено като променливата `{other}`: преименувайте едната от тях @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файловете от версия {0} не могат да бъдат компресирани: само версия {COMPRESSED_SINCE} и по-нови отварят компресирани файлове @msg width and height are at least 1 pixel ширината и височината са най-малко 1 пиксел @msg workspace name can't be empty името на работното пространство не може да бъде празно diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d7efa9c0e7..035a87d75c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4747,6 +4747,9 @@ imageTrace Outline Obris @msg unsupported: {0} nepodržano: {0} @msg variables are locked varijable su zaključane @msg variables that aren't text were left out: {kinds} izostavljene su varijable koje nisu tekst: {kinds} +@msg a new document won't read these variables back with their kind: {names} novi dokument neće ponovo učitati ove varijable s njihovom vrstom: {names} +@msg a new document refuses this file because of these variables: {names} novi dokument odbija ovu datoteku zbog ovih varijabli: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them zaglavlje `{header}` za `{name}` učitalo bi se kao varijabla `{other}`: preimenujte jednu od njih @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` i `options.{key}: {inner}` se ne slažu: navedite opciju jednom @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files datoteke verzije {0} ne mogu se komprimirati: komprimirane datoteke otvaraju samo verzija {COMPRESSED_SINCE} i novije @msg width and height are at least 1 pixel širina i visina su najmanje 1 piksel diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 205991cbce..dee5c31384 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5604,6 +5604,9 @@ digits Malayalam Malaiàlam @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} més de {MAX_CSV_ROWS} conjunts de dades: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} més de {MAX_CSV_COLS} variables: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} +@msg a new document won't read these variables back with their kind: {names} un document nou no tornarà a llegir aquestes variables amb el seu tipus: {names} +@msg a new document refuses this file because of these variables: {names} un document nou rebutja aquest fitxer a causa d'aquestes variables: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them la capçalera `{header}` de `{name}` es tornaria a llegir com la variable `{other}`: canvieu el nom d’una de les dues @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft no cerca a les carpetes d’altres aplicacions ni del sistema: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft no cerca a la carpeta Shared o Public d’Usuaris: {path} @msg VectorCraft failed to start: {e} VectorCraft no s’ha pogut iniciar: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a6d23ba3cd..9b0218d5ca 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4791,6 +4791,9 @@ imageTrace Outline Obrys @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} více než {MAX_CSV_ROWS} sad dat: Importovat sady dat načte nejvýše {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} více než {MAX_CSV_COLS} proměnných: Importovat sady dat načte nejvýše {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} proměnné, které nejsou textové, byly vynechány: {kinds} +@msg a new document won't read these variables back with their kind: {names} nový dokument tyto proměnné nenačte zpět s jejich druhem: {names} +@msg a new document refuses this file because of these variables: {names} nový dokument tento soubor kvůli těmto proměnným odmítne: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them záhlaví `{header}` pro `{name}` by se načetlo jako proměnná `{other}`: jednu z nich přejmenujte @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` a `options.{key}: {inner}` si odporují: zadejte volbu jen jednou @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files soubory verze {0} nelze komprimovat: komprimované soubory otevírá až verze {COMPRESSED_SINCE} a novější @msg width and height are at least 1 pixel šířka i výška jsou alespoň 1 obrazový bod diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5a23913424..5cfe139d8b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5138,6 +5138,9 @@ mark-style Japanese Japansk Export Data Sets… Eksportér datasæt… Load Variable Library… Indlæs variabelbibliotek… @msg variables that aren't text were left out: {kinds} variabler, der ikke er tekst, blev udeladt: {kinds} +@msg a new document won't read these variables back with their kind: {names} et nyt dokument læser ikke disse variabler tilbage med deres type: {names} +@msg a new document refuses this file because of these variables: {names} et nyt dokument afviser denne fil på grund af disse variabler: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them overskriften `{header}` for `{name}` ville blive læst som variablen `{other}`: omdøb en af dem Make Graph Dynamic Gør diagram dynamisk Batch… Batch… Source Folder: Kildemappe: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1433e9d1cb..d23d59d4ec 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4400,6 +4400,9 @@ theme Appearance Erscheinungsbild @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mehr als {MAX_CSV_ROWS} Datensätze: „Datensätze importieren“ liest höchstens {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mehr als {MAX_CSV_COLS} Variablen: „Datensätze importieren“ liest höchstens {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} die Variablen, die kein Text sind, wurden ausgelassen: {kinds} +@msg a new document won't read these variables back with their kind: {names} ein neues Dokument liest diese Variablen nicht mit ihrer Art zurück: {names} +@msg a new document refuses this file because of these variables: {names} ein neues Dokument lehnt diese Datei wegen dieser Variablen ab: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them die Kopfzeile `{header}` für `{name}` würde als die Variable `{other}` gelesen: Benennen Sie eine der beiden um @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` und `options.{key}: {inner}` widersprechen sich: Option nur einmal angeben @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files Dateien der Version {0} können nicht komprimiert werden: Erst Version {COMPRESSED_SINCE} und neuer öffnen komprimierte Dateien @msg width and height are at least 1 pixel Breite und Höhe betragen mindestens 1 Pixel diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f28611c541..e2a1118481 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4433,6 +4433,9 @@ digits Malayalam Μαλαγιάλαμ @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} περισσότερα από {MAX_CSV_ROWS} σύνολα δεδομένων: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} περισσότερες από {MAX_CSV_COLS} μεταβλητές: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} οι μεταβλητές που δεν είναι κειμένου παραλείφθηκαν: {kinds} +@msg a new document won't read these variables back with their kind: {names} ένα νέο έγγραφο δεν θα διαβάσει ξανά αυτές τις μεταβλητές με το είδος τους: {names} +@msg a new document refuses this file because of these variables: {names} ένα νέο έγγραφο απορρίπτει αυτό το αρχείο λόγω αυτών των μεταβλητών: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them η κεφαλίδα `{header}` για το `{name}` θα διαβαζόταν ως η μεταβλητή `{other}`: μετονομάστε μία από τις δύο @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once τα `{key}: {top}` και `options.{key}: {inner}` διαφέρουν: δώστε την επιλογή μόνο μία φορά @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files τα αρχεία έκδοσης {0} δεν μπορούν να συμπιεστούν: μόνο η έκδοση {COMPRESSED_SINCE} και νεότερες ανοίγουν συμπιεσμένα αρχεία @msg width and height are at least 1 pixel το πλάτος και το ύψος πρέπει να είναι τουλάχιστον 1 εικονοστοιχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index dbd5dfb238..9e63d5266b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4485,6 +4485,9 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} más de {MAX_CSV_ROWS} conjuntos de datos: Importar conjuntos de datos lee como máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} más de {MAX_CSV_COLS} variables: Importar conjuntos de datos lee como máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} se omitieron las variables que no son de texto: {kinds} +@msg a new document won't read these variables back with their kind: {names} un documento nuevo no volverá a leer estas variables con su tipo: {names} +@msg a new document refuses this file because of these variables: {names} un documento nuevo rechaza este archivo por estas variables: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them el encabezado `{header}` de `{name}` se leería como la variable `{other}`: cambie el nombre de una de las dos @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` y `options.{key}: {inner}` no coinciden: indique la opción una sola vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files los archivos de la versión {0} no se pueden comprimir: solo la versión {COMPRESSED_SINCE} y posteriores abren archivos comprimidos @msg width and height are at least 1 pixel el ancho y el alto son de al menos 1 píxel diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e232c972a8..13f2d85be4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4693,6 +4693,9 @@ imageTrace Outline Ääriviiva @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} yli {MAX_CSV_ROWS} tietojoukkoa: Tuo tietojoukot lukee enintään {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} yli {MAX_CSV_COLS} muuttujaa: Tuo tietojoukot lukee enintään {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} muut kuin tekstimuuttujat jätettiin pois: {kinds} +@msg a new document won't read these variables back with their kind: {names} uusi asiakirja ei lue näitä muuttujia takaisin niiden lajin mukaisina: {names} +@msg a new document refuses this file because of these variables: {names} uusi asiakirja hylkää tämän tiedoston näiden muuttujien vuoksi: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them muuttujan `{name}` otsikko `{header}` luettaisiin muuttujaksi `{other}`: nimeä toinen niistä uudelleen @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` ja `options.{key}: {inner}` ovat ristiriidassa: anna asetus vain kerran @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files version {0} tiedostoja ei voi pakata: pakattuja tiedostoja voi avata vain versiosta {COMPRESSED_SINCE} alkaen @msg width and height are at least 1 pixel leveys ja korkeus ovat vähintään 1 pikseli diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 789e40c815..213bdb3d39 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4475,6 +4475,9 @@ axis Both Les deux @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ({kinds}) ont été ignorées +@msg a new document won't read these variables back with their kind: {names} un nouveau document ne relira pas ces variables avec leur type : {names} +@msg a new document refuses this file because of these variables: {names} un nouveau document refuse ce fichier à cause de ces variables : {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’en-tête `{header}` de `{name}` serait relu comme la variable `{other}` : renommez l’une des deux @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` et `options.{key}: {inner}` ne concordent pas. Indiquez l’option une seule fois @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files les fichiers de version {0} ne peuvent pas être compressés : seules les versions {COMPRESSED_SINCE} et ultérieures ouvrent les fichiers compressés @msg width and height are at least 1 pixel la largeur et la hauteur valent au moins 1 pixel diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 76dc225e81..5396a64557 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5255,6 +5255,9 @@ imageTrace Outline Körvonal @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} több mint {MAX_CSV_ROWS} adatkészlet: az Adatkészletek importálása legfeljebb {MAX_CSV_ROWS} adatkészletet olvas be @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} több mint {MAX_CSV_COLS} változó: az Adatkészletek importálása legfeljebb {MAX_CSV_COLS} változót olvas be @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} +@msg a new document won't read these variables back with their kind: {names} egy új dokumentum nem a fajtájukkal olvassa vissza ezeket a változókat: {names} +@msg a new document refuses this file because of these variables: {names} egy új dokumentum ezen változók miatt elutasítja ezt a fájlt: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them a(z) `{name}` változó `{header}` fejléce a(z) `{other}` változóként olvasódna vissza: nevezze át az egyiket @msg VectorCraft doesn't search other apps' or the system's folders: {path} a VectorCraft nem keres más alkalmazások és a rendszer mappáiban: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} a VectorCraft nem keres a Users alatti Shared és Public mappában: {path} @msg VectorCraft failed to start: {e} A VectorCraft nem tudott elindulni: {e} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 89633ae991..1ae04500b4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5138,6 +5138,9 @@ mark-style Japanese Jepang Export Data Sets… Ekspor himpunan data… Load Variable Library… Muat pustaka variabel… @msg variables that aren't text were left out: {kinds} variabel yang bukan teks dihilangkan: {kinds} +@msg a new document won't read these variables back with their kind: {names} dokumen baru tidak akan membaca kembali variabel ini dengan jenisnya: {names} +@msg a new document refuses this file because of these variables: {names} dokumen baru menolak file ini karena variabel berikut: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them header `{header}` untuk `{name}` akan terbaca sebagai variabel `{other}`: ganti nama salah satunya Make Graph Dynamic Jadikan grafik dinamis Batch… Batch… Source Folder: Folder sumber: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ad25ad87c4..b34a730a75 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4526,6 +4526,9 @@ axis Both Entrambi @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} più di {MAX_CSV_ROWS} set di dati: Importa set di dati ne legge al massimo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} più di {MAX_CSV_COLS} variabili: Importa set di dati ne legge al massimo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} le variabili che non sono di testo sono state escluse: {kinds} +@msg a new document won't read these variables back with their kind: {names} un nuovo documento non rileggerà queste variabili con il loro tipo: {names} +@msg a new document refuses this file because of these variables: {names} un nuovo documento rifiuta questo file a causa di queste variabili: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’intestazione `{header}` di `{name}` verrebbe riletta come la variabile `{other}`: rinomina una delle due @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` non coincidono: indicare l'opzione una sola volta @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files i file della versione {0} non possono essere compressi: solo la versione {COMPRESSED_SINCE} e successive aprono file compressi @msg width and height are at least 1 pixel larghezza e altezza sono di almeno 1 pixel diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 804186dd67..e7b1a1bf34 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4079,6 +4079,9 @@ swatch Bright Violet ビビッドバイオレット @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} データセットが {MAX_CSV_ROWS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_ROWS} 個までです @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 変数が {MAX_CSV_COLS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_COLS} 個までです @msg variables that aren't text were left out: {kinds} テキスト以外の変数は除外されました: {kinds} +@msg a new document won't read these variables back with their kind: {names} 新しいドキュメントでは、これらの変数は元の種類で読み込まれません: {names} +@msg a new document refuses this file because of these variables: {names} 新しいドキュメントは、これらの変数のためにこのファイルを拒否します: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` の見出し `{header}` は変数 `{other}` として読み込まれます: どちらかの名前を変更してください @msg guides are locked ガイドがロックされています @msg handle must be in or out handle には in または out を指定してください @msg no saved selection recalled 保存した選択範囲を呼び出していません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 250e0f384e..2dafb7cebb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5424,6 +5424,9 @@ imageTrace Outline კონტური @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS}-ზე მეტი მონაცემთა ნაკრები: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_ROWS}-ს @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS}-ზე მეტი ცვლადი: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_COLS}-ს @msg variables that aren't text were left out: {kinds} ცვლადები, რომლებიც ტექსტი არ არის, გამოტოვებულია: {kinds} +@msg a new document won't read these variables back with their kind: {names} ახალი დოკუმენტი ამ ცვლადებს მათი ტიპით ვერ წაიკითხავს: {names} +@msg a new document refuses this file because of these variables: {names} ახალი დოკუმენტი ამ ფაილს ამ ცვლადების გამო უარყოფს: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`-ის სათაური `{header}` წაიკითხება როგორც ცვლადი `{other}`: გადაარქვით სახელი ერთ-ერთს @msg x and y must be finite x და y სასრული უნდა იყოს @msg {id} opens another app: only the person at the keyboard can run it {id} სხვა აპს ხსნის: მისი გაშვება მხოლოდ კლავიატურასთან მყოფ ადამიანს შეუძლია @msg “{name}” is not a file „{name}“ ფაილი არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 3ee9cb9d4c..2cb947582f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4006,6 +4006,9 @@ theme Appearance 외관 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 데이터 세트가 {MAX_CSV_ROWS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_ROWS}개를 읽습니다 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 변수가 {MAX_CSV_COLS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_COLS}개를 읽습니다 @msg variables that aren't text were left out: {kinds} 텍스트가 아닌 변수는 제외되었습니다: {kinds} +@msg a new document won't read these variables back with their kind: {names} 새 문서는 이 변수들을 원래 종류로 다시 읽지 않습니다: {names} +@msg a new document refuses this file because of these variables: {names} 새 문서는 이 변수들 때문에 이 파일을 거부합니다: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`의 머리글 `{header}`은(는) 변수 `{other}`(으)로 다시 읽힙니다: 둘 중 하나의 이름을 바꾸십시오 @msg guides are locked 안내선이 잠겨 있습니다 @msg handle must be in or out handle은 in 또는 out이어야 합니다 @msg no saved selection recalled 불러온 저장된 선택 영역이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3448536832..11e489e562 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5493,6 +5493,9 @@ swatch Bright Violet Felviolet @msg the spine has no segments de as heeft geen segmenten @msg variables are locked variabelen zijn vergrendeld @msg variables that aren't text were left out: {kinds} variabelen die geen tekst zijn, zijn weggelaten: {kinds} +@msg a new document won't read these variables back with their kind: {names} een nieuw document leest deze variabelen niet terug met hun soort: {names} +@msg a new document refuses this file because of these variables: {names} een nieuw document weigert dit bestand vanwege deze variabelen: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them de kop `{header}` voor `{name}` zou worden gelezen als de variabele `{other}`: wijzig de naam van een van beide @msg x and y must be finite x en y moeten eindig zijn @msg Persistent libraries not found: {files} Permanente bibliotheken niet gevonden: {files} @msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` is geen bibliotheekpaneel (zie window.swatchLibrary) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5830a1b6ab..c042bc487f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4617,6 +4617,9 @@ imageTrace Outline Kontur @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} więcej niż {MAX_CSV_ROWS} zestawów danych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} więcej niż {MAX_CSV_COLS} zmiennych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} pominięto zmienne, które nie są tekstowe: {kinds} +@msg a new document won't read these variables back with their kind: {names} nowy dokument nie odczyta tych zmiennych z ich rodzajem: {names} +@msg a new document refuses this file because of these variables: {names} nowy dokument odrzuca ten plik z powodu tych zmiennych: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them nagłówek `{header}` dla `{name}` zostałby odczytany jako zmienna `{other}`: zmień nazwę jednej z nich @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` i `options.{key}: {inner}` są sprzeczne: podaj opcję tylko raz @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files plików w wersji {0} nie można kompresować: skompresowane pliki otwierają tylko wersje {COMPRESSED_SINCE} i nowsze @msg width and height are at least 1 pixel szerokość i wysokość muszą wynosić co najmniej 1 piksel diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 00c6192224..8f86b811cb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4057,6 +4057,9 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mais de {MAX_CSV_ROWS} conjuntos de dados: Importar Conjuntos de Dados lê no máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mais de {MAX_CSV_COLS} variáveis: Importar Conjuntos de Dados lê no máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} as variáveis que não são de texto foram omitidas: {kinds} +@msg a new document won't read these variables back with their kind: {names} um novo documento não lerá essas variáveis de volta com o tipo delas: {names} +@msg a new document refuses this file because of these variables: {names} um novo documento recusa este arquivo por causa destas variáveis: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them o cabeçalho `{header}` de `{name}` seria lido como a variável `{other}`: renomeie uma delas @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` e `options.{key}: {inner}` não coincidem: informe a opção uma só vez @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files arquivos da versão {0} não podem ser compactados: somente a versão {COMPRESSED_SINCE} e posteriores abrem arquivos compactados @msg width and height are at least 1 pixel largura e altura têm pelo menos 1 pixel diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 50d1ca1bdd..c28d4e979c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4521,6 +4521,9 @@ axis Both Оба @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} больше {MAX_CSV_ROWS} наборов данных: «Импортировать наборы данных» читает не более {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} больше {MAX_CSV_COLS} переменных: «Импортировать наборы данных» читает не более {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} переменные, которые не являются текстовыми, пропущены: {kinds} +@msg a new document won't read these variables back with their kind: {names} новый документ не прочитает эти переменные обратно с их типом: {names} +@msg a new document refuses this file because of these variables: {names} новый документ отклоняет этот файл из-за этих переменных: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` будет прочитан как переменная `{other}`: переименуйте одну из них @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` и `options.{key}: {inner}` противоречат друг другу: укажите параметр только один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файлы версии {0} не могут быть сжаты: только версия {COMPRESSED_SINCE} и новее открывают сжатые файлы @msg width and height are at least 1 pixel ширина и высота должны быть не менее 1 пикселя diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8ca7a39271..a42ba37e24 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4384,6 +4384,9 @@ axis Both Båda @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} fler än {MAX_CSV_ROWS} datauppsättningar: Importera datauppsättningar läser högst {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} fler än {MAX_CSV_COLS} variabler: Importera datauppsättningar läser högst {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} variabler som inte är text utelämnades: {kinds} +@msg a new document won't read these variables back with their kind: {names} ett nytt dokument läser inte tillbaka dessa variabler med deras typ: {names} +@msg a new document refuses this file because of these variables: {names} ett nytt dokument avvisar den här filen på grund av dessa variabler: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them rubriken `{header}` för `{name}` skulle läsas som variabeln `{other}`: byt namn på en av dem @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` och `options.{key}: {inner}` stämmer inte överens: ange alternativet bara en gång @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files filer i version {0} kan inte komprimeras: endast version {COMPRESSED_SINCE} och senare kan öppna komprimerade filer @msg width and height are at least 1 pixel bredd och höjd är minst 1 pixel diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c893d81f38..f6f841f6cb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5523,6 +5523,9 @@ theme Appearance Görünüm @msg an image has no pixels and was left out piksel içermeyen bir görüntü dışarıda bırakıldı @msg thumbnail: no page {n} (the file has 1) thumbnail: {n}. sayfa yok (dosyada 1 sayfa var) @msg variables that aren't text were left out: {kinds} metin olmayan değişkenler dışarıda bırakıldı: {kinds} +@msg a new document won't read these variables back with their kind: {names} yeni bir belge bu değişkenleri türleriyle geri okumaz: {names} +@msg a new document refuses this file because of these variables: {names} yeni bir belge bu değişkenler nedeniyle bu dosyayı reddeder: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{header}` başlığı `{other}` değişkeni olarak okunur: birini yeniden adlandırın Collapse Panel Group Panel Grubunu Daralt @msg panel is not in a dock group panel bir yuva grubunda değil @msg only a dock group above or below others collapses, not one beside another yalnızca diğerlerinin üstünde veya altındaki bir yuva grubu daraltılabilir, yanındaki değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2676d107e6..0685758bfa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4510,6 +4510,9 @@ axis Both Обидві @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} більше ніж {MAX_CSV_ROWS} наборів даних: «Імпортувати набори даних» читає не більше {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} більше ніж {MAX_CSV_COLS} змінних: «Імпортувати набори даних» читає не більше {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} змінні, що не є текстовими, пропущено: {kinds} +@msg a new document won't read these variables back with their kind: {names} новий документ не прочитає ці змінні назад з їхнім видом: {names} +@msg a new document refuses this file because of these variables: {names} новий документ відхиляє цей файл через ці змінні: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` буде прочитано як змінну `{other}`: перейменуйте одну з них @msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` і `options.{key}: {inner}` суперечать одне одному: вкажіть параметр лише один раз @msg version {0} files can't be compressed: only version {COMPRESSED_SINCE} and later open compressed files файли версії {0} не можуть бути стиснуті: тільки версія {COMPRESSED_SINCE} і новіші відкривають стислі файли @msg width and height are at least 1 pixel ширина та висота повинні бути не менше 1 пікселя diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 42de855e0c..75e0f7af4e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4917,6 +4917,9 @@ theme Appearance Giao diện @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} hơn {MAX_CSV_ROWS} tập dữ liệu: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} hơn {MAX_CSV_COLS} biến số: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} +@msg a new document won't read these variables back with their kind: {names} tài liệu mới sẽ không đọc lại các biến số này đúng loại: {names} +@msg a new document refuses this file because of these variables: {names} tài liệu mới sẽ từ chối tệp này vì các biến số sau: {names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them tiêu đề `{header}` của `{name}` sẽ được đọc thành biến số `{other}`: hãy đổi tên một trong hai @msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft không tìm kiếm trong thư mục của ứng dụng khác hoặc hệ thống: {path} @msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft không tìm kiếm thư mục Shared hoặc Public trong Users: {path} @msg VectorCraft failed to start: {e} VectorCraft khởi động thất bại: {e} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 53a2e2847d..815667fb9b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3474,6 +3474,9 @@ digits Malayalam 马拉雅拉姆数字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 数据集超过 {MAX_CSV_ROWS} 个:“导入数据集”最多读取 {MAX_CSV_ROWS} 个 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 变量超过 {MAX_CSV_COLS} 个:“导入数据集”最多读取 {MAX_CSV_COLS} 个 @msg variables that aren't text were left out: {kinds} 已省略非文本变量:{kinds} +@msg a new document won't read these variables back with their kind: {names} 新文档不会按原类型读回这些变量:{names} +@msg a new document refuses this file because of these variables: {names} 新文档会因这些变量而拒绝此文件:{names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的标题 `{header}` 会被读作变量 `{other}`:请重命名其中一个 List Variables 列出变量 Bind Variable 绑定变量 Unbind Variable 解除变量绑定 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 0e9c6b5f29..27ae8fed5c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4466,6 +4466,9 @@ digits Malayalam 馬來亞拉姆數字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 資料集超過 {MAX_CSV_ROWS} 個:「匯入資料集」最多讀取 {MAX_CSV_ROWS} 個 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 變數超過 {MAX_CSV_COLS} 個:「匯入資料集」最多讀取 {MAX_CSV_COLS} 個 @msg variables that aren't text were left out: {kinds} 已略過非文字變數:{kinds} +@msg a new document won't read these variables back with their kind: {names} 新文件不會以原類型讀回這些變數:{names} +@msg a new document refuses this file because of these variables: {names} 新文件會因這些變數而拒絕此檔案:{names} +@msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的標題 `{header}` 會被讀作變數 `{other}`:請重新命名其中一個 List Variables 列出變數 Bind Variable 綁定變數 Unbind Variable 解除變數綁定 diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 1f7a90598e..e45e618acf 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -489,6 +489,43 @@ mod tests { } } + /// Export Data Sets…'s warnings about variables a new document doesn't read back with their + /// kind and about variables that make it refuse the file show in the status bar, and so does + /// its refusal of a header that is another variable's name; all three are translated in every + /// language but English. + #[test] + fn the_export_data_sets_warning_shows_in_the_status_bar() { + use crate::i18n::{Lang, message}; + let mut app = app_with_data(); + let dir = std::env::temp_dir().join(format!("vc-export-warning-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("sets.csv"); + app.run("variable.define", json!({"name": "#Tag", "kind": "text"})).unwrap(); + app.run("dataset.export", json!({"path": path})).unwrap(); + assert_eq!(app.ui.status, "a new document won't read these variables back with their kind: `#Tag`"); + let warning = app.ui.status.clone(); + app.run("variable.define", json!({"name": "%Rate", "kind": "text"})).unwrap(); + app.run("dataset.export", json!({"path": path})).unwrap(); + assert_eq!(app.ui.status, "a new document refuses this file because of these variables: `%Rate`"); + let refuses = app.ui.status.clone(); + app.run("variable.delete", json!({"names": ["%Rate"]})).unwrap(); + app.run("variable.define", json!({"name": "Tag", "kind": "visibility"})).unwrap(); + assert!(app.run("dataset.export", json!({"path": path})).is_err()); + let refused = app.ui.status.clone(); + assert!(refused.contains("would read back as the variable `#Tag`"), "{refused}"); + let _ = std::fs::remove_dir_all(&dir); + let langs: Vec = Lang::all().filter(|l| l.code() != "en").collect(); + assert!(langs.len() >= 23, "{} languages", langs.len()); + for l in langs { + let shown = message(l, &warning); + assert!(!shown.contains("won't read") && shown.contains("`#Tag`"), "{}: {shown}", l.code()); + let shown = message(l, &refuses); + assert!(!shown.contains("refuses") && shown.contains("`%Rate`"), "{}: {shown}", l.code()); + let shown = message(l, &refused); + assert!(!shown.contains("would read back") && shown.contains("`#Tag`") && shown.contains("`Tag`"), "{}: {shown}", l.code()); + } + } + /// What the panel acts on is the highlight, and only while it names a variable: a stale one /// (deleted elsewhere, undone) highlights nothing, so Delete and Options… stay disabled. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f98195ed33..55d6d44d78 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1646,7 +1646,13 @@ already walks Image Trace. Short agent entry points: first free names `Data Set 1`, `Data Set 2` and so on. An import error about a row's values or name gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without - a prefix defines a text variable. A prefixed cell whose name is already a variable of the prefix's kind names it; + a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image + variable's as `@Photo`, and a text or graph variable's as its name alone. Its reply's `warning` names the variables + whose header or values make an import into a document without them refuse the file (a `%` header, a `#` header + whose values aren't true or false). Otherwise it names the variables that such an import does not read back with + their kind: text variables whose names start with `#` or `@`, and graph variables. Export is refused, naming both variables, when a variable's header is + another variable's name (a visibility variable `Show` next to a text variable `#Show`). A prefixed cell whose name + is already a variable of the prefix's kind names it; one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph data files) is refused, and so are two cells that name one variable (`City` twice, or `Shown` and `#Shown`). The reply's `defined` lists the variables the import defined. While the variables are From 664fe8a12b556afe791a9a318b75480a1a3bd574 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 08:56:52 -0800 Subject: [PATCH 027/189] .ai import: Stylize effects open with their saved settings An object whose art style holds Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble now opens as itself with those effects live, in their order. Feather is read under the name and key the files use (`Adobe Fuzzy Mask`, `Radius`). Each setting is read only when it is written as its kind (`/Int`, `/Real`, a fill style for a color) with a value in range. An unknown key or choice, a missing setting, or a Scribble with a color of its own keeps the drawn look, where the reader used to cast, clamp or default the value. --- crates/engine/tests/import_fuzz.rs | 23 +++ crates/eps/src/import/ai/style.rs | 234 ++++++++++++++++++---- crates/eps/src/import/ai/style/tests.rs | 255 ++++++++++++++++++------ crates/eps/src/import/ai/tests.rs | 10 +- docs/file-format-parity.md | 4 + docs/target-app-parity.md | 2 + 6 files changed, 432 insertions(+), 96 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 7ae7b1d634..d24f69d00f 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3401,6 +3401,29 @@ fn arb_ai_token() -> impl Strategy { "(Fill Style Filter) 0 0 /Filter ,", "(Adobe Outer Glow) 1 0 /Filter ,", "(Adobe Drop Shadow) 1 0 /Filter ,", + "(Adobe Inner Glow) 1 0 /Filter ,", + "(Adobe Fuzzy Mask) 1 0 /Filter ,", + "(Adobe Round Corners) 1 0 /Filter ,", + "(Adobe Scribble Fill) 1 0 /Filter ,", + "(Chain Style Filter) 0 0 /Filter ,", + "/Dictionary : /NotRecorded ,", + "; /Dict ;", + "2.5 /Int (blnd) ,", + "99 /Int (csrc) ,", + "1e308 /Int (gtyp) ,", + "1 /Int (gtyp) ,", + "-13 /Real (vert) ,", + "14 /Real (Radius) ,", + "-1e308 /Real (radius) ,", + "67 /Real (Angle) ,", + "0.17 /Real (Scribbliness) ,", + "1e308 /Real (Spacing) ,", + "(x) /String (note) ,", + "1 /Bool (usePSLBlur) ,", + "16 /Int (Adobe Effect Expand Before Version) ,", + "/FillStyle : 0 O\n0 0 0 0 1 0 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,", + "/FillStyle : 0 O\nBb\n2 (G) 0 0 0 1 1 0 0 1 0 0 Bg\n0 BB\n/Def ;\n (gclr) ,", + "(sclr) ,", "1 /Visible ,", "2 /FillOrStroke ,", "1 /Bool (BSDashAdj) ,", diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index ede1ae8e93..20950c9657 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -48,8 +48,12 @@ use super::obj::V; use super::paint; const GLOW: &str = "Adobe Outer Glow"; // brand-ok: the filter's name in the files -const FEATHER: &str = "Adobe Feather"; // brand-ok: the filter's name in the files +const INNER_GLOW: &str = "Adobe Inner Glow"; // brand-ok: the filter's name in the files +const FEATHER: &str = "Adobe Fuzzy Mask"; // brand-ok: the filter's name in the files const SHADOW: &str = "Adobe Drop Shadow"; // brand-ok: the filter's name in the files +const ROUND_CORNERS: &str = "Adobe Round Corners"; // brand-ok: the filter's name in the files +const SCRIBBLE: &str = "Adobe Scribble Fill"; // brand-ok: the filter's name in the files +const EXPAND_VERSION: &str = "Adobe Effect Expand Before Version"; // brand-ok: the key's name in the files const DEFORM: &str = "Adobe Deform"; // brand-ok: the filter's name in the files const OFFSET: &str = "Adobe Offset Path"; // brand-ok: the filter's name in the files const TRANSFORM: &str = "Adobe Transform"; // brand-ok: the filter's name in the files @@ -94,8 +98,8 @@ pub(super) struct ArtStyle { /// The style reads as [`Self::items`] and [`Self::effects`]. pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with - /// no transparency or effects of their own, and only Outer Glow, Feather and Drop Shadow on the - /// object: what any object is read with. Type takes the other plain styles too (its drawn look + /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, + /// Feather, Round Corners and Scribble on the object: what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, /// Its fills and strokes, bottom first. @@ -148,6 +152,17 @@ impl Default for ItemLook { } } +/// How a filter's dictionary writes an entry: `value /Int (key) ,`, `/Real`, `/Bool`, a fill's +/// style (`/FillStyle : … /Def ; (key) ,`), or anything else. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Int, + Real, + Bool, + Fill, + Other, +} + #[derive(Debug)] struct Filter { name: String, @@ -156,6 +171,8 @@ struct Filter { parent: Option, compound: bool, params: HashMap, + /// How each key of its dictionary is written. + kinds: HashMap, /// Its dictionary's arrays (`/Array : v /Real , … ; (key) ,`), by key. arrays: HashMap>, fill: Option, @@ -184,6 +201,7 @@ impl Default for Filter { parent: None, compound: false, params: HashMap::new(), + kinds: HashMap::new(), arrays: HashMap::new(), fill: None, stroke: None, @@ -223,6 +241,10 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { }; let mut array: Option> = None; let mut dict_array: Option> = None; + // A paint style being read as a dictionary entry: its key follows its `/Def ;`. + let mut style_entry: Option = None; + // A name of a basic filter's that may be an entry's type, with the string that follows it. + let mut other_entry: Option> = None; let mut lex = Lexer::new(data); while let Some(t) = lex.next_token() { if let (Some(a), Tok::Num(v)) = (array.as_mut(), &t.tok) { @@ -231,14 +253,21 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { } match t.tok { Tok::Num(v) => operands.push(V::Num(v)), - Tok::Str(s) | Tok::Hex(s) => operands.push(V::Str(s)), + Tok::Str(s) | Tok::Hex(s) => { + if let Some(key @ None) = other_entry.as_mut() { + *key = Some(String::from_utf8_lossy(&s).into_owned()); + } + operands.push(V::Str(s)); + } Tok::Name(n) => match n { b"KnownStyle" => { finish(name.take(), &mut filters); operands.clear(); open.clear(); - (pending, in_basic) = (None, false); + (pending, in_basic, style_entry, other_entry) = (None, false, None, None); } + b"FillStyle" => style_entry = Some(Kind::Fill), + b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other), b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(V::text), b"CompoundFilter" => pending = Some(true), b"BasicFilter" => pending = Some(false), @@ -271,17 +300,31 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { a.extend(value); continue; } + let kind = match n { + b"Int" => Kind::Int, + b"Real" => Kind::Real, + _ => Kind::Bool, + }; // The key follows: `value /Real (key) ,`. - if let (Some(value), Some(Tok::Str(key))) = (value, lex.next_token().map(|t| t.tok)) + if let Some(Tok::Str(key)) = lex.next_token().map(|t| t.tok) && let Some(f) = filters.last_mut() { - f.params.insert(String::from_utf8_lossy(&key).into_owned(), value); + let key = String::from_utf8_lossy(&key).into_owned(); + match value { + Some(value) => f.params.insert(key.clone(), value), + None => f.params.remove(&key), + }; + f.kinds.insert(key, kind); } continue; } + // Perhaps an entry of another type (`(text) /String (key) ,`): its key, if any, is + // the string before the `,`. + _ if in_basic => other_entry = Some(None), _ => {} }, Tok::Word(w) => { + let entry = other_entry.take().flatten(); let op = std::str::from_utf8(w).unwrap_or_default(); if op == "[" { array = Some(vec![]); @@ -304,6 +347,15 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { if op == ";" && !in_basic { open.pop(); } + if op == "," { + let key = match style_entry.take() { + Some(kind) => operands.iter().rev().find_map(V::text).map(|k| (k, kind)), + None => entry.map(|k| (k, Kind::Other)), + }; + if let (Some((key, kind)), Some(f)) = (key, filters.last_mut()) { + f.kinds.insert(key, kind); + } + } if let Some(f) = filters.last_mut() { paint_op(f, op, &operands); } @@ -428,39 +480,144 @@ fn width_profile(arrays: &HashMap>) -> Option { (!uniform).then_some(WidthProfile { points }) } +/// A Stylize effect's dictionary, read only as it is written: each setting a key of the kind it +/// names, with a finite value in the effect's range. +struct Settings<'a>(&'a Filter); + +impl Settings<'_> { + /// Every key is one of `known`, or one of `fixed` holding the value it names. + /// The choices (`blnd`, `csrc`, `gtyp`) are written as `/Int`, the colors as fill styles and + /// the other settings as `/Real`. + fn only(&self, known: &[&str], fixed: &[(&str, Kind, f64)]) -> bool { + let f = self.0; + let kind_of = |key: &str| match key { + "blnd" | "csrc" | "gtyp" => Kind::Int, + "sclr" | "gclr" => Kind::Fill, + _ => Kind::Real, + }; + f.arrays.is_empty() + && f.kinds.iter().all(|(key, kind)| { + (known.contains(&key.as_str()) && kind_of(key) == *kind) + || fixed.iter().any(|(k, want, v)| k == key && want == kind && f.params.get(key.as_str()) == Some(v)) + }) + } + + fn real(&self, key: &str, range: std::ops::RangeInclusive) -> Option { + (self.0.kinds.get(key) == Some(&Kind::Real)).then_some(())?; + self.0.params.get(key).copied().filter(|v| v.is_finite() && range.contains(v)) + } + + /// A choice numbered from 0 to `max`. + fn choice(&self, key: &str, max: u8) -> Option { + (self.0.kinds.get(key) == Some(&Kind::Int)).then_some(())?; + let v = self.0.params.get(key).copied().filter(|v| v.is_finite() && v.fract() == 0.0 && (0.0..=f64::from(max)).contains(v))?; + Some(v as usize) + } + + /// The blend mode in `blnd`, numbered as transparency's (`Xy`). + fn mode(&self) -> Option { + Some(super::read::blend_name(self.choice("blnd", 15)?)) + } + + /// The color of the fill style written as `key`: a solid color, in Normal at full opacity. + fn color(&self, key: &str) -> Option { + let f = self.0; + let normal = f.xy.is_none_or(|(mode, opacity)| mode == 0 && opacity >= 1.0); + (f.kinds.get(key) == Some(&Kind::Fill) && !f.gradient && f.pattern.is_none() && normal).then_some(())?; + f.fill.as_ref()?.color() + } +} + +/// Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners and Scribble (`None`: another +/// filter). `Some(None)` is one whose settings aren't all read: an unknown key, a key of another +/// kind, a value out of range or a missing setting keeps the drawn look. The keys are LiveEffect +/// XML's +/// (https://community.adobe.com/questions-652/pageitem-applyeffect-liveeffectxml-769450). +fn stylize(f: &Filter) -> Option> { + let s = Settings(f); + let opacity = || Some(s.real("opac", 0.0..=1.0)? * 100.0); + Some(match f.name.as_str() { + // `horz` and `vert` are the X and Y Offset, right and down + // (https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-drop-shadows.html); + // `csrc` 0 is Color (`sclr`), 1 Darkness (`dark`, a percent). `blur` is half the catalog's. + SHADOW => (|| { + let fixed = [("pair", Kind::Bool, 1.0), ("usePSLBlur", Kind::Bool, 1.0), (EXPAND_VERSION, Kind::Int, 16.0)]; + s.only(&["blnd", "opac", "horz", "vert", "blur", "csrc", "dark", "sclr"], &fixed).then_some(())?; + let mut params = json!({ + "mode": s.mode()?, + "opacity": opacity()?, + "blur": 2.0 * s.real("blur", 0.0..=500.0)?, + "x": s.real("horz", -1e4..=1e4)?, + "y": s.real("vert", -1e4..=1e4)?, + }); + if s.choice("csrc", 1)? == 0 { + params["color"] = json!(s.color("sclr")?); + } else { + params["shade"] = json!("darkness"); + params["darkness"] = json!(s.real("dark", 0.0..=100.0)?); + if let Some(c) = s.color("sclr") { + params["color"] = json!(c); + } + } + Some(("stylize.dropShadow", params)) + })(), + // `gtyp` 0 is Center, 1 Edge (https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/create-an-inner-or-outer-glow.html); + // `blur` is the catalog's. + INNER_GLOW => (|| { + s.only(&["blnd", "opac", "blur", "gtyp", "gclr"], &[]).then_some(())?; + let source = if s.choice("gtyp", 1)? == 0 { "center" } else { "edge" }; + let params = json!({ + "mode": s.mode()?, + "opacity": opacity()?, + "blur": s.real("blur", 0.0..=1000.0)?, + "color": s.color("gclr")?, + "source": source, + }); + Some(("stylize.innerGlow", params)) + })(), + // `blur` is half the catalog's. + GLOW => (|| { + s.only(&["blnd", "opac", "blur", "sclr"], &[("usePSLBlur", Kind::Bool, 1.0), (EXPAND_VERSION, Kind::Int, 16.0)]).then_some(())?; + let params = json!({"mode": s.mode()?, "opacity": opacity()?, "blur": 2.0 * s.real("blur", 0.0..=500.0)?, "color": s.color("sclr")?}); + Some(("stylize.outerGlow", params)) + })(), + // https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/feather-object-edges.html + FEATHER => s.only(&["Radius"], &[]).then(|| s.real("Radius", 0.0..=1000.0)).flatten().map(|r| ("stylize.feather", json!({"radius": r}))), + ROUND_CORNERS => { + s.only(&["radius"], &[]).then(|| s.real("radius", 0.0..=1e4)).flatten().map(|r| ("stylize.roundCorners", json!({"radius": r}))) + } + // `Angle` in degrees; widths, spacings and overlaps in points; `Scribbliness` (Curviness) + // and `ScribbleVariation` as fractions. The catalog's Scribble has no color, so a Scribble + // with `sclr` keeps the drawn look. + SCRIBBLE => (|| { + let keys = + ["Angle", "EdgeOverlap", "EdgeOverlapVariation", "StrokeWidth", "Scribbliness", "ScribbleVariation", "Spacing", "SpacingVariation"]; + s.only(&keys, &[]).then_some(())?; + let params = json!({ + "angle": s.real("Angle", -360.0..=360.0)?, + "overlap": s.real("EdgeOverlap", -1000.0..=1000.0)?, + "overlapVariation": s.real("EdgeOverlapVariation", 0.0..=100.0)?, + "strokeWidth": s.real("StrokeWidth", 0.01..=1000.0)?, + "curviness": s.real("Scribbliness", 0.0..=1.0)? * 100.0, + "curvinessVariation": s.real("ScribbleVariation", 0.0..=1.0)? * 100.0, + "spacing": s.real("Spacing", 0.1..=1000.0)?, + "spacingVariation": s.real("SpacingVariation", 0.0..=100.0)?, + }); + Some(("stylize.scribble", params)) + })(), + _ => return None, + }) +} + /// The live effect filter `f` is, when it is one read here. fn effect(f: &Filter) -> Option { + if let Some(stylized) = stylize(f) { + let (id, params) = stylized?; + return Some(Effect { id: id.into(), params, visible: f.visible }); + } let param = |k: &str| f.params.get(k).copied().filter(|v| v.is_finite()); let flag = |k: &str| param(k).is_some_and(|v| v != 0.0); - let mode = |default: usize| super::read::blend_name(param("blnd").map_or(default, |v| v.max(0.0) as usize)); - let color = f.fill.as_ref().and_then(Paint::color).unwrap_or(vectorcraft_color::Color::BLACK); let (id, params) = match f.name.as_str() { - // `blur`'s scale isn't publicly documented: read as the Gaussian's σ, an effect's blur being 2σ. - GLOW => ( - "stylize.outerGlow", - json!({"mode": mode(2), "opacity": param("opac").unwrap_or(0.75) * 100.0, "blur": 2.0 * param("blur").unwrap_or(5.0), "color": color}), - ), - // LiveEffect XML uses `radius`; art styles abbreviate it `rad` (public scripting posts on applyEffect). - FEATHER => ("stylize.feather", json!({"radius": param("rad").or_else(|| param("radius")).unwrap_or(5.0)})), - SHADOW => { - let mut params = json!({ - "mode": mode(1), - "opacity": param("opac").unwrap_or(0.75) * 100.0, - "blur": 2.0 * param("blur").unwrap_or(5.0), - // Undocumented; read as the dialog's offsets, not flipped like art-space y: its default 7/7 pt is - // right and down (https://helpx.adobe.com/illustrator/using/drop-shadows-glows-feathering.html). - "x": param("horz").unwrap_or(7.0), - "y": param("vert").unwrap_or(7.0), - "color": color, - }); - // A `csrc` of 1 is Darkness, the object's own colors with black added; any value other than 0 is read as - // Darkness. `dark` is the percent of black (0 to 100, where `opac` is a fraction), and 100 when it is missing or not finite. - if param("csrc").unwrap_or(0.0) != 0.0 { - params["shade"] = json!("darkness"); - params["darkness"] = json!(param("dark").map_or(100.0, |v| v.clamp(0.0, 100.0))); - } - ("stylize.dropShadow", params) - } // Effect › Warp: `DeformStyle` numbers the styles from 1 as the dialog lists them, `Rotate` // is Vertical, and the bend and distortions are fractions. DEFORM => { @@ -657,7 +814,12 @@ fn style(filters: &[Filter]) -> ArtStyle { && count(false) <= 1 && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Stroke { .. } | StyleItem::Gradient { .. })) && st.looks.iter().all(|l| l.visible && l.opacity >= 1.0 && l.blend == BlendMode::Normal && l.effects.is_empty()) - && st.effects.iter().all(|e| matches!(e.id.as_str(), "stylize.outerGlow" | "stylize.feather" | "stylize.dropShadow")); + && st.effects.iter().all(|e| { + matches!( + e.id.as_str(), + "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "stylize.roundCorners" | "stylize.scribble" + ) + }); st } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 964b74f10b..9ba5838f39 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -26,94 +26,236 @@ fn dashes_aligned_to_corners_keep_the_drawn_look() { assert!(!art_styles(data)["Stitches"].plain); } -#[test] -fn a_drop_shadow_offset_down_points_down() { - // GUARDS: the document has y down; flipping `vert` like an art-space y would turn the dialog's - // default shadow (7 pt right, 7 pt down) upwards. - let data = b"/KnownStyle :\n(Shade) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n7 /Real (horz) ,\n7 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(data); - let [shadow] = styles["Shade"].effects.as_slice() else { panic!("{:?}", styles["Shade"]) }; - assert_eq!((shadow.params["x"].as_f64(), shadow.params["y"].as_f64()), (Some(7.0), Some(7.0))); -} - /// The style `Shade`: a Drop Shadow whose dictionary holds `keys`. fn shadow_style(keys: &str) -> ArtStyle { + effect_style("Adobe Drop Shadow", keys) +} + +/// The style `Fx`: an effect `name` on the whole object, its dictionary holding `keys`. +fn effect_style(name: &str, keys: &str) -> ArtStyle { let data = format!( - "/KnownStyle :\n(Shade) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n;\n" + "/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n({name}) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{keys}; /Dict ;\n /Part ,\n;\n" ); - art_styles(data.as_bytes()).remove("Shade").unwrap_or_default() + art_styles(data.as_bytes()).remove("Fx").unwrap_or_default() +} + +/// A colour entry `key`: a fill style in RGB `r g b`. +fn color_entry(key: &str, rgb: &str) -> String { + format!("/FillStyle : 0 O\n0 0 0 0 {rgb} Xa\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Def ;\n ({key}) ,\n") +} + +/// A Drop Shadow's dictionary: every setting, with Color or Darkness set by `shade`. +fn shadow_keys(shade: &str) -> String { + format!( + "2 /Int (blnd) ,\n0.43 /Real (opac) ,\n37 /Real (dark) ,\n-13 /Real (vert) ,\n11 /Real (horz) ,\n17 /Real (blur) ,\n{}{shade}", + color_entry("sclr", "0 1 0") + ) +} + +/// `style`'s one effect on the whole object. +fn only_effect(style: &ArtStyle) -> &Effect { + assert!(style.plain, "{style:?}"); + let [e] = style.effects.as_slice() else { panic!("{style:?}") }; + e +} + +/// `params[key]`, a number within rounding of `want`. +fn near(params: &serde_json::Value, key: &str, want: f64) { + let got = params[key].as_f64(); + assert!(got.is_some_and(|v| (v - want).abs() < 1e-9), "{key}: {got:?}, not {want}: {params}"); +} + +#[test] +fn a_drop_shadow_reads_its_settings() { + // GUARDS: `vert` read as an art-space y would flip a shadow offset down to up. + let style = shadow_style(&shadow_keys("0 /Int (csrc) ,\n")); + let shadow = only_effect(&style); + let p = &shadow.params; + assert_eq!( + (shadow.id.as_str(), &p["mode"], &p["color"]), + ("stylize.dropShadow", &json!("Screen"), &json!(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0))) + ); + for (key, want) in [("x", 11.0), ("y", -13.0), ("blur", 34.0), ("opacity", 43.0)] { + near(p, key, want); + } + assert_eq!((p.get("shade"), p.get("darkness")), (None, None)); } #[test] fn a_drop_shadow_with_darkness_reads_its_darkness() { - // GUARDS: a `csrc` other than 0 made the style not plain, and the object came in as its drawn look. - let style = shadow_style("1 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n1 /Int (csrc) ,\n50 /Real (dark) ,\n"); - assert!(style.plain, "{style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{style:?}") }; - let p = &shadow.params; + let shadow = only_effect(&shadow_style(&shadow_keys("1 /Int (csrc) ,\n"))).clone(); + assert_eq!((&shadow.params["shade"], &shadow.params["darkness"]), (&json!("darkness"), &json!(37.0))); +} + +#[test] +fn a_drop_shadow_with_settings_not_read_keeps_the_drawn_look() { + // GUARDS: an unknown `csrc` was read as Darkness, `blnd` was cast to a mode, a missing setting + // took a default and an unknown key was skipped: each became an editable shadow the file doesn't draw. + let full = shadow_keys("0 /Int (csrc) ,\n"); + let cases = [ + full.replace("0 /Int (csrc)", "99 /Int (csrc)"), + full.replace("2 /Int (blnd)", "99 /Int (blnd)"), + full.replace("2 /Int (blnd)", "2.5 /Int (blnd)"), + full.replace("0 /Int (csrc)", "0.5 /Int (csrc)"), + full.replace("11 /Real (horz)", "11 /Int (horz)"), + full.replace("37 /Real (dark)", "37 /Int (dark)"), + full.replace("2 /Int (blnd)", "2 /Real (blnd)"), + full.replace("0.43 /Real (opac)", "1.5 /Real (opac)"), + full.replace("11 /Real (horz) ,\n", ""), + full.replace(&color_entry("sclr", "0 1 0"), ""), + full.replace("0 1 0 0 0 Xy", "2 0.5 0 0 0 Xy"), + format!("{full}1 /Real (spread) ,\n"), + format!("{full}0 /Bool (pair) ,\n"), + format!("{full}(x) /String (note) ,\n"), + format!("{full}3 4 /RealPointRelToROrigin (spot) ,\n"), + shadow_keys("1 /Int (csrc) ,\n").replace("37 /Real (dark)", "250 /Real (dark)"), + shadow_keys("1 /Int (csrc) ,\n").replace("37 /Real (dark)", "(fifty) /Real (dark)"), + ]; + for keys in cases { + assert!(!shadow_style(&keys).plain, "{keys}"); + } + let observed = format!("{full}1 /Bool (pair) ,\n1 /Bool (usePSLBlur) ,\n16 /Int (Adobe Effect Expand Before Version) ,\n"); + assert!(shadow_style(&observed).plain); +} + +#[test] +fn an_inner_glow_reads_its_settings() { + let keys = + |gtyp: &str| format!("10 /Int (blnd) ,\n0.41 /Real (opac) ,\n13 /Real (blur) ,\n{}{gtyp} /Int (gtyp) ,\n", color_entry("gclr", "1 0 0")); + let style = effect_style("Adobe Inner Glow", &keys("0")); + let glow = only_effect(&style); + let p = &glow.params; assert_eq!( - (shadow.id.as_str(), &p["shade"], &p["darkness"], &p["opacity"], &p["blur"]), - ("stylize.dropShadow", &json!("darkness"), &json!(50.0), &json!(75.0), &json!(10.0)) + (glow.id.as_str(), &p["mode"], &p["source"], &p["color"]), + ("stylize.innerGlow", &json!("Difference"), &json!("center"), &json!(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))) ); + near(p, "opacity", 41.0); + near(p, "blur", 13.0); + assert!(style.simple); + assert_eq!(only_effect(&effect_style("Adobe Inner Glow", &keys("1"))).params["source"], json!("edge")); + assert!(!effect_style("Adobe Inner Glow", &keys("2")).plain); } #[test] -fn a_drop_shadow_darkness_is_100_percent_when_missing_and_kept_within_0_to_100() { - for (dark, want) in [("", 100.0), ("(fifty) /Real (dark) ,\n", 100.0), ("250 /Real (dark) ,\n", 100.0), ("-5 /Real (dark) ,\n", 0.0)] { - let style = shadow_style(&format!("1 /Int (csrc) ,\n{dark}")); - assert!(style.plain, "{dark:?}: {style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{dark:?}: {style:?}") }; - assert_eq!((&shadow.params["shade"], &shadow.params["darkness"]), (&json!("darkness"), &json!(want)), "{dark:?}"); +fn an_outer_glow_reads_its_settings_and_keeps_the_drawn_look_for_others() { + let keys = format!( + "16 /Int (Adobe Effect Expand Before Version) ,\n10 /Int (blnd) ,\n0.42 /Real (opac) ,\n19 /Real (blur) ,\n{}1 /Bool (usePSLBlur) ,\n", + color_entry("sclr", "0 0 1") + ); + let glow = only_effect(&effect_style("Adobe Outer Glow", &keys)).clone(); + assert_eq!((glow.id.as_str(), &glow.params["mode"]), ("stylize.outerGlow", &json!("Difference"))); + near(&glow.params, "opacity", 42.0); + near(&glow.params, "blur", 38.0); + for other in [ + format!("{keys}1 /Real (spread) ,\n"), + keys.replace("19 /Real (blur)", "19 /Int (blur)"), + keys.replace("1 /Bool (usePSLBlur)", "0 /Bool (usePSLBlur)"), + ] { + assert!(!effect_style("Adobe Outer Glow", &other).plain, "{other}"); } } #[test] -fn a_drop_shadow_with_color_keeps_its_params() { - // GUARDS: a `csrc` of 0, or none, is Color; its shadow has neither `shade` nor `darkness`. - for csrc in ["", "0 /Int (csrc) ,\n50 /Real (dark) ,\n"] { - let style = shadow_style(&format!("2 /Int (blnd) ,\n0.5 /Real (opac) ,\n{csrc}")); - assert!(style.plain, "{csrc:?}: {style:?}"); - let [shadow] = style.effects.as_slice() else { panic!("{csrc:?}: {style:?}") }; - let want = json!({"mode": "Screen", "opacity": 50.0, "blur": 10.0, "x": 7.0, "y": 7.0, "color": vectorcraft_color::Color::BLACK}); - assert_eq!(shadow.params, want, "{csrc:?}"); +fn a_feather_reads_its_radius() { + // GUARDS: Feather was looked for under another name and key, so the files' Feather kept the drawn look. + let style = effect_style("Adobe Fuzzy Mask", "14 /Real (Radius) ,\n"); + let feather = only_effect(&style); + assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(14.0))); + assert!(style.simple); + for other in ["14 /Real (radius) ,\n", "", "-1 /Real (Radius) ,\n"] { + assert!(!effect_style("Adobe Fuzzy Mask", other).plain, "{other}"); } } #[test] -fn a_feather_reads_its_radius_from_rad() { - let data = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n12 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(data); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(12.0))); +fn round_corners_read_their_radius() { + let style = effect_style("Adobe Round Corners", "21 /Real (radius) ,\n"); + let round = only_effect(&style); + assert_eq!((round.id.as_str(), round.params["radius"].as_f64()), ("stylize.roundCorners", Some(21.0))); + assert!(style.simple); + for other in ["21 /Real (Radius) ,\n", "21 /Int (radius) ,\n", "-1 /Real (radius) ,\n"] { + assert!(!effect_style("Adobe Round Corners", other).plain, "{other}"); + } +} + +/// A Scribble's dictionary with every setting. +const SCRIBBLE_KEYS: &str = "0.8 /Real (SpacingVariation) ,\n0.23 /Real (ScribbleVariation) ,\n4 /Real (EdgeOverlapVariation) ,\n67 /Real (Angle) ,\n\ + 2.3 /Real (StrokeWidth) ,\n-7 /Real (EdgeOverlap) ,\n0.17 /Real (Scribbliness) ,\n13 /Real (Spacing) ,\n"; + +#[test] +fn a_scribble_reads_its_settings() { + let style = effect_style("Adobe Scribble Fill", SCRIBBLE_KEYS); + let scribble = only_effect(&style); + assert_eq!(scribble.id, "stylize.scribble"); + let want = [ + ("angle", 67.0), + ("overlap", -7.0), + ("overlapVariation", 4.0), + ("strokeWidth", 2.3), + ("curviness", 17.0), + ("curvinessVariation", 23.0), + ("spacing", 13.0), + ("spacingVariation", 0.8), + ]; + for (key, v) in want { + near(&scribble.params, key, v); + } + assert!(style.simple); } #[test] -fn a_feather_falls_back_to_radius_and_defaults_to_five_points() { - let with_name = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n3 /Real (radius) ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(with_name); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!(feather.params["radius"].as_f64(), Some(3.0)); +fn a_scribble_with_a_colour_or_settings_not_read_keeps_the_drawn_look() { + let cases = [ + format!("{SCRIBBLE_KEYS}{}", color_entry("sclr", "0 1 0")), + format!("{SCRIBBLE_KEYS}0.5 /Real (MinDensity) ,\n"), + SCRIBBLE_KEYS.replace("13 /Real (Spacing) ,\n", ""), + SCRIBBLE_KEYS.replace("0.17 /Real (Scribbliness)", "17 /Real (Scribbliness)"), + ]; + for keys in cases { + assert!(!effect_style("Adobe Scribble Fill", &keys).plain, "{keys}"); + } +} - let bare = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n"; - let styles = art_styles(bare); - let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; - assert_eq!(feather.params["radius"].as_f64(), Some(5.0)); +#[test] +fn effects_on_the_object_keep_their_order() { + let data = format!( + "/KnownStyle :\n(Two) /Name ,\n/ActiveStyle :\n{}", + compound( + "Chain Style Filter", + &[basic("Adobe Round Corners", "10 /Real (radius) ,\n"), basic("Adobe Drop Shadow", &shadow_keys("0 /Int (csrc) ,\n"))] + ) + ); + let st = &art_styles(data.as_bytes())["Two"]; + assert!(st.plain && st.simple, "{st:?}"); + assert_eq!(st.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.roundCorners", "stylize.dropShadow"]); +} + +#[test] +fn a_glow_on_one_fill_stays_on_that_fill() { + // An ordinary object keeps the drawn look (`simple` is false); type takes the fill's glow. + let glow = basic( + "Adobe Inner Glow", + &format!("2 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n{}1 /Int (gtyp) ,\n", color_entry("gclr", "1 1 1")), + ); + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), glow]); + let data = + format!("/KnownStyle :\n(Lit) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + let st = &art_styles(data.as_bytes())["Lit"]; + assert!(st.plain && !st.simple, "{st:?}"); + assert!(st.effects.is_empty()); + assert_eq!(st.looks[0].effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.innerGlow"]); } #[test] fn art_styles_clear_operands_beyond_the_cap() { let mut data = Vec::from( - b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n", + b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n", ); for _ in 0..80 { data.extend_from_slice(b"1 "); } - data.extend_from_slice(b"/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n"); + data.extend_from_slice(b"/Dictionary : /NotRecorded ,\n5 /Real (Radius) ,\n; /Dict ;\n /Part ,\n;\n"); let styles = art_styles(&data); let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; assert_eq!(feather.params["radius"].as_f64(), Some(5.0)); @@ -121,7 +263,8 @@ fn art_styles_clear_operands_beyond_the_cap() { #[test] fn art_styles_ignore_filters_beyond_the_cap() { - const UNIT: &[u8] = b"/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n"; + const UNIT: &[u8] = + b"/BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Real (Radius) ,\n; /Dict ;\n /Part ,\n"; let mut data = Vec::from(b"/KnownStyle :\n(Capped) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n"); for _ in 0..MAX_FILTERS + 16 { @@ -309,7 +452,7 @@ fn contents_above_some_items_count_them() { #[test] fn an_effect_not_read_here_keeps_the_drawn_look() { - let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Adobe Scribble Fill", "")]); + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), basic("Adobe Zig Zag", "")]); let data = format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); assert!(!art_styles(data.as_bytes())["Odd"].plain); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 96d0ba9411..05f33e6a3e 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2080,12 +2080,14 @@ const ART_STYLES: &str = "%AI9_BeginArtStyles\n\ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n1 /Int (blnd) ,\n0.75 /Real (opac) ,\n5 /Real (blur) ,\n\ + 0 /Int (csrc) ,\n/FillStyle : 0 O\n0 0 0 1 0 0 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,\n3 /Real (horz) ,\n4 /Real (vert) ,\n; /Dict ;\n /Part ,\n;\n\ /KnownStyle :\n(Lit) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n1 (G) 0 0 0 1 1 0 0 1 0 0 Bg\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Outer Glow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n0.5 /Real (opac) ,\n2 /Real (blur) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Outer Glow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n2 /Int (blnd) ,\n0.5 /Real (opac) ,\n2 /Real (blur) ,\n\ + /FillStyle : 0 O\n0 0 0 0 1 1 0 Xa\n0 1 Xd\n/Def ;\n (sclr) ,\n; /Dict ;\n /Part ,\n;\n\ %AI9_EndArtStyles\n"; #[test] @@ -2114,7 +2116,7 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ - /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n8 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n\ + /BasicFilter :\n(Adobe Fuzzy Mask) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n8 /Real (Radius) ,\n; /Dict ;\n /Part ,\n;\n\ %AI9_EndArtStyles\n"; let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Soft) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); @@ -2156,7 +2158,7 @@ fn a_styled_object_inside_a_drawn_look_survives_it() { /// that shadow, not as its drawn look. #[test] fn an_object_with_a_darkness_shadow_comes_in_as_itself() { - let styles = ART_STYLES.replace("3 /Real (horz) ,\n", "1 /Int (csrc) ,\n50 /Real (dark) ,\n3 /Real (horz) ,\n"); + let styles = ART_STYLES.replace("0 /Int (csrc) ,\n", "1 /Int (csrc) ,\n50 /Real (dark) ,\n"); let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_{hidden_rect}f\n1 (Blue) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); let r = read_ok(&format!("{styles}{}", layer(&art_))); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 98260d60a3..2c7fc01094 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -79,6 +79,9 @@ private editing data. VectorCraft: opens a file with that prolog from its program, as the format. - **Known failures in users' files:** layer structure flattened or multiplied (#951: 109 layers instead of 14; #868: round trip with Illustrator 2018 loses layers and groups), guides and non-printing construction + lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects + that are not read or have settings that are not read, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` + without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868. lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type (`To` … `TO`) since #868, with its paragraphs' letter @@ -89,6 +92,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4736272d74..326a9cc951 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1207,6 +1207,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Drop Shadow's Darkness:** Effect › Stylize › Drop Shadow… has Color and Darkness as radio buttons, each with its field, and the Appearance panel's inline editor has the two radio buttons in its Shade row (`shade`: `color` or `darkness`; `darkness`: 0 to 100%, 100 by default). Color is the default, and a shadow saved without these keys draws as before. With Darkness, the stored source-color model determines the adjustment before document/profile conversion and blur: subtract Darkness/100 from each RGB channel, clamped at zero, or add it to CMYK black K and Gray black, clamped at one, preserving CMYK C/M/Y. At the near-100% endpoint the shadow source becomes gray black before conversion. Shadow opacity stays separate. Original gradient stops follow the same application rule before interpolation; exact resource-level gradient parity remains open. Application SVG export keeps a live filter for simple uniform sRGB sources and uses rendered shadow images for other working RGB profiles, source models and gradients. Low-level SVG filter output warns when this preparation is needed; proportional intermediate SVG filters are not misread as additive Darkness. Exact spot/custom-color and composite-source parity remain open, and resulting CMYK ink values follow the application color pipeline. CSS export leaves the shadow out and marks the object unsupported. When a `.ai`, EPS or PDF opens from its editing data, a Drop Shadow with Darkness in an object's art style is read as one with Color is, with the shadow's Darkness percentage (100% when the style gives none). Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 428 (PDF page 434). +- **Stylize effects in `.ai` and EPS editing data:** an object whose art style holds Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble opens with those effects live, in their order, with their saved settings. A key the reader does not know, a missing or out-of-range setting, or a Scribble with a color of its own keeps the object's drawn look. + - **Live objects after document changes:** a blend, envelope or repeat, with or without an effect of its own, is evaluated again when one of these changes: the tiling of a pattern whose tiles an envelope bends (Distort Pattern Fills), a symbol shown inside a symbol, a pattern or an opacity mask, the fonts of its type, a placed document's file once the file is read, and the color settings. A gradient mesh, with or without an effect of its own, is colored again when the color settings change. - **Blend, mesh and envelope points by number:** `object.blend.spine.moveAnchor`, `reshapeSegment` and `removeAnchor`, `object.mesh.setPointColor`, `movePoint` and `deletePoint`, and `object.envelope.setMeshPoint` refuse an `anchor`, `segment` or `index` that is not a whole number, and `object.envelope.setMeshPoint` refuses a negative `index`. Specified Steps (`object.blend.make`, `object.blend.options`) and the rows and columns of `object.mesh.create`, `object.envelope.makeWithMesh` and `resetWithMesh` must be whole numbers too. From e130cf3e0c247b3e4c29bdccb4d18b7e070aed7e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 11:11:47 +0700 Subject: [PATCH 028/189] .ai import: Convert to Shape opens live on paths and type Squashed from #5142 onto main. --- crates/engine/tests/import_fuzz.rs | 56 ++++++++++ crates/eps/src/import/ai/style.rs | 74 ++++++++++++- crates/eps/src/import/ai/style/tests.rs | 136 ++++++++++++++++++++++++ crates/eps/src/import/ai/tests.rs | 39 +++++++ crates/eps/src/import/tests_native.rs | 38 +++++++ docs/file-format-parity.md | 1 + docs/target-app-parity.md | 1 + 7 files changed, 341 insertions(+), 4 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index d24f69d00f..ea03a6bfc8 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3439,6 +3439,18 @@ fn arb_ai_token() -> impl Strategy { "/Def ;", "/Execution ;", "[5 5] 1e308 d", + "(Adobe Shape Effects) 1 0 /Filter ,", + "0 /Visible ,", + "(Rectangle) /UnicodeString (DisplayString) ,", + "2 /Int (Shape) ,", + "1e999 /Int (Shape) ,", + "1 /Real (Absolute) ,", + "-1e308 /Real (RelWidth) ,", + "1e5 /Real (RelHeight) ,", + "NaN /Real (AbsWidth) ,", + "0 /Real (AbsHeight) ,", + "-9 /Real (CornerRadius) ,", + "1 /Bool (Absolute) ,", "-0.5 /Real ,", "1.5 /Real ,", "-2 /Real ,", @@ -3470,6 +3482,50 @@ fn deflated(data: &[u8]) -> Vec { proptest! { #![proptest_config(config())] + /// Art styles with Convert to Shape whose dictionary holds any of its entries, and unknown ones, + /// as any kind, with any value (huge, tiny, not a number, a string), repeated or left out, shown + /// or hidden, on a path, a group and type, on the whole object or on its fill. + #[test] + fn ai_convert_to_shape_never_panics( + entries in prop::collection::vec(( + prop::sample::select(vec![ + "Shape", "Absolute", "AbsWidth", "AbsHeight", "RelWidth", "RelHeight", "CornerRadius", "DisplayString", "futureKey", + ]), + prop::sample::select(vec!["Int", "Real", "Bool", "UnicodeString", "String"]), + prop_oneof![ + (-1e4f64..1e4).prop_map(|v| v.to_string()), + prop::sample::select(vec!["0", "1", "2", "3", "-1", "0.5", "1e-300", "1e308", "-1e308", "1e999", "NaN", "(x)", ""]).prop_map(str::to_string), + ], + ), 0..16), + visible in any::(), + on_fill in any::(), + ) { + use vectorcraft_testkit::ai; + let keys: String = entries.iter().map(|(k, kind, v)| format!("{v} /{kind} ({k}) ,\n")).collect(); + let basic = |name: &str, body: &str| format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n"); + let compound = |name: &str, kids: &[String]| format!("/CompoundFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n{};\n /Part ,\n", kids.concat()); + let fill = basic("Fill Style Filter", "/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n"); + let effect = basic("Adobe Shape Effects", &keys).replacen("1 /Visible", if visible { "1 /Visible" } else { "0 /Visible" }, 1); + let bare = compound("Chain Style Filter", &[effect.clone(), basic("Conduit Filter", "")]); + let root = if on_fill { + compound("Chain Style Filter", &[compound("Stack Style Filter", &[compound("Chain Style Filter", &[fill, effect]), basic("Conduit Filter", "")])]) + } else { + compound("Chain Style Filter", &[effect, compound("Stack Style Filter", &[fill, basic("Conduit Filter", "")])]) + }; + let styles = format!("%AI9_BeginArtStyles\n/KnownStyle :\n(Fx) /Name ,\n/ActiveStyle :\n{root}/KnownStyle :\n(Bare) /Name ,\n/ActiveStyle :\n{bare}%AI9_EndArtStyles\n"); + let hidden = ai::rect(20.0, 20.0, 80.0, 60.0).replace('\n', "\n%_"); + let art = format!( + "0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_{hidden}f\n1 (Fx) XW\n0 Ae\nu\n0 0 1 0 k\n{}f\nU\n%_0 Ae\n%_u\n%_{hidden}f\n%_U\n1 (Bare) XW\nu\n/AI11Text :\n1 /FreeUndo ,\n;\n0 0 1 0 k\n{}f\nU\n1 (Fx) XW\n", + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(20.0, 20.0, 80.0, 60.0), + ai::rect(100.0, 20.0, 180.0, 60.0) + ); + let data = ai::editing_data(200.0, 100.0, &format!("{styles}{}", ai::layer("L", &art))); + survive("Convert to Shape art style", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("Convert to Shape art style in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } + /// Hostile editing data in Illustrator EPS and `.ai` files: operators in any order with any /// operands, sections and dictionaries left open, images of any size. #[test] diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 20950c9657..3da062f8dd 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -59,6 +59,7 @@ const OFFSET: &str = "Adobe Offset Path"; // brand-ok: the filter's name in the const TRANSFORM: &str = "Adobe Transform"; // brand-ok: the filter's name in the files const GAUSSIAN: &str = "Adobe PSL Gaussian Blur"; // brand-ok: the filter's name in the files const BAS_RELIEF: &str = "PSAdapter_plugin_BsRl"; +const SHAPE_EFFECTS: &str = "Adobe Shape Effects"; // brand-ok: the filter's name in the files const CHAIN: &str = "Chain Style Filter"; const STACK: &str = "Stack Style Filter"; @@ -99,7 +100,7 @@ pub(super) struct ArtStyle { pub plain: bool, /// It is one fill and one stroke at most, in solid colours or the object's own gradient, with /// no transparency or effects of their own, and only Drop Shadow, Inner Glow, Outer Glow, - /// Feather, Round Corners and Scribble on the object: what any object is read with. Type takes the other plain styles too (its drawn look + /// Feather, Round Corners, Scribble and Convert to Shape on the object: what any object is read with. Type takes the other plain styles too (its drawn look /// can't be retyped); other objects keep their drawn look, which is the app's own rendering. pub simple: bool, /// Its fills and strokes, bottom first. @@ -326,6 +327,11 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { Tok::Word(w) => { let entry = other_entry.take().flatten(); let op = std::str::from_utf8(w).unwrap_or_default(); + if op == "," + && let (Some(key), Some(f)) = (entry, filters.last_mut()) + { + f.kinds.insert(key, Kind::Other); + } if op == "[" { array = Some(vec![]); continue; @@ -609,6 +615,55 @@ fn stylize(f: &Filter) -> Option> { }) } +/// The largest size or radius Convert to Shape reads, in points. +const MAX_SHAPE_SIZE: f64 = 1e5; + +/// Convert to Shape: Rectangle, Rounded Rectangle or Ellipse, with an absolute size or one relative +/// to the object, and a corner radius +/// (https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). +/// The keys are LiveEffect XML's: `Shape` 0 Rectangle, 1 Rounded Rectangle, 2 Ellipse +/// (https://community.adobe.com/questions-652/effect-convert-to-shape-ellipse-in-javascript-761645), +/// `Absolute` 1 for an absolute `AbsWidth` × `AbsHeight`, else `RelWidth` and `RelHeight` added to +/// each side, and `CornerRadius`; a missing size is 18 pt a side or 36 pt, and a missing radius +/// 9 pt. `None`: a key, a kind or a value that isn't read, which keeps the drawn look. +fn shape_effect(f: &Filter) -> Option { + const SIZES: [&str; 5] = ["AbsWidth", "AbsHeight", "RelWidth", "RelHeight", "CornerRadius"]; + let known = f.kinds.iter().all(|(key, kind)| match key.as_str() { + "DisplayString" => *kind == Kind::Other, + "Shape" => *kind == Kind::Int, + key => (key == "Absolute" || SIZES.contains(&key)) && *kind == Kind::Real, + }); + if !known || !f.arrays.is_empty() || f.fill.is_some() || f.stroke.is_some() || f.gradient || f.pattern.is_some() { + return None; + } + // A written size is a finite number from `min`; a missing one is `default`. + let size = |key: &str, min: f64, default: f64| match f.kinds.get(key) { + None => Some(default), + Some(_) => f.params.get(key).copied().filter(|v| v.is_finite() && (min..=MAX_SHAPE_SIZE).contains(v)), + }; + let shape = f.params.get("Shape").copied().filter(|_| f.kinds.get("Shape") == Some(&Kind::Int))?; + let absolute = match f.params.get("Absolute").copied() { + Some(0.0) => false, + Some(1.0) => true, + _ => return None, + }; + let (rel_w, rel_h) = (size("RelWidth", -MAX_SHAPE_SIZE, 18.0)?, size("RelHeight", -MAX_SHAPE_SIZE, 18.0)?); + let (abs_w, abs_h, radius) = (size("AbsWidth", 0.0, 36.0)?, size("AbsHeight", 0.0, 36.0)?, size("CornerRadius", 0.0, 9.0)?); + let id = match shape { + 0.0 => "convertToShape.rectangle", + 1.0 => "convertToShape.roundedRectangle", + // A relative Ellipse in the file is drawn round the enlarged box, and VectorCraft's inside + // it: it keeps its drawn look. + 2.0 if absolute => "convertToShape.ellipse", + _ => return None, + }; + let mut params = json!({"relative": !absolute, "extraW": 2.0 * rel_w, "extraH": 2.0 * rel_h, "width": abs_w, "height": abs_h}); + if id == "convertToShape.roundedRectangle" { + params["radius"] = json!(radius); + } + Some(Effect { id: id.into(), params, visible: f.visible }) +} + /// The live effect filter `f` is, when it is one read here. fn effect(f: &Filter) -> Option { if let Some(stylized) = stylize(f) { @@ -662,6 +717,7 @@ fn effect(f: &Filter) -> Option { GAUSSIAN => ("blur.gaussian", json!({"radius": param("blur").unwrap_or(5.0).clamp(0.0, 1000.0)})), // Its settings are in a Photoshop plug-in's binary block: the effect's defaults stand in. BAS_RELIEF => ("sketch.basRelief", json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"})), + SHAPE_EFFECTS => return shape_effect(f), _ => return None, }; Some(Effect { id: id.into(), params, visible: f.visible }) @@ -748,9 +804,11 @@ impl Builder<'_> { (look.blend, look.opacity) = (super::read::blend_mode(mode), opacity); } } + // Convert to Shape on one fill or stroke isn't read yet: what it draws there is + // the drawn look's. _ => match effect(c) { - Some(e) => look.effects.push(e), - None => self.plain = false, + Some(e) if !e.id.starts_with("convertToShape.") => look.effects.push(e), + _ => self.plain = false, }, } } @@ -817,7 +875,15 @@ fn style(filters: &[Filter]) -> ArtStyle { && st.effects.iter().all(|e| { matches!( e.id.as_str(), - "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow" | "stylize.feather" | "stylize.roundCorners" | "stylize.scribble" + "stylize.dropShadow" + | "stylize.innerGlow" + | "stylize.outerGlow" + | "stylize.feather" + | "stylize.roundCorners" + | "stylize.scribble" + | "convertToShape.rectangle" + | "convertToShape.roundedRectangle" + | "convertToShape.ellipse" ) }); st diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 9ba5838f39..c08c496763 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -469,3 +469,139 @@ fn a_hidden_fill_comes_in_hidden() { assert!(st.plain, "{st:?}"); assert_eq!(st.looks.iter().map(|l| l.visible).collect::>(), [false, true]); } + +/// A Convert to Shape filter whose dictionary holds `keys`. +fn shape(keys: &str) -> String { + basic("Adobe Shape Effects", &format!("(Shape) /UnicodeString (DisplayString) ,\n{keys}")) +} + +/// The style `Boxed`: a fill and a stroke, and `effects` on the whole object after them. +fn shape_style(effects: &[String]) -> ArtStyle { + let stack = compound( + "Stack Style Filter", + &[ + basic("Stroke Style Filter", "/StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n"), + fill("0 0 0 0 1 1 1 Xa"), + ], + ); + let mut kids = vec![stack]; + kids.extend_from_slice(effects); + let data = format!("/KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &kids)); + art_styles(data.as_bytes()).remove("Boxed").unwrap_or_default() +} + +/// Every setting of a Relative or Absolute size, with a corner radius. +const SIZES: &str = "150 /Real (AbsWidth) ,\n40 /Real (AbsHeight) ,\n20 /Real (RelWidth) ,\n6 /Real (RelHeight) ,\n15 /Real (CornerRadius) ,\n"; + +#[test] +fn convert_to_shape_comes_in_live_with_its_settings() { + // GUARDS: `Adobe Shape Effects` wasn't read, so an object with it kept its drawn look. + for (keys, id, want) in [ + ( + format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + ( + format!("1 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.roundedRectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0, "radius": 15.0}), + ), + ( + format!("2 /Int (Shape) ,\n1 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.ellipse", + json!({"relative": false, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + ( + format!("0 /Int (Shape) ,\n1 /Real (Absolute) ,\n{SIZES}"), + "convertToShape.rectangle", + json!({"relative": false, "extraW": 40.0, "extraH": 12.0, "width": 150.0, "height": 40.0}), + ), + // A relative size alone, and one that shrinks the shape: each is added to every side. + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n20 /Real (RelWidth) ,\n6 /Real (RelHeight) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 12.0, "width": 36.0, "height": 36.0}), + ), + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n-10 /Real (RelWidth) ,\n-4 /Real (RelHeight) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": -20.0, "extraH": -8.0, "width": 36.0, "height": 36.0}), + ), + // Missing sizes: 18 pt a side, 36 pt, and a 9 pt radius. + ( + "0 /Int (Shape) ,\n0 /Real (Absolute) ,\n20 /Real (RelWidth) ,\n".to_string(), + "convertToShape.rectangle", + json!({"relative": true, "extraW": 40.0, "extraH": 36.0, "width": 36.0, "height": 36.0}), + ), + ( + "1 /Int (Shape) ,\n1 /Real (Absolute) ,\n".to_string(), + "convertToShape.roundedRectangle", + json!({"relative": false, "extraW": 36.0, "extraH": 36.0, "width": 36.0, "height": 36.0, "radius": 9.0}), + ), + ] { + let st = shape_style(&[shape(&keys)]); + assert!(st.plain && st.simple, "{keys}: {st:?}"); + let [e] = st.effects.as_slice() else { panic!("{keys}: {:?}", st.effects) }; + assert_eq!((e.id.as_str(), &e.params, e.visible), (id, &want, true), "{keys}"); + assert_eq!(st.items.len(), 2, "{keys}"); + } +} + +#[test] +fn convert_to_shape_keeps_its_place_among_effects_and_its_visibility() { + let offset = basic("Adobe Offset Path", "2 /Int (jntp) ,\n4 /Real (mlim) ,\n4 /Real (ofst) ,\n"); + let st = shape_style(&[shape(&format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}")), offset.clone()]); + assert!(st.plain, "{st:?}"); + let ids: Vec<_> = st.effects.iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids, ["convertToShape.rectangle", "path.offsetPath"]); + // Offset Path isn't read on objects other than type yet. + assert!(!st.simple); + // A hidden one stays, hidden, with its settings. + let hidden = shape(&format!("1 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}")).replacen("1 /Visible", "0 /Visible", 1); + let st = shape_style(&[hidden]); + assert!(st.plain && st.simple, "{st:?}"); + let [e] = st.effects.as_slice() else { panic!("{:?}", st.effects) }; + assert_eq!( + (e.id.as_str(), e.visible, &e.params["radius"], &e.params["extraW"]), + ("convertToShape.roundedRectangle", false, &json!(15.0), &json!(40.0)) + ); +} + +#[test] +fn convert_to_shape_settings_that_arent_read_keep_the_drawn_look() { + let valid = format!("0 /Int (Shape) ,\n0 /Real (Absolute) ,\n{SIZES}"); + assert!(shape_style(&[shape(&valid)]).plain); + for keys in [ + // Another shape, a shape that isn't a whole number or an /Int, and a missing one. + valid.replace("0 /Int (Shape)", "3 /Int (Shape)"), + valid.replace("0 /Int (Shape)", "0.5 /Int (Shape)"), + valid.replace("0 /Int (Shape)", "0 /Real (Shape)"), + valid.replace("0 /Int (Shape) ,\n", ""), + // A mode other than 0 and 1, or a missing one. + valid.replace("0 /Real (Absolute)", "2 /Real (Absolute)"), + valid.replace("0 /Real (Absolute) ,\n", ""), + valid.replace("0 /Real (Absolute)", "0 /Int (Absolute)"), + // Sizes that aren't finite numbers, negative absolute sizes and radii, and huge ones. + valid.replace("20 /Real (RelWidth)", "NaN /Real (RelWidth)"), + valid.replace("6 /Real (RelHeight)", "1e999 /Real (RelHeight)"), + valid.replace("6 /Real (RelHeight)", "(x) /Real (RelHeight)"), + valid.replace("150 /Real (AbsWidth)", "-150 /Real (AbsWidth)"), + valid.replace("15 /Real (CornerRadius)", "-1 /Real (CornerRadius)"), + valid.replace("20 /Real (RelWidth)", "1e6 /Real (RelWidth)"), + valid.replace("40 /Real (AbsHeight)", "40 /Int (AbsHeight)"), + // A key that isn't read. + format!("{valid}1 /Real (Future) ,\n"), + format!("{valid}(x) /String (Future) ,\n"), + // A relative Ellipse. + valid.replace("0 /Int (Shape)", "2 /Int (Shape)"), + ] { + let st = shape_style(&[shape(&keys)]); + assert!(!st.plain, "{keys}: {st:?}"); + } + // On one fill: the drawn look, for type too. + let item = compound("Chain Style Filter", &[fill("0 0 0 1 0 0 0 Xa"), shape(&valid)]); + let data = + format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])])); + assert!(!art_styles(data.as_bytes())["Odd"].plain); +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 05f33e6a3e..a11e89139e 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2128,6 +2128,45 @@ fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +#[test] +fn an_object_with_convert_to_shape_comes_in_as_itself_with_the_effect_live() { + // GUARDS: `Adobe Shape Effects` wasn't read, so the object came in as its drawn look. + let styles = |keys: &str| { + format!( + "%AI9_BeginArtStyles\n\ + /KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Shape Effects) 1 0 /Filter ,\n1 /Visible ,\n(ShapeEffect.aip) /PluginFileName ,\n(Shape) /Title ,\n\ + /Dictionary : /NotRecorded ,\n(Rectangle) /UnicodeString (DisplayString) ,\n{keys}; /Dict ;\n /Part ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n" + ) + }; + let hidden_rect = rect_path(20.0, 20.0, 90.0, 60.0).replace('\n', "\n%_"); + // The drawn look is the shape: 20 pt wider on each side and 6 pt taller. + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Boxed) XW\n", rect_path(0.0, 14.0, 110.0, 66.0)); + let keys = "0 /Int (Shape) ,\n150 /Real (AbsWidth) ,\n0 /Real (Absolute) ,\n40 /Real (AbsHeight) ,\n20 /Real (RelWidth) ,\n15 /Real (CornerRadius) ,\n6 /Real (RelHeight) ,\n"; + let r = read_ok(&format!("{}{}", styles(keys), layer(&art_))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}"); + let b = a[0].geometric_bounds().unwrap(); + assert_eq!((b.width(), b.height()), (70.0, 40.0), "the object keeps its own path"); + assert_eq!(fill(&a[0]).color(), Some(Color::rgb(0.0, 0.0, 1.0))); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{:?}", a[0].appearance.effects) }; + assert_eq!( + (e.id.as_str(), e.params["relative"].as_bool(), e.params["extraW"].as_f64(), e.params["extraH"].as_f64()), + ("convertToShape.rectangle", Some(true), Some(40.0), Some(12.0)) + ); + // A shape that isn't read: the drawn look. + let r = read_ok(&format!("{}{}", styles(&keys.replace("0 /Int (Shape)", "7 /Int (Shape)")), layer(&art_))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 94127e8cfd..49c1f1f61c 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2956,6 +2956,44 @@ fn type_with_a_stacked_art_style_comes_in_as_type_with_that_appearance() { check(&r.document, &r.warnings); } +#[test] +fn type_with_convert_to_shape_comes_in_as_type_with_it_live() { + // GUARDS: `Adobe Shape Effects` wasn't read, and type with it came in without its art style, + // the style's drawing beside it as paths. + let shape = "/BasicFilter :\n(Adobe Shape Effects) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + (RoundedRectangle) /UnicodeString (DisplayString) ,\n1 /Int (Shape) ,\n0 /Real (Absolute) ,\n4 /Real (RelWidth) ,\n\ + 2 /Real (RelHeight) ,\n3 /Real (CornerRadius) ,\n; /Dict ;\n /Part ,\n"; + let stack = "/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n"; + let styles = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Boxed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + {shape}{stack};\n /Part ,\n%AI9_EndArtStyles\n" + ); + let doc = text_document(&[("Bang\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let drawing = "0 0 1 0 k\n54 56 m\n100 56 L\n100 80 L\n54 80 L\nf"; + let look = format!("u\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n{drawing}\nU\n9 () XW\n"); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let art = native_with_text(&(styles + &layer("Art", true, &format!("{look}{own}1 (Boxed) XW\n"))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + let (mut texts, mut paths) = (vec![], 0); + d.walk(|n| match &n.kind { + NodeKind::Text(t) => texts.push((t.plain_text(), n.appearance.effects.clone())), + NodeKind::Path { .. } => paths += 1, + _ => {} + }); + let [(text, effects)] = texts.as_slice() else { panic!("{texts:?} {notes:?}") }; + assert_eq!((text.as_str(), paths), ("Bang", 0), "{notes:?}"); + let [e] = effects.as_slice() else { panic!("{effects:?}") }; + assert_eq!( + (e.id.as_str(), &e.params), + ( + "convertToShape.roundedRectangle", + &serde_json::json!({"relative": true, "extraW": 8.0, "extraH": 4.0, "width": 36.0, "height": 36.0, "radius": 3.0}) + ) + ); +} + #[test] fn point_type_without_a_matrix_is_placed_by_its_layout() { // GUARDS: Illustrator 24 leaves an unturned, unscaled point type's matrix out of its frame; such diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2c7fc01094..6371aea8f1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -92,6 +92,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow or Convert to Shape comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 326a9cc951..02504f89f9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1076,6 +1076,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From 54b79c02b059a087332d5937cc77199c598bb3a1 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:27:45 +0700 Subject: [PATCH 029/189] .ai import: Convert to Shape records string entries through the shared dictionary parser --- crates/eps/src/import/ai/style.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 3da062f8dd..c2b305bdcb 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -327,11 +327,6 @@ pub(super) fn art_styles(data: &[u8]) -> HashMap { Tok::Word(w) => { let entry = other_entry.take().flatten(); let op = std::str::from_utf8(w).unwrap_or_default(); - if op == "," - && let (Some(key), Some(f)) = (entry, filters.last_mut()) - { - f.kinds.insert(key, Kind::Other); - } if op == "[" { array = Some(vec![]); continue; From 6bf2941f28f25a398cd211257a0f2c1f2b04a6da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:28:39 -0700 Subject: [PATCH 030/189] Docs: .ai guides are no longer listed as lost #5057 opens ruler guides and guide objects from a .ai's editing data and closed #779. The File formats row of docs/target-app-parity.md, the known failures in docs/file-format-parity.md, G9 in docs/gaps.md and docs/roadmap.md still listed guides as lost. --- docs/file-format-parity.md | 4 ++++ docs/gaps.md | 3 +-- docs/roadmap.md | 4 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6371aea8f1..0e11ca08f6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -78,6 +78,10 @@ private editing data. VectorCraft: (gradients filled with their first stop's colour, type left to the apps that read the format). VectorCraft opens a file with that prolog from its program, as the format. - **Known failures in users' files:** layer structure flattened or multiplied (#951: 109 layers instead of + 14; #868: round trip with Illustrator 2018 loses layers and groups), some files 4× slower to open since the + editing data is read whole (#758), live effects, brushes and symbols come in as their drawn look (#637; + pattern fills are read since #1025); legacy `.ai` without the prolog opens since #1027, its legacy type + (`To` … `TO`) since #868; guides open as ruler guides and guide paths since #5057 (#779). 14; #868: round trip with Illustrator 2018 loses layers and groups), guides and non-printing construction lines lost (#779), some files 4× slower to open since the editing data is read whole (#758), live effects that are not read or have settings that are not read, brushes and symbols come in as their drawn look (#637; pattern fills are read since #1025); legacy `.ai` diff --git a/docs/gaps.md b/docs/gaps.md index 5c04e87040..1abcecc5bd 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -160,8 +160,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done (2026-10-16):** EPS legacy mesh corners and vector opacity masks retained; winding-declared compound member groups keep shared paint. Raster print-page minification no longer causes a false editing-data fallback; comparison limits remain unchanged. Synthetic regressions cover damage and missing artwork. This narrows G9; scores and estimates unchanged. - **Missing:** faithful layer and group structure from the editing data in real files (#951: 109 layers instead - of 14), guides and non-printing construction - lines (#779), open speed on large files (#758), live effects, brushes and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope + of 14), open speed on large files (#758), live effects, brushes and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope (undocumented): a PDF-compatible `.ai` opens in Illustrator 2018 without its layers and groups (#868). Save As `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification instead, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and diff --git a/docs/roadmap.md b/docs/roadmap.md index 979eb11214..abfaea70ba 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -58,13 +58,13 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | Set type: point and area type, Character and Paragraph styles, threading, outlines | yes | type core 80%; styles, threading, Create Outlines and font matching tested ([type-parity.md](type-parity.md)); justification options missing (not blocking) | 0 | | Organise layers and artboards and export assets (Export for Screens, SVG, PNG, PDF per artboard) | yes | Layers panel rework, Artboards panel and tool, Export for Screens and Asset Export done; Art Optimized supersample closes ghost borders (#983 / #1037) | 0 | | Print production: CMYK and spot colour, bleed and marks, PDF/X out, separations preview | yes | PDF/X-1a/3/4, presets, marks and bleed, ICC output intent, Separations Preview, Print with PostScript output | 0 | -| Exchange files with Illustrator users: open their `.ai`/EPS/PDF, hand back a file they can open | partial (doesn't block alpha) | `.ai`, EPS and PDF open as editable art, but real files can get the wrong layer structure (#951) and lose guides (#779); Save As `.ai` is PDF-compatible, which Illustrator opens without its own editing data (#868), or legacy version 7, which keeps layers, groups and type as text, one artboard per file, and waits for users' testing. EPS legacy mesh corners, vector opacity masks and raster print-page comparison now preserve editable art under synthetic regressions. This is the beta main-format gap ([gaps.md](gaps.md) G9) | 10–20 (for beta) | +| Exchange files with Illustrator users: open their `.ai`/EPS/PDF, hand back a file they can open | partial (doesn't block alpha) | `.ai`, EPS and PDF open as editable art, but real files can get the wrong layer structure (#951); Save As `.ai` is PDF-compatible, which Illustrator opens without its own editing data (#868), or legacy version 7, which keeps layers, groups and type as text, one artboard per file, and waits for users' testing. EPS legacy mesh corners, vector opacity masks and raster print-page comparison now preserve editable art under synthetic regressions. This is the beta main-format gap ([gaps.md](gaps.md) G9) | 10–20 (for beta) | ## Current focus 1. **Interaction-fidelity pass** (G1) by tool, from [ui-parity.md](ui-parity.md): Pen and Curvature, Direct Selection, smart guides and snapping first. 60–90 h, parallel by tool. -2. **`.ai` files from real users** (G9): layer structure (#951), guides (#779). 10–20 h. +2. **`.ai` files from real users** (G9): layer structure (#951). 10–20 h. 3. **Launch and stability** (G10): the Windows and Linux start-up reports. 20–35 h. 4. **Core-tool bugs** (G11): SVG units reverting to points (#864) and a Transform effect in a fill's or stroke's own effects (#885). Shape Builder regions (#937), Asset Export ghost borders (#983 / #1037) and the stalling bezier drag preview (#834) are fixed. 8–15 h. 5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 02504f89f9..73f40007b5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -145,7 +145,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated; document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and Arrange | 9–14 | estimated | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented; video rulers (View › Rulers › Show Video Rulers, #2849) done, score unchanged | From afeb4a85746bdf5f77f6d111a26d01bcb87b938a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 1 Nov 2026 00:42:13 -0700 Subject: [PATCH 031/189] Docs: the .ai issue counts in G9 and the file-exchange discount are dated Both passages still name guides among the open .ai issues. They now say the counts were measured on 2026-10-10, before #779 closed. --- docs/gaps.md | 2 +- docs/target-app-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 1abcecc5bd..2bef5bff57 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -169,7 +169,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall omitted, hidden objects go to a hidden layer, are omitted or made visible), and type is set again in the reader's fonts. Legacy type in `.ai` files in PostScript form is read on open. It waits for testing by users who hand files back. -- **Evidence:** the issues above; 28 of the 350 issues are about `.ai`/EPS (about 22 people, the most common single +- **Evidence:** the issues above; 28 of the 350 issues measured on 2026-10-10 are about `.ai`/EPS (about 22 people, the most common single format theme), 20 fixed, and the 8 open ones are about structure (layers, guides, speed, live objects), not missing art. No real-file `.ai` corpus (users' files may be used locally, never committed). - **Impact:** blocks anyone who hands files back to Illustrator users. Opening and reworking their own archive diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 73f40007b5..2df8531f84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -221,7 +221,7 @@ generative AI, pen tilt, languages beyond their own) are left out. **Essentials: The discounts, with the evidence: - **Illustrator's own files (×0.92).** `.ai` and EPS open as editable art by reading their PDF/PostScript and the - structure of the editing data. Users do open legacy files a lot: 28 of the 350 issues (8%, ~22 people) are + structure of the editing data. Users do open legacy files a lot: 28 of the 350 issues measured on 2026-10-10 (8%, ~22 people) are about `.ai`/EPS, the most common single format theme. 20 of the 28 are fixed (often the same day). The 8 open ones are about structure, not missing art: layers flattened or multiplied (#951: 109 layers instead of 14; #868), guides lost (#779), slower opening (#758), live effects, brushes and symbols as their drawn look From 9596130be49340c0faaf99ffad5e2587e70c85c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:46:41 -0700 Subject: [PATCH 032/189] .ai import: Objects on Path records measure each group once Each Objects on Path record measured the bounds of every object it names, and checked its path, before it was turned down. A thousand copies of a record whose object is a group of 20,000 paths took 5.6 s to open instead of about 50 ms. A record now checks its group and ids first, and the path and objects of a group are measured for one record at most. --- crates/eps/src/import/ai/read/on_path.rs | 34 +++++++++++------ crates/eps/src/import/ai/tests.rs | 48 ++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 11 deletions(-) diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs index 909d611315..4fe14e8545 100644 --- a/crates/eps/src/import/ai/read/on_path.rs +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -131,13 +131,15 @@ pub(super) fn apply(doc: &mut Document, found: &OnPath) { // Where every object with an id is, found in one walk of the tree (setting a record doesn't // move anything). let at = doc.index_paths(found.tags.keys().copied()); + // The groups whose path and objects have been measured. + let mut tried = HashSet::new(); for r in &found.records { // A record that doesn't match leaves the group as it was read. - let _ = apply_one(doc, found, &at, r); + let _ = apply_one(doc, found, &at, &mut tried, r); } } -fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap>, r: &Record) -> Option<()> { +fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap>, tried: &mut HashSet, r: &Record) -> Option<()> { // The one object still in the document with the id `uuid` (a commented copy may have gone). let resolve = |uuid: &str| -> Option<(NodeId, &Vec)> { let mut live = found.ids.get(uuid)?.iter().filter_map(|id| at.get(id).map(|p| (*id, p))); @@ -150,26 +152,36 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap return None; } let (_, group_at) = path_at.split_last()?; + let g = doc.node_at(group_at)?; + let NodeKind::Group { children, clip: false } = &g.kind else { return None }; + if g.extras().objects_on_path.is_some() || children.len() != r.ids.len() { + return None; + } let mut seen = HashSet::from([path]); - let mut members = Vec::with_capacity(rest.len()); + let mut placed = Vec::with_capacity(rest.len()); for (i, uuid) in rest.iter().enumerate() { let (id, place) = resolve(uuid)?; let tag = found.tags.get(&id)?; if !seen.insert(id) || place.split_last().map(|(_, up)| up) != Some(group_at) || tag.key_path || tag.order != Some(i as f64) { return None; } - // The frame the object is drawn in: turned by its angle (the document's y points down) - // about the center of its bounds. - let angle = -tag.angle?; - let center = doc.node_at(place)?.geometric_bounds()?.center(); - members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); + placed.push((id, place, -tag.angle?)); } - let g = doc.node_at(group_at)?; - let NodeKind::Group { children, clip: false } = &g.kind else { return None }; - if g.extras().objects_on_path.is_some() || children.len() != seen.len() || children.iter().any(|c| !seen.contains(&c.id)) { + if children.iter().any(|c| !seen.contains(&c.id)) { + return None; + } + // What is left depends on the group's objects alone, so each group is measured once. + if !tried.insert(g.id) { return None; } attachable_path(children.iter().find(|c| c.id == path)?)?; + let mut members = Vec::with_capacity(placed.len()); + for (id, place, angle) in placed { + // The frame the object is drawn in: turned by its angle (the document's y points down) + // about the center of its bounds. + let center = doc.node_at(place)?.geometric_bounds()?.center(); + members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); + } let on_path = ObjectsOnPath { path, members, pivot: r.pivot, rotate: r.rotate }; doc.node_mut_at(group_at)?.extras_mut().objects_on_path = Some(Box::new(on_path)); Some(()) diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index a11e89139e..9ef13e271b 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3400,3 +3400,51 @@ fn an_objects_on_path_group_in_versioned_content_opens_once() { assert_eq!(kids[0].children().unwrap().len(), 5); assert!(kids[0].extras().objects_on_path.is_some()); } + +/// The path and objects of a group are measured once however many records name it: a thousand +/// copies of a record open about as fast as one copy followed by 999 records whose path id is +/// missing, when the group opens live, when its long path has no length, and when its first object +/// is a group of many paths and its last object has no bounds. +#[test] +fn repeated_objects_on_path_records_dont_measure_the_objects_again() { + use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record}; + let paths: String = (0..20_000).map(|i| format!("{}f\n", rect_path(f64::from(i % 200), 40.0, f64::from(i % 200) + 1.0, 46.0))).collect(); + let big = format!("u\n{RED}{paths}U\n{}", on_path_member(ON_PATH_IDS[1], Some(0), 0.0)); + let empty = format!("u\nU\n{}", on_path_member(ON_PATH_IDS[2], Some(1), 0.0)); + let still = format!("20 20 m\n{}S\n", "20 20 L\n".repeat(20_000)); + let cases = [ + ("a live group", OPEN_PATH.to_string(), big.clone(), 2, true), + ("a path without length", still, big.clone(), 2, false), + ("an object without bounds", OPEN_PATH.to_string(), format!("{big}{empty}"), 3, false), + ]; + for (why, path, objects, n, live) in cases { + let ids = &ON_PATH_IDS[..n]; + let group = format!( + "0 Ae\nu\n/ConstraintGroup :\n128 /GroupType ,\n;\n0 0 1 0 0 0 1 XA\n2 w\n{path}{}{objects}U\n", + on_path_member(ids[0], None, 0.0) + ); + let record = on_path_record(ALIGN_ON_PATH, ids, &on_path_options(n - 1, 4, 0.0, "")); + let (start, end) = (record.find("%_/Dictionary :\n%_1 /Int").unwrap(), record.find("%_; (Constraint Data)").unwrap()); + let copy = &record[start..end]; + let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000"); + let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]); + let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]); + let time = |data: &str| { + let started = std::time::Instant::now(); + let doc = read_ok(&format!("{data}{}", layer(&group))).doc; + let elapsed = started.elapsed(); + let g = art(&doc)[0].clone(); + assert_eq!(g.children().unwrap().len(), n, "{why}"); + assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}"); + elapsed + }; + // The fastest of three runs each, taken in turn, so that other tests running at the same + // time weigh on both. + let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX); + for _ in 0..3 { + fastest_one = fastest_one.min(time(&one)); + fastest_many = fastest_many.min(time(&many)); + } + assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}"); + } +} From cbd4dd5599df01aa859a934053e352a6bbea9410 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:57:10 -0700 Subject: [PATCH 033/189] Docs: list every case where an unread .ai object still sends the file to its page The file-format and progress docs named three of the cases in which an unread object's page art is not used and the file comes in as its page. The import also does this when the object lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, and when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's (`replace_unread` and `copy_page_resources` in `crates/eps/src/import/native/build.rs`). --- docs/file-format-parity.md | 1 + docs/target-app-parity.md | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0e11ca08f6..2a2ecbe9bf 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -96,6 +96,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow, Drop Shadow or Convert to Shape comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners or Scribble comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), guides, and every artboard where it is. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with an Outer Glow or Drop Shadow comes in as itself with them; one with more, other effects, a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Transform (with copies), Drop Shadow, Outer Glow, Feather, Gaussian Blur and Bas Relief (its settings at their defaults), and a style with others keeps the type's drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); the page's drawing of it (often in pieces) is left out. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2df8531f84..2294563f63 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1074,6 +1074,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). When the editing data of a `.ai` or EPS is for a page of another size than the file's, the warning that its layers weren't read gives both sizes in points, and the scale of the editing data's page to the file's page (1:10 for a tenth of its size) when their sides are in proportion (#2034; `crates/eps/src/import/tests_native.rs`). A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type keeps its drawn art, with its type hidden (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From bb354fc92ad8f185d785ea5ae222e47309bbf33b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 21:54:32 -0700 Subject: [PATCH 034/189] .ai import: page art moved to its artboard takes its pattern tiles along Art taken from a `.ai`'s PDF part on a later page is moved to where the editing data puts that artboard. The move left pattern fills and strokes where they were, so their tiles no longer lined up with the art. This happened in three places: the page art that stands in for an unread object (#5050), the page's type given to text objects, and the art on each page when the file comes in as its PDF part with the artboard layout kept. Each move now transforms the pattern tiles too. --- crates/eps/src/import/native/build.rs | 8 +- crates/eps/src/import/native/layers.rs | 4 +- crates/eps/src/import/tests_native.rs | 104 +++++++++++++++++++++++++ 3 files changed, 112 insertions(+), 4 deletions(-) diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index bf0a8d4a5a..b4f8ee30c4 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -15,6 +15,10 @@ pub(super) enum Page { Artboard, } +/// How art moved from a page to its place in the layers' document transforms: its pattern tiles +/// move with it. +pub(super) const PAGE_MOVE: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: false, patterns: true }; + /// The page (`visible`, the file read as its page) and the place of its area in the layers' /// document. pub(super) struct Frame<'a> { @@ -177,7 +181,7 @@ pub(super) fn build_from( None => shift, }; for n in object.iter_mut() { - Arc::make_mut(n).transform(shift, false); + Arc::make_mut(n).transform(shift, PAGE_MOVE); } } // An EPS saved as its artboard has the art outside it left out of its page. @@ -681,7 +685,7 @@ fn replace_unread( for &i in &selected { let mut copy = Node::clone(&art[i].node); if let Some(shift) = moves.get(page) { - copy.transform(*shift, false); + copy.transform(*shift, PAGE_MOVE); } found.push(Arc::new(reid_page_art(doc, ©))); claimed.insert(i, art[i].end); diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index 6be56c200d..c4e961c476 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{Page, build, build_from}; +use super::build::{PAGE_MOVE, Page, build, build_from}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -204,7 +204,7 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { let fit = |p: &Rect| (p.intersect(r).area().max(0.0), -(p.center() - r.center()).hypot()); let Some((i, _)) = pages.iter().map(fit).enumerate().max_by(|(_, a), (_, b)| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))) else { continue }; if let Some(v) = moves.get(i).filter(|v| **v != Vec2::ZERO) { - Arc::make_mut(child).transform(Affine::translate(*v), false); + Arc::make_mut(child).transform(Affine::translate(*v), PAGE_MOVE); } } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 49c1f1f61c..15b3e21caa 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -832,6 +832,43 @@ fn unread_object_on_second_artboard_takes_second_page_art() { assert_eq!(bounds, vectorcraft_geom::Rect::new(50.0, 196.0, 54.0, 200.0)); } +#[test] +fn page_art_from_second_artboard_moves_its_pattern_tile() { + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let second = "u\n0 0 1 0 k\n50 -100 m\n54 -100 L\n54 -96 L\n50 -96 L\nf\nZZ\nU"; + let art = native(&(boards.to_string() + dots + &layer("Live", true, &square(10, 10)) + &layer("Mixed", true, second))); + let (editing, _) = crate::ai_alone(&private(&native(&format!("{dots}{}", layer("Live", true, &square(10, 10)))))).unwrap(); + let source = editing.pattern("Dots").unwrap(); + let mut page = pdf_part(10.0, 86.0); + let mut pattern = source.clone(); + pattern.art = source.art.iter().map(|node| std::sync::Arc::new(page.reid(node))).collect(); + page.patterns.push(pattern); + let mut board = page.artboards[0].clone(); + (board.id, board.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + page.artboards.push(board); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(170.0, 46.0, 174.0, 50.0)); + let paint = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let node = Node::path(page.alloc_id(), path, appearance); + let layer = page.layers[0].id; + page.insert(Some(layer), 1, node).unwrap(); + let (doc, notes, read) = crate::layered_ai(&private(&art), page, vec![], false, false, 1.0); + assert!(read, "{notes:?}"); + let replacement = &doc.layers[1].children().unwrap()[0].children().unwrap()[0]; + assert_eq!(replacement.visual_bounds().unwrap(), vectorcraft_geom::Rect::new(50.0, 196.0, 54.0, 200.0)); + let Some(vectorcraft_color::Paint::Pattern { xf, .. }) = replacement.appearance.fill().map(|f| &f.paint) else { + panic!("the page art's pattern fill is kept: {:?}", replacement.appearance); + }; + assert_eq!(*xf, vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(-120.0, 150.0))); +} + #[test] fn unknown_operator_between_objects_falls_back() { let body = format!("{}\nZZ\n{}", square(50, 10), square(70, 10)); @@ -1443,6 +1480,38 @@ fn an_ai_file_read_as_its_pdf_part_keeps_its_artboard_layout() { assert!((moved[1] - vectorcraft_geom::Point::new(100.0, 1600.0)).hypot() < 1e-6, "the second's art goes with its page: {moved:?}"); } +#[test] +fn art_moved_with_its_page_moves_its_pattern_tile() { + // Two 100-point artboards, the second 50 below the first; an operator this doesn't know, so + // the layers aren't read. + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let art = native(&(boards.to_string() + &layer("Art", true, &(square(10, 10) + "\n1 Zz")))); + // The PDF part: the second page 20 points right of the first, with a pattern-filled square. + let mut pdf = pdf_part(10.0, 10.0); + let mut page = pdf.artboards[0].clone(); + (page.id, page.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + pdf.artboards.push(page); + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(130.0, 10.0, 134.0, 14.0)); + let paint = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + }; + let (id, layer_id) = (pdf.alloc_id(), pdf.layers[0].id); + pdf.insert(Some(layer_id), 1, Node::path(id, path, appearance)).unwrap(); + let (d, w, read) = crate::layered_ai(&private(&art), pdf, vec![], false, false, 1.0); + assert!(!read, "{w:?}"); + let square = &d.layers[0].children().unwrap()[1]; + assert_eq!(square.visual_bounds().unwrap().origin(), vectorcraft_geom::Point::new(10.0, 160.0)); + let Some(vectorcraft_color::Paint::Pattern { xf, .. }) = square.appearance.fill().map(|f| &f.paint) else { + panic!("the square keeps its pattern fill: {:?}", square.appearance); + }; + assert_eq!(*xf, vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(-120.0, 150.0))); +} + #[test] fn a_gray_is_a_grayscale_colour() { // `g` is a gray: 0.25 is 75 % of the black ink, as the page's own CMYK black says; the colour @@ -2126,6 +2195,41 @@ fn type_on_a_later_artboard_of_an_ai_file_goes_to_its_text_object() { assert!(!w.iter().any(|w| w.contains("with another's") || w.contains("doesn't draw")), "{w:?}"); } +#[test] +fn page_type_on_a_later_artboard_moves_its_pattern_tile() { + // As above, with a frame this doesn't read, so the text object takes the page's type, which + // has a pattern fill. + let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ + %_/Dictionary :\n%_0 100 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_/Dictionary :\n%_0 -50 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_100 -150 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ + %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; + let doc = last_frame_unread(&text_document(&[("Hi there\r", 0, (8200.0, 8341.5), (0.0, 0.0), 0.0)])); + let art = native_with_text(&(boards.to_string() + &layer("Art", true, &(square(10, 10) + &text_object(0)))), &doc); + let mut pdf = pdf_part(10.0, 86.0); + let mut page = pdf.artboards[0].clone(); + (page.id, page.rect) = (2, vectorcraft_geom::Rect::new(120.0, 0.0, 220.0, 100.0)); + pdf.artboards.push(page); + let style = vectorcraft_doc::CharStyle { size: 14.0, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(178.5, 50.0), "Hi there", style); + let (id, layer_id) = (pdf.alloc_id(), pdf.layers[0].id); + let mut node = Node::new(id, NodeKind::Text(Box::new(text))); + let paint = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + node.appearance = vectorcraft_doc::Appearance { + items: vec![vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(paint))], + ..Default::default() + } + .into(); + pdf.insert(Some(layer_id), 1, node).unwrap(); + let (d, w, read) = crate::layered_ai(&private(&art), pdf, vec![], false, false, 1.0); + assert!(read, "{w:?}"); + let texts: Vec<&Node> = d.layers[0].children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| &**n).collect(); + assert_eq!(texts.len(), 1, "{w:?}"); + let Some(vectorcraft_color::Paint::Pattern { xf, .. }) = texts[0].appearance.fill().map(|f| &f.paint) else { + panic!("the page's type keeps its pattern fill: {:?}", texts[0].appearance); + }; + assert_eq!(*xf, vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(-120.0, 150.0))); +} + /// A global process colour (`Xk`) or a pattern fill on a sublayer no longer sends a `.ai` to its /// PDF part, which has only the top-level layers (#1025). #[test] From ecd184510c32dc8dbac4996eaefb107268553543 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 31 Oct 2026 19:07:17 -0700 Subject: [PATCH 035/189] Place: Word .doc styles are resolved once and damaged property tables are refused Each style's formatting is now worked out once, on top of the style it is based on, and each property run's formatting once, so a document with many hidden paragraphs or long style chains no longer resolves the chains again for every paragraph and run. Character styles are applied as a change to the paragraph's formatting. A bin table whose file positions do not rise, a property page listed twice, pages whose runs overlap, and styles based on each other in a loop are refused as damaged, as MS-DOC requires (PlcBteChpx, ChpxFkp, StdfBase). Property runs refer to their page instead of copying it. --- crates/engine/src/cmd/place/doc.rs | 324 ++++++++++++++++++++------ crates/engine/src/tests/textimport.rs | 66 +++++- docs/mcp.md | 5 +- 3 files changed, 314 insertions(+), 81 deletions(-) diff --git a/crates/engine/src/cmd/place/doc.rs b/crates/engine/src/cmd/place/doc.rs index 41f269c502..f46634b077 100644 --- a/crates/engine/src/cmd/place/doc.rs +++ b/crates/engine/src/cmd/place/doc.rs @@ -39,7 +39,8 @@ //! other stories, tracked changes and tables. A stream larger than [`MAX_STREAM`] bytes, a main //! text longer than [`text::MAX_TEXT`] characters, more than [`MAX_PIECES`] pieces or //! [`MAX_PAGES`] property pages, and placed type of more than [`MAX_PARAGRAPHS`] paragraphs or -//! [`MAX_RUNS`] runs are refused, and so is a structure that lies outside its stream. +//! [`MAX_RUNS`] runs are refused, and so are a structure that lies outside its stream, property +//! pages whose runs are listed twice or overlap, and styles based on each other in a loop. use std::io::{Cursor, Read}; @@ -71,8 +72,6 @@ const MAX_PIECES: usize = 100_000; const MAX_PAGES: usize = 16_384; /// The most styles read from the style sheet (`Stshif.cstd` is below 0x0FFE). const MAX_STYLES: usize = 0x0FFE; -/// The most styles one style's chain of `istdBase` takes in. -const MAX_BASED_ON: usize = 32; /// The most fonts read from the font table (SttbfFfn's `cData` is at most 0x7FF0). const MAX_FONTS: usize = 0x7FF0; /// The most bytes of a font name kept. @@ -359,17 +358,21 @@ enum Fkp { } /// The file positions `start..end` and the properties a property page gives them. -struct Run { +struct Run<'a> { start: u32, end: u32, /// The paragraph style (Papx only). istd: u16, - grpprl: Vec, + /// The properties, in their property page. + grpprl: &'a [u8], } /// The runs of the property pages the bin table `plc` (PlcBteChpx or PlcBtePapx) points to, in -/// the WordDocument stream `wd`, ordered by file position. -fn runs(wd: &[u8], plc: &[u8], kind: Fkp, cmd: &str) -> Result> { +/// the WordDocument stream `wd`, ordered by file position. The bin table's file positions rise +/// ("MUST be sorted in ascending order", and a PlcBteChpx "MUST NOT contain duplicate stream +/// offsets"), and so do the runs of its pages one after another: a page listed twice, or pages +/// whose runs overlap, are damaged. +fn runs<'a>(wd: &'a [u8], plc: &[u8], kind: Fkp, cmd: &str) -> Result>> { let broken = || damaged(cmd, "its character or paragraph properties are damaged"); if plc.len() < 4 || !(plc.len() - 4).is_multiple_of(8) { return Err(broken()); @@ -378,19 +381,28 @@ fn runs(wd: &[u8], plc: &[u8], kind: Fkp, cmd: &str) -> Result> { if n > MAX_PAGES { return Err(bad(cmd, format!("the Word document has more than {MAX_PAGES} pages of properties, too many to place"))); } - let mut out = vec![]; + let fcs = (0..=n).map(|i| u32_at(plc, 4 * i)).collect::>>().ok_or_else(broken)?; + if fcs.windows(2).any(|w| w.first() >= w.get(1)) { + return Err(broken()); + } + let mut out: Vec> = vec![]; for i in 0..n { // PnFkpChpx and PnFkpPapx: the page number in bits 0 to 21. let pn = u32_at(plc, 4 * (n + 1) + 4 * i).ok_or_else(broken)? & 0x003F_FFFF; let page = bytes_at(wd, pn as usize * 512, 512).ok_or_else(broken)?; + let first = out.len(); page_runs(page, kind, &mut out).ok_or_else(broken)?; + // A page's own runs rise (rgfc); its first starts at or after the end of the page before. + let before = first.checked_sub(1).and_then(|k| out.get(k)).map(|r| r.end); + if before.zip(out.get(first)).is_some_and(|(end, r)| r.start < end) { + return Err(broken()); + } } - out.sort_by_key(|r| r.start); Ok(out) } /// The runs of one 512-byte property page; None when it is damaged. -fn page_runs(page: &[u8], kind: Fkp, out: &mut Vec) -> Option<()> { +fn page_runs<'a>(page: &'a [u8], kind: Fkp, out: &mut Vec>) -> Option<()> { let count = usize::from(*page.get(511)?); let most = if kind == Fkp::Chpx { 0x65 } else { 0x1D }; if count == 0 || count > most { @@ -402,10 +414,10 @@ fn page_runs(page: &[u8], kind: Fkp, out: &mut Vec) -> Option<()> { let entry = 4 * (count + 1) + if kind == Fkp::Chpx { i } else { 13 * i }; let offset = usize::from(*page.get(entry)?) * 2; let (istd, grpprl) = match (offset, kind) { - (0, _) => (0, vec![]), + (0, _) => (0, &[][..]), (_, Fkp::Chpx) => { let cb = usize::from(*page.get(offset)?); - (0, bytes_at(page, offset + 1, cb).filter(|_| offset + 1 + cb <= 511)?.to_vec()) + (0, bytes_at(page, offset + 1, cb).filter(|_| offset + 1 + cb <= 511)?) } (_, Fkp::Papx) => { // PapxInFkp: 2 × cb − 1 bytes, or (cb = 0) 2 × cb′ bytes after cb′. @@ -414,9 +426,11 @@ fn page_runs(page: &[u8], kind: Fkp, out: &mut Vec) -> Option<()> { cb => (offset + 1, 2 * cb - 1), }; let grp = bytes_at(page, at, len).filter(|_| at + len <= 511 && len >= 2)?; - (u16_at(grp, 0)?, grp.get(2..)?.to_vec()) + (u16_at(grp, 0)?, grp.get(2..)?) } }; + // rgfc "MUST be sorted in ascending order and MUST NOT contain duplicates": each run ends + // where the next starts. if end <= start { return None; } @@ -473,10 +487,14 @@ struct Style { chpx: Vec, } -/// The style sheet: its styles by istd and its default font. +/// The style sheet: each style's formatting with that of the styles it is based on, by istd, and +/// its default font. #[derive(Default)] struct Sheet { - styles: Vec>, + /// Paragraph styles: their paragraph formatting and their text's. + paragraph: Vec>, + /// Character styles: what they do to the formatting of the text they are applied to. + character: Vec>, /// `Stshif.ftcAsci`. font: Option, } @@ -500,23 +518,74 @@ impl Sheet { // LPStd records start on even offsets. at += 2 + usize::from(len) + usize::from(len) % 2; } - Ok(Self { styles, font }) + let root = (Para::default(), Chars { font, ..Chars::default() }); + let paragraph = resolve(&styles, 1, root, |(mut para, chars), s| { + para.apply(&s.papx); + (para, chars.with(&CharsChange::of(&s.chpx))) + }) + .ok_or_else(broken)?; + let character = resolve(&styles, 2, CharsChange::default(), |change, s| change.then(&CharsChange::of(&s.chpx))).ok_or_else(broken)?; + Ok(Self { paragraph, character, font }) } - /// Style `istd` of kind `stk` and the styles it is based on, the first of the chain first. - fn chain(&self, istd: u16, stk: u8) -> Vec<&Style> { - let mut seen: Vec = vec![]; - let mut chain = vec![]; - let mut next = istd; - while next != NO_STYLE && !seen.contains(&next) && seen.len() < MAX_BASED_ON { - let Some(s) = self.styles.get(usize::from(next)).and_then(Option::as_ref).filter(|s| s.stk == stk) else { break }; - seen.push(next); - chain.push(s); - next = s.base; - } - chain.reverse(); - chain + /// Paragraph style `istd`'s paragraph formatting and its text's; the document defaults when + /// it is no paragraph style. + fn paragraph_style(&self, istd: u16) -> (Para, Chars) { + self.paragraph.get(usize::from(istd)).copied().flatten().unwrap_or((Para::default(), Chars { font: self.font, ..Chars::default() })) } + + /// What character style `istd` does to text; nothing when it is no character style. + fn character_style(&self, istd: u16) -> CharsChange { + self.character.get(usize::from(istd)).copied().flatten().unwrap_or_default() + } +} + +/// The formatting of each style of `styles` of kind `stk` with that of the styles it is based on: +/// `root` with `own` applied for each style of its chain of `istdBase`, the first of the chain +/// first. Each style's formatting is worked out once, on that of the style it is based on. A chain +/// ends at a style of another kind or none. None when `istdBase` makes a loop (which it "MUST +/// NOT", StdfBase). +fn resolve(styles: &[Option