From efd57a4a5de91fb2630df973901bdc3b456dedb1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:31:22 -0800 Subject: [PATCH 01/41] i18n: unused-answers and Liquify skip messages translate for one item too The script error for answers left in `answers` and Liquify's warning about objects under the brush that it left as they were built their singular by adding an empty suffix, so no catalog template could match the singular form, and neither message had a catalog row for either count. - Both messages are now built from complete singular and plural English sentences; `it was` and `they were` are part of the sentence. The English the commands return does not change. - Every complete-message catalog has an `@msgplural` row for each, with the language's own count forms. The tool name and the list of kinds stay as written. --- crates/engine/src/cmd/distortcmds.rs | 13 +++++----- crates/engine/src/script/mod.rs | 6 ++++- crates/engine/src/tests/distort.rs | 20 +++++++++++++++ crates/engine/src/tests/script_dialogs.rs | 12 +++++++++ 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/hi.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/nl.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 | 31 +++++++++++++++++++++++ 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/target-app-parity.md | 1 + 29 files changed, 121 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 2dbb7a9a18..80b9474c81 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -631,13 +631,12 @@ impl LiquifyStroke { } let msg = (!ids.is_empty()).then(|| { let n = ids.len(); - format!( - "{} left {n} object{} under the brush as {} ({}): it reshapes paths only", - self.prm.kind.label(), - if n == 1 { "" } else { "s" }, - if n == 1 { "it was" } else { "they were" }, - kinds.join(", ") - ) + let (tool, kinds) = (self.prm.kind.label(), kinds.join(", ")); + if n == 1 { + format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only") + } else { + format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only") + } }); (ids, msg) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 1edeb84e93..d169b1294c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2004,7 +2004,11 @@ impl Session { Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => { let n = job.host.dialogs.unused(); let kind = LimitKind::Host; - let message = format!("`answers` has {n} answer{} the script did not use", if n == 1 { "" } else { "s" }); + let message = if n == 1 { + format!("`answers` has {n} answer the script did not use") + } else { + format!("`answers` has {n} answers the script did not use") + }; Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 })) } Ok(Ok(Progress::Done(_))) => { diff --git a/crates/engine/src/tests/distort.rs b/crates/engine/src/tests/distort.rs index d033fadee6..6e0cb2b88c 100644 --- a/crates/engine/src/tests/distort.rs +++ b/crates/engine/src/tests/distort.rs @@ -265,6 +265,26 @@ fn liquify_without_selection_hits_paths_under_the_brush() { assert!(path(&s, b).bounds().unwrap().width() < 100.0); } +/// The warning about objects under the brush that Liquify leaves as they are names their count +/// with the matching noun and verb. +#[test] +fn liquify_warns_about_one_or_several_skipped_objects() { + let mut s = session(); + let text = + |s: &mut Session, x: i32| s.execute("text.create", &json!({"x": x, "y": 460, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap(); + let pucker = json!({"tool": "pucker", "points": [[550, 450]], "diameter": 150, "intensity": 1}); + let first = text(&mut s, 520); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("object.liquify", &pucker).unwrap(); + assert_eq!(r["skipped"], json!([first])); + assert_eq!(r["warning"], "Pucker left 1 object under the brush as it was (type): it reshapes paths only"); + let second = text(&mut s, 560); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let r = s.execute("object.liquify", &pucker).unwrap(); + assert_eq!(r["skipped"], json!([first, second])); + assert_eq!(r["warning"], "Pucker left 2 objects under the brush as they were (type): it reshapes paths only"); +} + /// With nothing selected, a stroke leaves the art on a locked artboard as it is. #[test] fn liquify_without_selection_leaves_the_art_on_a_locked_artboard() { diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index f955a6fdb3..baa8989208 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -120,6 +120,18 @@ fn missing_or_mismatched_answer_rolls_back() { assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "missing"); } +/// The error about answers left over names their count with the matching noun. +#[test] +fn unused_answers_are_counted_in_the_singular_and_the_plural() { + let mut s = one_doc(); + let ok = json!({"kind": "alert", "value": "ok"}); + for (extra, says) in [(1, "`answers` has 1 answer the script did not use"), (2, "`answers` has 2 answers the script did not use")] { + let given = Value::Array(vec![ok.clone(); extra + 1]); + let e = headless(&mut s, "alert('x');", given).unwrap_err().to_string(); + assert!(e.contains(says), "{e}"); + } +} + #[test] fn invalid_answers_are_rejected_before_run() { let mut s = one_doc(); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 373eb0b79d..8cc7090986 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5556,6 +5556,8 @@ digits Malayalam Malaiàlam @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un quadre de diàleg no es pot obrir dins d'una crida de retorn d'una funció integrada, un getter, una conversió o un fitxer que executa $.evalFile; crideu-lo des del codi propi de l'script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la resposta següent d'`answers` és per a {_1}, no per a {name} @msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no queden respostes per a aquest quadre de diàleg +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` conté {n} resposta que l'script no ha utilitzat|`answers` conté {n} respostes que l'script no ha utilitzat +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ha deixat {n} objecte sota el pinzell sense canvis ({_2}): només remodela traçats|{_1} ha deixat {n} objectes sota el pinzell sense canvis ({_2}): només remodela traçats @msg vc.document{place} is too large for a script vc.document{place} és massa gran per a un script @msg vc.log: the log of this run is full vc.log: el registre d'aquesta execució és ple @msg this function's script run has ended l'execució de l'script d'aquesta funció ha acabat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7178be3143..9b80e745af 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4665,6 +4665,8 @@ imageTrace Outline Obrys @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog se nemůže otevřít uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; zavolejte jej z vlastního kódu skriptu @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: další odpověď v `answers` je pro {_1}, ne pro {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` už nemá pro tento dialog žádnou odpověď +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use V `answers` je {n} odpověď, kterou skript nepoužil|V `answers` jsou {n} odpovědi, které skript nepoužil|V `answers` je {n} odpovědí, které skript nepoužil +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ponechal {n} objekt pod štětcem beze změny ({_2}): mění pouze cesty|{_1} ponechal {n} objekty pod štětcem beze změny ({_2}): mění pouze cesty|{_1} ponechal {n} objektů pod štětcem beze změny ({_2}): mění pouze cesty @msg vc.document{place} is too large for a script vc.document{place} je pro skript příliš velký @msg vc.log: the log of this run is full vc.log: protokol tohoto běhu je plný @msg this function's script run has ended běh skriptu této funkce skončil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 951f6f9c37..03b04b5610 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4278,6 +4278,8 @@ theme Appearance Erscheinungsbild @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: Ein Dialog kann sich nicht in einem Callback einer integrierten Funktion, einem Getter, einer Umwandlung oder einer Datei öffnen, die $.evalFile ausführt; rufen Sie ihn aus dem eigenen Code des Skripts auf @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: Die nächste Antwort in `answers` ist für {_1}, nicht für {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` hat keine Antwort mehr für diesen Dialog +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` enthält {n} Antwort, die das Skript nicht verwendet hat|`answers` enthält {n} Antworten, die das Skript nicht verwendet hat +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ließ {n} Objekt unter dem Pinsel unverändert ({_2}): es formt nur Pfade um|{_1} ließ {n} Objekte unter dem Pinsel unverändert ({_2}): es formt nur Pfade um @msg vc.document{place} is too large for a script vc.document{place} ist zu groß für ein Skript @msg vc.log: the log of this run is full vc.log: Das Protokoll dieses Laufs ist voll @msg this function's script run has ended der Skriptlauf dieser Funktion ist beendet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 62e3adc491..ab9ac9af30 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2425,6 +2425,8 @@ axis Both Και τα δύο @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ένα παράθυρο διαλόγου δεν μπορεί να ανοίξει μέσα σε επανάκληση ενσωματωμένης συνάρτησης, getter, μετατροπή ή αρχείο που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: η επόμενη απάντηση στο `answers` είναι για το {_1}, όχι για το {name} @msg {name}: `answers` has no answer left for this dialog {name}: το `answers` δεν έχει άλλη απάντηση για αυτό το παράθυρο διαλόγου +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use Το `answers` περιέχει {n} απάντηση που δεν χρησιμοποίησε το σενάριο|Το `answers` περιέχει {n} απαντήσεις που δεν χρησιμοποίησε το σενάριο +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only Το {_1} άφησε {n} αντικείμενο κάτω από το πινέλο χωρίς αλλαγή ({_2}): αναδιαμορφώνει μόνο διαδρομές|Το {_1} άφησε {n} αντικείμενα κάτω από το πινέλο χωρίς αλλαγή ({_2}): αναδιαμορφώνει μόνο διαδρομές @msg vc.document{place} is too large for a script το vc.document{place} είναι πολύ μεγάλο για σενάριο @msg vc.log: the log of this run is full vc.log: το αρχείο καταγραφής αυτής της εκτέλεσης είναι γεμάτο @msg this function's script run has ended η εκτέλεση σεναρίου αυτής της συνάρτησης έχει τελειώσει diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d1c6aa53af..a42f00bd84 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4355,6 +4355,8 @@ axis Both Ambos @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un cuadro de diálogo no puede abrirse dentro de una devolución de llamada de una función integrada, un getter, una conversión o un archivo que ejecuta $.evalFile; llámelo desde el propio código del script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la siguiente respuesta de `answers` es para {_1}, no para {name} @msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no le quedan respuestas para este cuadro de diálogo +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contiene {n} respuesta que el script no usó|`answers` contiene {n} respuestas que el script no usó +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} dejó {n} objeto bajo el pincel sin cambios ({_2}): solo modifica trazados|{_1} dejó {n} objetos bajo el pincel sin cambios ({_2}): solo modifica trazados @msg vc.document{place} is too large for a script vc.document{place} es demasiado grande para un script @msg vc.log: the log of this run is full vc.log: el registro de esta ejecución está lleno @msg this function's script run has ended la ejecución del script de esta función ha terminado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 45e47fd355..4695ffec4f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4579,6 +4579,8 @@ imageTrace Outline Ääriviiva @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: valintaikkuna ei voi avautua sisäänrakennetun funktion takaisinkutsussa, getterissä, muunnoksessa tai tiedostossa, jonka $.evalFile ajaa; kutsu sitä skriptin omasta koodista @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: seuraava vastaus kohteessa `answers` on kohteelle {_1}, ei kohteelle {name} @msg {name}: `answers` has no answer left for this dialog {name}: kohteessa `answers` ei ole enää vastausta tälle valintaikkunalle +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` sisältää {n} vastauksen, jota komentosarja ei käyttänyt|`answers` sisältää {n} vastausta, joita komentosarja ei käyttänyt +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} jätti {n} objektin siveltimen alla muuttamatta ({_2}): se muokkaa vain polkuja|{_1} jätti {n} objektia siveltimen alla muuttamatta ({_2}): se muokkaa vain polkuja @msg vc.document{place} is too large for a script vc.document{place} on liian suuri skriptille @msg vc.log: the log of this run is full vc.log: tämän ajon loki on täynnä @msg this function's script run has ended tämän funktion skriptiajo on päättynyt diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 057dce6872..8e91cc3391 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4344,6 +4344,8 @@ axis Both Les deux @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue ne peut pas s'ouvrir dans un rappel d'une fonction intégrée, un accesseur, une conversion ou un fichier que $.evalFile exécute ; appelez-la depuis le code du script lui-même @msg {name}: the next answer in `answers` is for {_1}, not {name} {name} : la réponse suivante de `answers` est pour {_1}, pas pour {name} @msg {name}: `answers` has no answer left for this dialog {name} : `answers` n'a plus de réponse pour cette boîte de dialogue +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contient {n} réponse que le script n'a pas utilisée|`answers` contient {n} réponses que le script n'a pas utilisées +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} a laissé {n} objet sous le pinceau sans changement ({_2}) : il ne remodèle que les tracés|{_1} a laissé {n} objets sous le pinceau sans changement ({_2}) : il ne remodèle que les tracés @msg vc.document{place} is too large for a script vc.document{place} est trop volumineux pour un script @msg vc.log: the log of this run is full vc.log : le journal de cette exécution est plein @msg this function's script run has ended l'exécution du script de cette fonction est terminée diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9d056e085a..e891e8ebfa 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6668,6 +6668,8 @@ antiAlias Sharp शार्प @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: कोई डायलॉग किसी बिल्ट-इन फ़ंक्शन के कॉलबैक, getter, रूपांतरण या $.evalFile द्वारा चलाई गई फ़ाइल के भीतर नहीं खुल सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` में अगला उत्तर {_1} के लिए है, {name} के लिए नहीं @msg {name}: `answers` has no answer left for this dialog {name}: `answers` में इस डायलॉग के लिए कोई उत्तर नहीं बचा है +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` में {n} उत्तर है जिसका स्क्रिप्ट ने उपयोग नहीं किया|`answers` में {n} उत्तर हैं जिनका स्क्रिप्ट ने उपयोग नहीं किया +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ने ब्रश के नीचे {n} ऑब्जेक्ट को अपरिवर्तित छोड़ा ({_2}): यह केवल पाथ को नया आकार देता है|{_1} ने ब्रश के नीचे {n} ऑब्जेक्ट्स को अपरिवर्तित छोड़ा ({_2}): यह केवल पाथ्स को नया आकार देता है @msg vc.document{place} is too large for a script vc.document{place} स्क्रिप्ट के लिए बहुत बड़ा है @msg vc.log: the log of this run is full vc.log: इस रन का लॉग भर गया है @msg this function's script run has ended इस फ़ंक्शन का स्क्रिप्ट रन समाप्त हो गया है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c2f1a52cd9..fd28ce795a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5165,6 +5165,8 @@ imageTrace Outline Körvonal @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: párbeszédpanel nem nyílhat meg beépített függvény visszahívásában, getterben, átalakításban vagy a $.evalFile által futtatott fájlban; hívja a parancsfájl saját kódjából @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: a következő válasz az `answers` listában ehhez tartozik: {_1}, nem ehhez: {name} @msg {name}: `answers` has no answer left for this dialog {name}: az `answers` listában nem maradt válasz ehhez a párbeszédpanelhez +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use Az `answers` listában {n} válasz maradt, amelyet a parancsfájl nem használt fel +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}: az ecset alatt {n} objektum változatlan maradt ({_2}); csak útvonalakat alakít át @msg vc.document{place} is too large for a script a vc.document{place} túl nagy egy parancsfájlhoz @msg vc.log: the log of this run is full vc.log: ennek a futásnak a naplója megtelt @msg this function's script run has ended ennek a függvénynek a parancsfájl-futása véget ért diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0ac2816b07..93ecf45caa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4407,6 +4407,8 @@ axis Both Entrambi @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: una finestra di dialogo non può aprirsi dentro un callback di una funzione integrata, un getter, una conversione o un file eseguito da $.evalFile; chiamala dal codice dello script stesso @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: la prossima risposta in `answers` è per {_1}, non per {name} @msg {name}: `answers` has no answer left for this dialog {name}: in `answers` non rimangono risposte per questa finestra di dialogo +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contiene {n} risposta che lo script non ha usato|`answers` contiene {n} risposte che lo script non ha usato +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ha lasciato {n} oggetto sotto il pennello senza modifiche ({_2}): rimodella solo i tracciati|{_1} ha lasciato {n} oggetti sotto il pennello senza modifiche ({_2}): rimodella solo i tracciati @msg vc.document{place} is too large for a script vc.document{place} è troppo grande per uno script @msg vc.log: the log of this run is full vc.log: il registro di questa esecuzione è pieno @msg this function's script run has ended l'esecuzione dello script di questa funzione è terminata diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 71de1ce91c..33cda40c61 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5169,6 +5169,8 @@ swatch Bright Violet ビビッドバイオレット @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 組み込み関数のコールバック、getter、変換、または $.evalFile が実行するファイルの中ではダイアログを開けません。スクリプト自身のコードから呼び出してください @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` の次の回答は {name} ではなく {_1} のものです @msg {name}: `answers` has no answer left for this dialog {name}: `answers` にこのダイアログの回答が残っていません +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` にスクリプトが使用しなかった回答が {n} 件あります +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} はブラシの下にある {n} 個のオブジェクトを変更せずに残しました({_2})。パスのみを変形します @msg vc.document{place} is too large for a script vc.document{place} はスクリプトには大きすぎます @msg vc.log: the log of this run is full vc.log: この実行のログがいっぱいです @msg this function's script run has ended この関数のスクリプトの実行は終了しています diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2cff51d94b..6253248728 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5575,6 +5575,8 @@ imageTrace Outline კონტური @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: დიალოგი ვერ გაიხსნება ჩაშენებული ფუნქციის უკუძახილში, getter-ში, გარდაქმნაში ან ფაილში, რომელსაც $.evalFile უშვებს; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: შემდეგი პასუხი `answers`-ში არის {_1}-ისთვის და არა {name}-ისთვის @msg {name}: `answers` has no answer left for this dialog {name}: `answers`-ში ამ დიალოგისთვის პასუხი აღარ დარჩა +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers`-ში დარჩა {n} პასუხი, რომელიც სკრიპტს არ გამოუყენებია +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}-მა ფუნჯის ქვეშ უცვლელი დატოვა {n} ობიექტი ({_2}): ის მხოლოდ ტრაექტორიებს ცვლის @msg vc.document{place} is too large for a script vc.document{place} ზედმეტად დიდია სკრიპტისთვის @msg vc.log: the log of this run is full vc.log: ამ გაშვების ჟურნალი სავსეა @msg this function's script run has ended ამ ფუნქციის სკრიპტის გაშვება დასრულდა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4715a413f4..c6b9485c55 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5096,6 +5096,8 @@ theme Appearance 외관 @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 기본 제공 함수의 콜백, getter, 변환 또는 $.evalFile이 실행하는 파일 안에서는 대화 상자를 열 수 없습니다. 스크립트 자체 코드에서 호출하세요 @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers`의 다음 답은 {name}이(가) 아니라 {_1}에 대한 것입니다 @msg {name}: `answers` has no answer left for this dialog {name}: `answers`에 이 대화 상자에 대한 답이 남아 있지 않습니다 +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers`에 스크립트가 사용하지 않은 답이 {n}개 있습니다 +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}은(는) 브러시 아래의 개체 {n}개를 변경하지 않았습니다({_2}). 패스만 변형합니다 @msg vc.document{place} is too large for a script vc.document{place}이(가) 스크립트에 비해 너무 큽니다 @msg vc.log: the log of this run is full vc.log: 이 실행의 로그가 가득 찼습니다 @msg this function's script run has ended 이 함수의 스크립트 실행이 끝났습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 94957fb782..a4dd02b9e4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -131,6 +131,8 @@ @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: een dialoogvenster kan niet openen binnen een callback van een ingebouwde functie, een getter, een conversie of een bestand dat $.evalFile uitvoert; roep het aan vanuit de eigen code van het script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: het volgende antwoord in `answers` is voor {_1}, niet voor {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` heeft geen antwoord meer voor dit dialoogvenster +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` bevat {n} antwoord dat het script niet heeft gebruikt|`answers` bevat {n} antwoorden die het script niet heeft gebruikt +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} liet {n} object onder het penseel ongewijzigd ({_2}): het vervormt alleen paden|{_1} liet {n} objecten onder het penseel ongewijzigd ({_2}): het vervormt alleen paden @msg vc.document{place} is too large for a script vc.document{place} is te groot voor een script @msg vc.log: the log of this run is full vc.log: het logboek van deze uitvoering is vol @msg this function's script run has ended de scriptuitvoering van deze functie is beëindigd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 48f2671c2d..8a1f6af6f3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4489,6 +4489,8 @@ imageTrace Outline Kontur @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: okno dialogowe nie może się otworzyć w wywołaniu zwrotnym funkcji wbudowanej, getterze, konwersji ani pliku uruchamianym przez $.evalFile; wywołaj je z własnego kodu skryptu @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: następna odpowiedź w `answers` jest dla {_1}, nie dla {name} @msg {name}: `answers` has no answer left for this dialog {name}: w `answers` nie została żadna odpowiedź dla tego okna dialogowego +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` zawiera {n} odpowiedź, której skrypt nie użył|`answers` zawiera {n} odpowiedzi, których skrypt nie użył|`answers` zawiera {n} odpowiedzi, których skrypt nie użył +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} pozostawił {n} obiekt pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki|{_1} pozostawił {n} obiekty pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki|{_1} pozostawił {n} obiektów pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki @msg vc.document{place} is too large for a script vc.document{place} jest za duży dla skryptu @msg vc.log: the log of this run is full vc.log: dziennik tego uruchomienia jest pełny @msg this function's script run has ended uruchomienie skryptu tej funkcji zakończyło się diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f6e54552d4..36ec788215 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5384,6 +5384,8 @@ axis Both Ambos @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: uma caixa de diálogo não pode abrir dentro de um callback de uma função interna, um getter, uma conversão ou um arquivo que $.evalFile executa; chame-a a partir do próprio código do script @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: a próxima resposta em `answers` é para {_1}, não para {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` não tem mais respostas para esta caixa de diálogo +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contém {n} resposta que o script não usou|`answers` contém {n} respostas que o script não usou +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} deixou {n} objeto sob o pincel sem alteração ({_2}): remodela apenas caminhos|{_1} deixou {n} objetos sob o pincel sem alteração ({_2}): remodela apenas caminhos @msg vc.document{place} is too large for a script vc.document{place} é grande demais para um script @msg vc.log: the log of this run is full vc.log: o registro desta execução está cheio @msg this function's script run has ended a execução do script desta função terminou diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8dc8336089..0a6c21462b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4392,6 +4392,8 @@ axis Both Оба @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: диалоговое окно не может открыться внутри обратного вызова встроенной функции, геттера, преобразования или файла, который выполняет $.evalFile; вызовите его из собственного кода скрипта @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: следующий ответ в `answers` предназначен для {_1}, а не для {name} @msg {name}: `answers` has no answer left for this dialog {name}: в `answers` не осталось ответа для этого диалогового окна +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use В `answers` остался {n} ответ, который скрипт не использовал|В `answers` осталось {n} ответа, которые скрипт не использовал|В `answers` осталось {n} ответов, которые скрипт не использовал +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} оставил без изменений {n} объект под кистью ({_2}): он изменяет только контуры|{_1} оставил без изменений {n} объекта под кистью ({_2}): он изменяет только контуры|{_1} оставил без изменений {n} объектов под кистью ({_2}): он изменяет только контуры @msg vc.document{place} is too large for a script vc.document{place} слишком велик для скрипта @msg vc.log: the log of this run is full vc.log: журнал этого запуска заполнен @msg this function's script run has ended запуск скрипта этой функции завершён diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cfb9d9734b..d56b9a8df4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4265,6 +4265,8 @@ axis Both Båda @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en dialogruta kan inte öppnas i ett återanrop från en inbyggd funktion, en getter, en konvertering eller en fil som $.evalFile kör; anropa den från skriptets egen kod @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: nästa svar i `answers` gäller {_1}, inte {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` har inget svar kvar för den här dialogrutan +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` har {n} svar som skriptet inte använde|`answers` har {n} svar som skriptet inte använde +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} lämnade {n} objekt under penseln utan ändring ({_2}): bara banor formas om|{_1} lämnade {n} objekt under penseln utan ändring ({_2}): bara banor formas om @msg vc.document{place} is too large for a script vc.document{place} är för stort för ett skript @msg vc.log: the log of this run is full vc.log: loggen för den här körningen är full @msg this function's script run has ended skriptkörningen för den här funktionen har avslutats diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 705fc68db2..7abee75a1c 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2029,6 +2029,37 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// A script's error about unused `answers` and Liquify's note on the objects it left as they were +/// are translated whole for one object as well as for several, in every complete-message language, +/// and keep their counts. +#[test] +fn messages_with_one_or_several_items_translate_in_every_complete_catalog() { + let notes = [ + ("`answers` has 1 answer the script did not use", "1"), + ("`answers` has 2 answers the script did not use", "2"), + ("`answers` has 5 answers the script did not use", "5"), + ("Warp left 1 object under the brush as it was (type): it reshapes paths only", "1"), + ("Twirl left 2 objects under the brush as they were (type, images): it reshapes paths only", "2"), + ("Pucker left 5 objects under the brush as they were (symbols): it reshapes paths only", "5"), + ]; + // Whole words, so that a word such as Swedish "under" or Dutch "object" is not read as English. + let english = ["answer", "did", "use", "left", "brush", "was", "they", "were", "reshapes", "paths", "only"]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (note, count) in notes { + let shown = message(lang, note); + assert_ne!(shown, note, "{code}"); + assert!(shown.split(|c: char| !c.is_alphabetic()).all(|w| !english.contains(&w)), "{code}: {shown}"); + assert!(shown.contains(count) && (!note.starts_with('`') || shown.contains("`answers`")), "{code}: {shown}"); + } + } + // The count picks the language's form. + let cs = cs(); + assert!(message(cs, "`answers` has 1 answer the script did not use").contains("1 odpověď,")); + assert!(message(cs, "`answers` has 2 answers the script did not use").contains("2 odpovědi,")); + assert!(message(cs, "`answers` has 5 answers the script did not use").contains("5 odpovědí,")); +} + #[test] fn package_status_message_templates_parse() { let c = Catalog::parse(concat!( diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2b3e843ba3..7130be9543 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4120,6 +4120,8 @@ axis Both Her İkisi @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: bir iletişim kutusu yerleşik bir işlevin geri çağrısında, bir getter içinde, bir dönüştürmede veya $.evalFile'ın çalıştırdığı bir dosyada açılamaz; bunu betiğin kendi kodundan çağırın @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: `answers` içindeki sonraki yanıt {name} için değil, {_1} için @msg {name}: `answers` has no answer left for this dialog {name}: `answers` içinde bu iletişim kutusu için yanıt kalmadı +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` içinde betiğin kullanmadığı {n} yanıt var +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}, fırçanın altındaki {n} nesneyi değiştirmeden bıraktı ({_2}): yalnızca yolları yeniden şekillendirir @msg vc.document{place} is too large for a script vc.document{place} bir betik için çok büyük @msg vc.log: the log of this run is full vc.log: bu çalıştırmanın günlüğü dolu @msg this function's script run has ended bu işlevin betik çalıştırması sona erdi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 50690fa0c7..58e0f4bc8b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4391,6 +4391,8 @@ axis Both Обидві @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: діалогове вікно не може відкритися всередині зворотного виклику вбудованої функції, гетера, перетворення або файлу, який виконує $.evalFile; викличте його з власного коду скрипту @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: наступна відповідь у `answers` призначена для {_1}, а не для {name} @msg {name}: `answers` has no answer left for this dialog {name}: у `answers` не залишилося відповіді для цього діалогового вікна +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use У `answers` залишилася {n} відповідь, яку скрипт не використав|У `answers` залишилися {n} відповіді, які скрипт не використав|У `answers` залишилося {n} відповідей, які скрипт не використав +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} залишив без змін {n} об’єкт під пензлем ({_2}): він змінює форму лише контурів|{_1} залишив без змін {n} об’єкти під пензлем ({_2}): він змінює форму лише контурів|{_1} залишив без змін {n} об’єктів під пензлем ({_2}): він змінює форму лише контурів @msg vc.document{place} is too large for a script vc.document{place} завеликий для скрипту @msg vc.log: the log of this run is full vc.log: журнал цього запуску заповнений @msg this function's script run has ended запуск скрипту цієї функції завершився diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d8469bce53..45a9f761b4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4819,6 +4819,8 @@ theme Appearance Giao diện @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: hộp thoại không thể mở bên trong lệnh gọi lại của hàm dựng sẵn, getter, phép chuyển đổi hoặc tệp mà $.evalFile chạy; hãy gọi nó từ mã của chính tập lệnh @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: câu trả lời tiếp theo trong `answers` dành cho {_1}, không phải {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` không còn câu trả lời nào cho hộp thoại này +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` có {n} câu trả lời mà tập lệnh không dùng +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} giữ nguyên {n} đối tượng dưới cọ ({_2}): chỉ biến dạng đường dẫn @msg vc.document{place} is too large for a script vc.document{place} quá lớn đối với tập lệnh @msg vc.log: the log of this run is full vc.log: nhật ký của lần chạy này đã đầy @msg this function's script run has ended lần chạy tập lệnh của hàm này đã kết thúc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d9d9110276..82cfe27b30 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4849,6 +4849,8 @@ imageTrace Outline 轮廓 @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:对话框不能在内置函数的回调、getter、转换或 $.evalFile 运行的文件中打开;请从脚本自身的代码中调用 @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}:`answers` 中的下一个回答是给 {_1} 的,而不是给 {name} 的 @msg {name}: `answers` has no answer left for this dialog {name}:`answers` 中已没有此对话框的回答 +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` 中有 {n} 个脚本未使用的回答 +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} 未更改画笔下的 {n} 个对象({_2}):它只重塑路径 @msg vc.document{place} is too large for a script vc.document{place}对脚本来说过大 @msg vc.log: the log of this run is full vc.log:本次运行的日志已满 @msg this function's script run has ended 此函数的脚本运行已结束 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a0d987fe69..f2d06f6973 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2563,6 +2563,8 @@ file-filter Templates 範本 @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:對話框不能在內建函式的回呼、getter、轉換或 $.evalFile 執行的檔案中開啟;請從指令碼本身的程式碼呼叫 @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}:`answers` 中的下一個回答是給 {_1} 的,而不是給 {name} 的 @msg {name}: `answers` has no answer left for this dialog {name}:`answers` 中已沒有此對話框的回答 +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` 中有 {n} 個指令碼未使用的回答 +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} 未變更筆刷下的 {n} 個物件({_2}):它只重塑路徑 @msg vc.document{place} is too large for a script vc.document{place}對指令碼來說太大 @msg vc.log: the log of this run is full vc.log:本次執行的記錄已滿 @msg this function's script run has ended 此函式的指令碼執行已結束 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 296bd84b2b..36a605c317 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -921,6 +921,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The errors of the 3D effects (Extrude & Bevel, Revolve, Inflate, Rotate and their Classic forms) show in the status bar in the interface language: the art a 3D effect cannot build a solid from, invalid light, graphics and surface settings, and the notes for an object that draws no 3D faces or more wireframe edges than the limit. Each has a row in every catalog that translates all status and error messages, and the effect's name and the values in the message are translated or kept as written (`three_d_refusals_are_translated_in_every_complete_catalog`, `three_d_refusals_translate_with_their_values`). - The errors of the parameter checks that many commands share show in the status bar in the interface language: a value that is not a number where a number goes (`object.move` with `"dx": "60 mm"`, and `object.rotate`, `object.setBounds` and the other commands that call `check_numbers`), a missing number or index, `ids` that are not a list of object ids, an object id that is not a non-negative integer or names no object, and a date that is not Unix seconds. Each has a row in every catalog that translates all status and error messages, and in Bulgarian, Danish, Indonesian and Dutch (`shared_param_check_errors_are_translated`). - A parameter schema's errors show in the status bar with what the value must be in the interface language, for every type a schema has (a number with each kind of range and with a unit, an integer and its range, true or false, a string, a list of names, an object id, a list of object ids, a color, a point, an object and a list), in every catalog that translates all status and error messages; the path, the refused value, the bounds, the unit and the names stay as the English gives them. The error for a value that is not one of its names is also translated in Bulgarian, Bosnian, Danish, Indonesian and Dutch (`parameter_schema_expected_phrases_are_translated`, `bracketed_message_parts_translate_only_as_exact_messages`). + - A script's error about answers in `answers` that it did not use, and Liquify's warning about the objects under the brush that it left as they were, show in the status bar in the interface language for one answer or object as well as for several, with the count's own form in each catalog that translates all status and error messages; the English the commands return stays as it was (`messages_with_one_or_several_items_translate_in_every_complete_catalog`, `unused_answers_are_counted_in_the_singular_and_the_plural`, `liquify_warns_about_one_or_several_skipped_objects`). - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate_and_schema_phrase`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and warn about a key that only another format takes (`{"format": "pdf", "quality": 80}` writes the PDF with the warning "`quality` was not used: PDF files don't read it"; `an_option_only_another_format_reads_gets_a_note`, `control_export_notes_an_option_the_format_does_not_read`, `convert_warns_about_an_unused_option_only_when_one_was_given`), and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. - Save commands run through MCP, the control channel or the CLI (`document.save`, `file.saveAs`, `file.saveCopy`, `file.saveAsTemplate`, `app.save`) refuse a key that no save format takes, beside the path or in `options`. Export for Screens refuses a key it doesn't take, and a key that no format takes in a format row or in a format's settings, by its path (`formats[1].marks.useDocumentBleed`); Export Assets (`assets.export`, `assets.settings.set`) checks the rows and settings it is given the same way. From ef742ccb2af1e7869ce181e49456108a27c9a6d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 22:08:33 -0800 Subject: [PATCH 02/41] i18n: custom toolbar command errors are translated in every complete-message catalog The status bar showed the errors of the toolbars made with New Toolbar in English in 15 of the complete-message languages (cs, el, es, fr, hu, ja, ka, ko, ru, vi, zh-hant, fi, tr, ca, nl), and the errors that window.toolbar.dock gives for a side that is not a string and for an order out of range in those and in hi and sv. The message scan already lists these templates; the untranslated-strings report only prints missing rows, so nothing failed. - Every complete-message catalog has a row for each error: a missing, empty, too long or taken toolbar name, a name or toolbar that is not a string, a missing new name, the 64-toolbar limit, and the dock command's side and order. The toolbar's name, the parameter key and the value given are kept as they are; the error the command returns stays English. Test: i18n::tests::custom_toolbar_command_errors_are_translated. --- crates/ui-egui/src/i18n/ca.tsv | 13 ++++ crates/ui-egui/src/i18n/cs.tsv | 13 ++++ crates/ui-egui/src/i18n/el.tsv | 13 ++++ crates/ui-egui/src/i18n/es.tsv | 13 ++++ crates/ui-egui/src/i18n/fi.tsv | 13 ++++ crates/ui-egui/src/i18n/fr.tsv | 13 ++++ crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 13 ++++ crates/ui-egui/src/i18n/ja.tsv | 13 ++++ crates/ui-egui/src/i18n/ka.tsv | 13 ++++ crates/ui-egui/src/i18n/ko.tsv | 13 ++++ crates/ui-egui/src/i18n/nl.tsv | 13 ++++ crates/ui-egui/src/i18n/ru.tsv | 13 ++++ crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tests.rs | 92 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 13 ++++ crates/ui-egui/src/i18n/vi.tsv | 13 ++++ crates/ui-egui/src/i18n/zh-hant.tsv | 13 ++++ docs/target-app-parity.md | 1 + 19 files changed, 292 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 373eb0b79d..e7a1c105fb 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7389,6 +7389,19 @@ breakText Glyphs Glifs Not Aligned to Pixel Grid No alineat a la quadrícula de píxels @msg only paths and compound paths can be aligned to the pixel grid només els traçats i els traçats compostos es poden alinear a la quadrícula de píxels @msg side is left or right, not `{s}` side ha de ser left o right, no `{s}` +@msg side is left or right, not `{v}` side ha de ser left o right, no `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order ha de ser un nombre enter de 0 a {others}, no `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (el nom d’una barra d’eines) ha de ser una cadena +@msg no toolbar named `{name}` no hi ha cap barra d’eines anomenada `{name}` +@msg toolbar name can't be empty el nom de la barra d’eines no pot ser buit +@msg a toolbar name has at most {MAX_NAME} characters un nom de barra d’eines té com a màxim {MAX_NAME} caràcters +@msg there is already a toolbar named `{name}` ja hi ha una barra d’eines anomenada `{name}` +@msg there is already a toolbar named `{to}` ja hi ha una barra d’eines anomenada `{to}` +@msg a workspace keeps at most {MAX} toolbars un espai de treball conté com a màxim {MAX} barres d’eines +@msg name (a toolbar's name) must be a string name (el nom d’una barra d’eines) ha de ser una cadena +@msg name (a toolbar's name) is required cal name (el nom d’una barra d’eines) +@msg to (the new name) is required cal to (el nom nou) +@msg name must be a toolbar's name name ha de ser el nom d’una barra d’eines Ignore All Ignora-ho tot Add to Dictionary Afegeix al diccionari No Suggestions No hi ha suggeriments diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7178be3143..ef9f0764b0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7408,6 +7408,19 @@ breakText Glyphs Glyfy Not Aligned to Pixel Grid Nezarovnané na mřížku obrazových bodů @msg only paths and compound paths can be aligned to the pixel grid na mřížku obrazových bodů lze zarovnat jen cesty a složené cesty @msg side is left or right, not `{s}` side je left nebo right, ne `{s}` +@msg side is left or right, not `{v}` side je left nebo right, ne `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order je celé číslo od 0 do {others}, ne `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (název panelu nástrojů) musí být řetězec +@msg no toolbar named `{name}` panel nástrojů s názvem `{name}` neexistuje +@msg toolbar name can't be empty název panelu nástrojů nesmí být prázdný +@msg a toolbar name has at most {MAX_NAME} characters název panelu nástrojů má nejvýše {MAX_NAME} znaků +@msg there is already a toolbar named `{name}` panel nástrojů s názvem `{name}` už existuje +@msg there is already a toolbar named `{to}` panel nástrojů s názvem `{to}` už existuje +@msg a workspace keeps at most {MAX} toolbars pracovní prostor obsahuje nejvýše {MAX} panelů nástrojů +@msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec +@msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné +@msg to (the new name) is required to (nový název) je povinné +@msg name must be a toolbar's name name musí být název panelu nástrojů Ignore All Ignorovat vše Add to Dictionary Přidat do slovníku No Suggestions Žádné návrhy diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 62e3adc491..afd25adaab 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7361,6 +7361,19 @@ breakText Glyphs Γλύφοι Not Aligned to Pixel Grid Μη στοιχισμένα στο πλέγμα εικονοστοιχείων @msg only paths and compound paths can be aligned to the pixel grid μόνο διαδρομές και σύνθετες διαδρομές μπορούν να στοιχιστούν στο πλέγμα εικονοστοιχείων @msg side is left or right, not `{s}` το side είναι left ή right, όχι `{s}` +@msg side is left or right, not `{v}` το side είναι left ή right, όχι `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` το order είναι ακέραιος αριθμός από 0 έως {others}, όχι `{v}` +@msg toolbar (a toolbar's name) must be a string το toolbar (το όνομα μιας γραμμής εργαλείων) πρέπει να είναι συμβολοσειρά +@msg no toolbar named `{name}` δεν υπάρχει γραμμή εργαλείων με όνομα `{name}` +@msg toolbar name can't be empty το όνομα της γραμμής εργαλείων δεν μπορεί να είναι κενό +@msg a toolbar name has at most {MAX_NAME} characters ένα όνομα γραμμής εργαλείων έχει το πολύ {MAX_NAME} χαρακτήρες +@msg there is already a toolbar named `{name}` υπάρχει ήδη γραμμή εργαλείων με όνομα `{name}` +@msg there is already a toolbar named `{to}` υπάρχει ήδη γραμμή εργαλείων με όνομα `{to}` +@msg a workspace keeps at most {MAX} toolbars ένας χώρος εργασίας κρατά το πολύ {MAX} γραμμές εργαλείων +@msg name (a toolbar's name) must be a string το name (το όνομα μιας γραμμής εργαλείων) πρέπει να είναι συμβολοσειρά +@msg name (a toolbar's name) is required απαιτείται το name (το όνομα μιας γραμμής εργαλείων) +@msg to (the new name) is required απαιτείται το to (το νέο όνομα) +@msg name must be a toolbar's name το name πρέπει να είναι όνομα γραμμής εργαλείων Ignore All Παράβλεψη όλων Add to Dictionary Προσθήκη στο λεξικό No Suggestions Καμία πρόταση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d1c6aa53af..b08fda6002 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7352,6 +7352,19 @@ breakText Glyphs Glifos Not Aligned to Pixel Grid No alineado con cuadrícula de píxeles @msg only paths and compound paths can be aligned to the pixel grid solo los trazados y los trazados compuestos se pueden alinear con la cuadrícula de píxeles @msg side is left or right, not `{s}` side es left o right, no `{s}` +@msg side is left or right, not `{v}` side es left o right, no `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order es un número entero de 0 a {others}, no `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (el nombre de una barra de herramientas) debe ser una cadena de texto +@msg no toolbar named `{name}` no hay ninguna barra de herramientas llamada `{name}` +@msg toolbar name can't be empty el nombre de la barra de herramientas no puede estar vacío +@msg a toolbar name has at most {MAX_NAME} characters el nombre de una barra de herramientas tiene como máximo {MAX_NAME} caracteres +@msg there is already a toolbar named `{name}` ya hay una barra de herramientas llamada `{name}` +@msg there is already a toolbar named `{to}` ya hay una barra de herramientas llamada `{to}` +@msg a workspace keeps at most {MAX} toolbars un espacio de trabajo guarda como máximo {MAX} barras de herramientas +@msg name (a toolbar's name) must be a string name (el nombre de una barra de herramientas) debe ser una cadena de texto +@msg name (a toolbar's name) is required Se requiere name (el nombre de una barra de herramientas) +@msg to (the new name) is required Se requiere to (el nuevo nombre) +@msg name must be a toolbar's name name debe ser el nombre de una barra de herramientas Ignore All Omitir todo Add to Dictionary Añadir al diccionario No Suggestions No hay sugerencias diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 45e47fd355..8b6189b4fe 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7443,6 +7443,19 @@ breakText Glyphs Merkit Not Aligned to Pixel Grid Ei tasattu pikseliruudukkoon @msg only paths and compound paths can be aligned to the pixel grid vain polut ja yhdistelmäpolut voi tasata pikseliruudukkoon @msg side is left or right, not `{s}` side on left tai right, ei `{s}` +@msg side is left or right, not `{v}` side on left tai right, ei `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order on kokonaisluku, vähintään 0 ja enintään {others}, ei `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar-arvon (työkalurivin nimi) on oltava merkkijono +@msg no toolbar named `{name}` ei työkaluriviä nimeltä `{name}` +@msg toolbar name can't be empty työkalurivin nimi ei voi olla tyhjä +@msg a toolbar name has at most {MAX_NAME} characters työkalurivin nimessä on enintään {MAX_NAME} merkkiä +@msg there is already a toolbar named `{name}` työkalurivi nimeltä `{name}` on jo olemassa +@msg there is already a toolbar named `{to}` työkalurivi nimeltä `{to}` on jo olemassa +@msg a workspace keeps at most {MAX} toolbars työtilassa on enintään {MAX} työkaluriviä +@msg name (a toolbar's name) must be a string name-arvon (työkalurivin nimi) on oltava merkkijono +@msg name (a toolbar's name) is required name (työkalurivin nimi) vaaditaan +@msg to (the new name) is required to (uusi nimi) vaaditaan +@msg name must be a toolbar's name name-arvon on oltava työkalurivin nimi Ignore All Ohita kaikki Add to Dictionary Lisää sanastoon No Suggestions Ei ehdotuksia diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 057dce6872..ab1251d972 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7403,6 +7403,19 @@ breakText Glyphs Glyphes Not Aligned to Pixel Grid Non aligné sur la grille de pixels @msg only paths and compound paths can be aligned to the pixel grid seuls les tracés et les tracés transparents peuvent être alignés sur la grille de pixels @msg side is left or right, not `{s}` side vaut left ou right, pas `{s}` +@msg side is left or right, not `{v}` side vaut left ou right, pas `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order est un nombre entier de 0 à {others}, pas `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (le nom d’une barre d’outils) doit être une chaîne de caractères +@msg no toolbar named `{name}` aucune barre d’outils nommée `{name}` +@msg toolbar name can't be empty le nom de la barre d’outils ne peut pas être vide +@msg a toolbar name has at most {MAX_NAME} characters un nom de barre d’outils compte au plus {MAX_NAME} caractères +@msg there is already a toolbar named `{name}` il existe déjà une barre d’outils nommée `{name}` +@msg there is already a toolbar named `{to}` il existe déjà une barre d’outils nommée `{to}` +@msg a workspace keeps at most {MAX} toolbars un espace de travail contient au plus {MAX} barres d’outils +@msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne de caractères +@msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est requis +@msg to (the new name) is required to (le nouveau nom) est requis +@msg name must be a toolbar's name name doit être le nom d’une barre d’outils Ignore All Tout ignorer Add to Dictionary Ajouter au dictionnaire No Suggestions Aucune suggestion diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9d056e085a..75007a8a94 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8799,6 +8799,8 @@ theme Appearance अपीयरेंस @msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` इंपोर्टर 1 से {MAX_EXTENSIONS} `extensions` घोषित करता है @msg an importer always gets an import's budget: leave `budget` out इंपोर्टर को हमेशा इंपोर्ट का बजट मिलता है: `budget` छोड़ दें @msg side is left or right, not `{s}` side left या right होना चाहिए, `{s}` नहीं +@msg side is left or right, not `{v}` side left या right होना चाहिए, `{v}` नहीं +@msg order is a whole number from 0 to {others}, not `{v}` order 0 से {others} तक की पूर्ण संख्या होनी चाहिए, `{v}` नहीं Ignore All सभी को अनदेखा करें Add to Dictionary शब्दकोश में जोड़ें No Suggestions कोई सुझाव नहीं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c2f1a52cd9..3c10d8b8e5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7392,6 +7392,19 @@ breakText Glyphs Glifák Not Aligned to Pixel Grid Pixelrácshoz nem igazított @msg only paths and compound paths can be aligned to the pixel grid csak útvonalak és összetett útvonalak igazíthatók a pixelrácshoz @msg side is left or right, not `{s}` a side értéke left vagy right lehet, nem `{s}` +@msg side is left or right, not `{v}` a side értéke left vagy right lehet, nem `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` az order értéke 0 és {others} közötti egész szám lehet, nem `{v}` +@msg toolbar (a toolbar's name) must be a string a toolbar értéke (egy eszköztár neve) szöveg lehet +@msg no toolbar named `{name}` nincs ilyen nevű eszköztár: `{name}` +@msg toolbar name can't be empty az eszköztár neve nem lehet üres +@msg a toolbar name has at most {MAX_NAME} characters egy eszköztár neve legfeljebb {MAX_NAME} karakter lehet +@msg there is already a toolbar named `{name}` már van ilyen nevű eszköztár: `{name}` +@msg there is already a toolbar named `{to}` már van ilyen nevű eszköztár: `{to}` +@msg a workspace keeps at most {MAX} toolbars egy munkaterület legfeljebb {MAX} eszköztárat tartalmazhat +@msg name (a toolbar's name) must be a string a name értéke (egy eszköztár neve) szöveg lehet +@msg name (a toolbar's name) is required a name (egy eszköztár neve) kötelező +@msg to (the new name) is required a to (az új név) kötelező +@msg name must be a toolbar's name a name értéke egy eszköztár neve lehet Ignore All Az összes kihagyása Add to Dictionary Hozzáadás a szótárhoz No Suggestions Nincs javaslat diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 71de1ce91c..6b92f126d6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7104,6 +7104,19 @@ breakText Glyphs 字形 Not Aligned to Pixel Grid ピクセルグリッドに未整合 @msg only paths and compound paths can be aligned to the pixel grid ピクセルグリッドに整合できるのはパスと複合パスのみです @msg side is left or right, not `{s}` side は left または right です(`{s}` ではありません) +@msg side is left or right, not `{v}` side は left または right です(`{v}` ではありません) +@msg order is a whole number from 0 to {others}, not `{v}` order は 0 から {others} までの整数です(`{v}` ではありません) +@msg toolbar (a toolbar's name) must be a string toolbar(ツールバーの名前)は文字列にしてください +@msg no toolbar named `{name}` `{name}` という名前のツールバーが見つかりません +@msg toolbar name can't be empty ツールバー名を空にすることはできません +@msg a toolbar name has at most {MAX_NAME} characters ツールバー名は {MAX_NAME} 文字以内です +@msg there is already a toolbar named `{name}` `{name}` という名前のツールバーはすでにあります +@msg there is already a toolbar named `{to}` `{to}` という名前のツールバーはすでにあります +@msg a workspace keeps at most {MAX} toolbars ワークスペースに置けるツールバーは {MAX} 個までです +@msg name (a toolbar's name) must be a string name(ツールバーの名前)は文字列にしてください +@msg name (a toolbar's name) is required name(ツールバーの名前)を指定してください +@msg to (the new name) is required to(新しい名前)を指定してください +@msg name must be a toolbar's name name はツールバーの名前にしてください Ignore All すべて無視 Add to Dictionary 辞書に追加 No Suggestions 候補なし diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2cff51d94b..b611f62514 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7517,6 +7517,19 @@ font-script Japanese იაპონური Not Aligned to Pixel Grid პიქსელურ ბადეზე გაუსწორებელი @msg only paths and compound paths can be aligned to the pixel grid პიქსელურ ბადეზე მხოლოდ ტრაექტორიების და შედგენილი ტრაექტორიების გასწორებაა შესაძლებელი @msg side is left or right, not `{s}` side არის left ან right და არა `{s}` +@msg side is left or right, not `{v}` side არის left ან right და არა `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order არის მთელი რიცხვი 0-დან {others}-მდე და არა `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს +@msg no toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` არ არის +@msg toolbar name can't be empty ხელსაწყოთა ზოლის სახელი ცარიელი ვერ იქნება +@msg a toolbar name has at most {MAX_NAME} characters ხელსაწყოთა ზოლის სახელში მაქსიმუმ {MAX_NAME} სიმბოლოა +@msg there is already a toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` უკვე არსებობს +@msg there is already a toolbar named `{to}` ხელსაწყოთა ზოლი სახელით `{to}` უკვე არსებობს +@msg a workspace keeps at most {MAX} toolbars სამუშაო სივრცე ინახავს მაქსიმუმ {MAX} ხელსაწყოთა ზოლს +@msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს +@msg name (a toolbar's name) is required name (ხელსაწყოთა ზოლის სახელი) აუცილებელია +@msg to (the new name) is required to (ახალი სახელი) აუცილებელია +@msg name must be a toolbar's name name ხელსაწყოთა ზოლის სახელი უნდა იყოს Ignore All ყველას იგნორირება Add to Dictionary ლექსიკონში დამატება No Suggestions შემოთავაზებები არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4715a413f4..58f76a7228 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6999,6 +6999,19 @@ breakText Glyphs 글리프 Not Aligned to Pixel Grid 픽셀 격자에 정렬되지 않음 @msg only paths and compound paths can be aligned to the pixel grid 패스와 컴파운드 패스만 픽셀 격자에 정렬할 수 있습니다 @msg side is left or right, not `{s}` side는 left 또는 right입니다(`{s}` 아님) +@msg side is left or right, not `{v}` side는 left 또는 right입니다(`{v}` 아님) +@msg order is a whole number from 0 to {others}, not `{v}` order는 0부터 {others}까지의 정수입니다(`{v}` 아님) +@msg toolbar (a toolbar's name) must be a string toolbar(도구 막대 이름)은 문자열이어야 합니다 +@msg no toolbar named `{name}` `{name}` 도구 막대가 없습니다 +@msg toolbar name can't be empty 도구 막대 이름은 비워 둘 수 없습니다 +@msg a toolbar name has at most {MAX_NAME} characters 도구 막대 이름은 최대 {MAX_NAME}자입니다 +@msg there is already a toolbar named `{name}` `{name}` 도구 막대가 이미 있습니다 +@msg there is already a toolbar named `{to}` `{to}` 도구 막대가 이미 있습니다 +@msg a workspace keeps at most {MAX} toolbars 작업 영역에는 도구 막대를 최대 {MAX}개까지 둘 수 있습니다 +@msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 +@msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 +@msg to (the new name) is required to(새 이름)가 필요합니다 +@msg name must be a toolbar's name name은 도구 막대 이름이어야 합니다 Ignore All 모두 무시 Add to Dictionary 사전에 추가 No Suggestions 제안 없음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 94957fb782..5991c9e12f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7445,6 +7445,19 @@ breakText Glyphs Glyphs Align New Objects to Pixel Grid Nieuwe objecten uitlijnen op pixelraster Not Aligned to Pixel Grid Niet uitgelijnd op pixelraster @msg side is left or right, not `{s}` side is left of right, niet `{s}` +@msg side is left or right, not `{v}` side is left of right, niet `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order is een geheel getal van 0 tot en met {others}, niet `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (de naam van een werkbalk) moet een string zijn +@msg no toolbar named `{name}` geen werkbalk met de naam `{name}` +@msg toolbar name can't be empty de naam van een werkbalk mag niet leeg zijn +@msg a toolbar name has at most {MAX_NAME} characters een werkbalknaam heeft hoogstens {MAX_NAME} tekens +@msg there is already a toolbar named `{name}` er is al een werkbalk met de naam `{name}` +@msg there is already a toolbar named `{to}` er is al een werkbalk met de naam `{to}` +@msg a workspace keeps at most {MAX} toolbars een werkruimte bevat hoogstens {MAX} werkbalken +@msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn +@msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist +@msg to (the new name) is required to (de nieuwe naam) is vereist +@msg name must be a toolbar's name name moet de naam van een werkbalk zijn Edit Custom Dictionary Aangepast woordenboek bewerken Entry: Item: # Script Console diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8dc8336089..9f6f7d71a2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7497,6 +7497,19 @@ shape Open Открытый Not Aligned to Pixel Grid Не выровненные по пиксельной сетке @msg only paths and compound paths can be aligned to the pixel grid по пиксельной сетке можно выровнять только контуры и составные контуры @msg side is left or right, not `{s}` side — это left или right, а не `{s}` +@msg side is left or right, not `{v}` side принимает значение left или right, а не `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order должен быть целым числом от 0 до {others}, а не `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (имя панели инструментов) должен быть строкой +@msg no toolbar named `{name}` нет панели инструментов с именем `{name}` +@msg toolbar name can't be empty имя панели инструментов не может быть пустым +@msg a toolbar name has at most {MAX_NAME} characters имя панели инструментов содержит не более {MAX_NAME} символов +@msg there is already a toolbar named `{name}` панель инструментов с именем `{name}` уже есть +@msg there is already a toolbar named `{to}` панель инструментов с именем `{to}` уже есть +@msg a workspace keeps at most {MAX} toolbars рабочая среда хранит не более {MAX} панелей инструментов +@msg name (a toolbar's name) must be a string name (имя панели инструментов) должен быть строкой +@msg name (a toolbar's name) is required Необходимо указать name (имя панели инструментов) +@msg to (the new name) is required Необходимо указать to (новое имя) +@msg name must be a toolbar's name name должен быть именем панели инструментов Ignore All Пропустить все Add to Dictionary Добавить в словарь No Suggestions Нет вариантов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cfb9d9734b..355a08e109 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8846,6 +8846,8 @@ digits Hindi Hindi Not Aligned to Pixel Grid Inte justerade mot pixelrutnät @msg only paths and compound paths can be aligned to the pixel grid bara banor och sammansatta banor kan justeras mot pixelrutnätet @msg side is left or right, not `{s}` side är left eller right, inte `{s}` +@msg side is left or right, not `{v}` side är left eller right, inte `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order är ett heltal från 0 till {others}, inte `{v}` Ignore All Ignorera alla Add to Dictionary Lägg till i ordlistan No Suggestions Inga förslag diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 705fc68db2..5391732421 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3201,6 +3201,98 @@ fn wrongly_shaped_plugin_commands_errors_are_translated() { } } +/// The errors of the custom toolbar commands (Window › Toolbars, New Toolbar and Manage Toolbars, +/// `window.toolbar.dock` and `window.toolbar.float`) have an `@msg` row in every complete-message +/// catalog, and the status bar shows each one in the interface language with the toolbar's name, +/// the key and the values given kept; the error the command returns stays English. +#[test] +fn custom_toolbar_command_errors_are_translated() { + use serde_json::json; + let scanned = message_literals(); + let templates = [ + "toolbar (a toolbar's name) must be a string", + "no toolbar named `{name}`", + "toolbar name can't be empty", + "a toolbar name has at most {MAX_NAME} characters", + "there is already a toolbar named `{name}`", + "there is already a toolbar named `{to}`", + "a workspace keeps at most {MAX} toolbars", + "name (a toolbar's name) must be a string", + "name (a toolbar's name) is required", + "to (the new name) is required", + "name must be a toolbar's name", + "side is left or right, not `{s}`", + "side is left or right, not `{v}`", + "order is a whole number from 0 to {others}, not `{v}`", + "no dialog open", + "`{key}` must be true or false", + "x and y must both be numbers", + ]; + for template in templates { + assert!(scanned.contains(template), "the scan lists {template}"); + } + let mut missing = vec![]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: std::collections::BTreeSet<&str> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, _)| src.as_str()).collect(); + missing.extend(templates.iter().filter(|t| !rows.contains(*t)).map(|t| format!("{code}: {t}"))); + } + assert!(missing.is_empty(), "{} toolbar errors have no @msg row:\n{}", missing.len(), missing.join("\n")); + + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + for name in ["Mine", "Pens"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + app.run("window.toolbar.dock", json!({"name": "Pens", "side": "left"})).unwrap(); + let cases = [ + ("window.toolbar.new", json!({"name": 5}), "name (a toolbar's name) must be a string", vec![]), + ("window.toolbar.new", json!({"name": " "}), "toolbar name can't be empty", vec![]), + ("window.toolbar.new", json!({"name": "x".repeat(201)}), "a toolbar name has at most 200 characters", vec!["200"]), + ("window.toolbar.new", json!({"name": "Mine"}), "there is already a toolbar named `Mine`", vec!["`Mine`"]), + ("window.toolbar.rename", json!({"name": "Mine", "to": "Pens"}), "there is already a toolbar named `Pens`", vec!["`Pens`"]), + ("window.toolbar.rename", json!({"name": "Mine"}), "to (the new name) is required", vec![]), + ("window.toolbar.custom", json!({}), "name (a toolbar's name) is required", vec![]), + ("window.toolbar.custom", json!({"name": "Nope"}), "no toolbar named `Nope`", vec!["`Nope`"]), + ("window.toolbar.custom", json!({"name": "Mine", "show": "yes"}), "`show` must be true or false", vec!["`show`"]), + ("window.toolbar.duplicate", json!({"name": 3}), "name must be a toolbar's name", vec![]), + ("toolbar.addTool", json!({"tool": "pen", "toolbar": 5}), "toolbar (a toolbar's name) must be a string", vec![]), + ("window.toolbar.dock", json!({"name": "Mine", "side": "up"}), "side is left or right, not `up`", vec!["`up`"]), + ("window.toolbar.dock", json!({"name": "Mine", "side": 3}), "side is left or right, not `3`", vec!["`3`"]), + ( + "window.toolbar.dock", + json!({"name": "Mine", "side": "left", "order": 9}), + "order is a whole number from 0 to 1, not `9`", + vec!["1", "`9`"], + ), + ("window.toolbar.float", json!({"name": "Mine", "x": "a", "y": 1}), "x and y must both be numbers", vec![]), + ]; + let mut errors: Vec<(String, Vec<&str>)> = vec![]; + for (id, params, want, kept) in cases { + let e = app.run(id, params.clone()).unwrap_err(); + assert_eq!(e, want, "{id} {params}"); + errors.push((e, kept)); + } + // New Toolbar's OK with no dialog open, and a workspace that holds as many toolbars as it keeps. + errors.push((crate::custom_toolbars::confirm(&mut app).unwrap_err(), vec![])); + for i in app.ui.custom_toolbars.len()..crate::custom_toolbars::MAX { + app.run("window.toolbar.new", json!({ "name": format!("T{i}") })).unwrap(); + } + for (id, params) in [("window.toolbar.new", json!({"name": "Extra"})), ("window.toolbar.duplicate", json!({"name": "Mine"}))] { + let e = app.run(id, params).unwrap_err(); + assert_eq!(e, "a workspace keeps at most 64 toolbars", "{id}"); + errors.push((e, vec!["64"])); + } + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for (e, kept) in &errors { + let shown = message(lang, e); + assert_ne!(shown, *e, "{code}: shown in English"); + assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {e} -> {shown}"); + } + } +} + /// The warnings of an Image Trace with keepColors, which the status bar shows and the scan above /// doesn't read, are translated in each language of [`COMPLETE_MESSAGES`], with the colors kept. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2b3e843ba3..5aa7a15dc7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7364,6 +7364,19 @@ breakText Glyphs Glifler Not Aligned to Pixel Grid Piksel Izgarasına Hizalanmamış @msg only paths and compound paths can be aligned to the pixel grid piksel ızgarasına yalnızca yollar ve bileşik yollar hizalanabilir @msg side is left or right, not `{s}` side left veya right olmalıdır, `{s}` değil +@msg side is left or right, not `{v}` side left veya right olmalıdır, `{v}` değil +@msg order is a whole number from 0 to {others}, not `{v}` order 0 ile {others} arasında bir tam sayı olmalıdır, `{v}` değil +@msg toolbar (a toolbar's name) must be a string toolbar (bir araç çubuğunun adı) bir dize olmalıdır +@msg no toolbar named `{name}` `{name}` adlı araç çubuğu yok +@msg toolbar name can't be empty araç çubuğu adı boş olamaz +@msg a toolbar name has at most {MAX_NAME} characters bir araç çubuğu adı en fazla {MAX_NAME} karakter olabilir +@msg there is already a toolbar named `{name}` `{name}` adlı bir araç çubuğu zaten var +@msg there is already a toolbar named `{to}` `{to}` adlı bir araç çubuğu zaten var +@msg a workspace keeps at most {MAX} toolbars bir çalışma alanı en fazla {MAX} araç çubuğu tutar +@msg name (a toolbar's name) must be a string name (bir araç çubuğunun adı) bir dize olmalıdır +@msg name (a toolbar's name) is required name (bir araç çubuğunun adı) gerekli +@msg to (the new name) is required to (yeni ad) gerekli +@msg name must be a toolbar's name name bir araç çubuğunun adı olmalıdır Ignore All Tümünü Yoksay Add to Dictionary Sözlüğe Ekle No Suggestions Öneri Yok diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d8469bce53..ebc22ed778 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7019,6 +7019,19 @@ breakText Glyphs Glyph Not Aligned to Pixel Grid Chưa căn theo lưới pixel @msg only paths and compound paths can be aligned to the pixel grid chỉ đường dẫn và đường dẫn phức mới căn theo lưới pixel được @msg side is left or right, not `{s}` side là left hoặc right, không phải `{s}` +@msg side is left or right, not `{v}` side là left hoặc right, không phải `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order là số nguyên từ 0 đến {others}, không phải `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (tên một thanh công cụ) phải là chuỗi +@msg no toolbar named `{name}` không có thanh công cụ tên `{name}` +@msg toolbar name can't be empty tên thanh công cụ không được để trống +@msg a toolbar name has at most {MAX_NAME} characters tên thanh công cụ có tối đa {MAX_NAME} ký tự +@msg there is already a toolbar named `{name}` đã có thanh công cụ tên `{name}` +@msg there is already a toolbar named `{to}` đã có thanh công cụ tên `{to}` +@msg a workspace keeps at most {MAX} toolbars một không gian làm việc giữ tối đa {MAX} thanh công cụ +@msg name (a toolbar's name) must be a string name (tên một thanh công cụ) phải là chuỗi +@msg name (a toolbar's name) is required name (tên một thanh công cụ) là bắt buộc +@msg to (the new name) is required to (tên mới) là bắt buộc +@msg name must be a toolbar's name name phải là tên của một thanh công cụ Ignore All Bỏ qua tất cả Add to Dictionary Thêm vào từ điển No Suggestions Không có gợi ý diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a0d987fe69..901c15e451 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7057,6 +7057,19 @@ breakText Glyphs 字符 Not Aligned to Pixel Grid 未對齊像素格點 @msg only paths and compound paths can be aligned to the pixel grid 只有路徑和複合路徑可以對齊像素格點 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` +@msg side is left or right, not `{v}` side 應為 left 或 right,而不是 `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order 應為 0 到 {others} 之間的整數,而不是 `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (工具列的名稱) 必須是字串 +@msg no toolbar named `{name}` 沒有名為 `{name}` 的工具列 +@msg toolbar name can't be empty 工具列名稱不能是空的 +@msg a toolbar name has at most {MAX_NAME} characters 工具列名稱最多 {MAX_NAME} 個字元 +@msg there is already a toolbar named `{name}` 已經有名為 `{name}` 的工具列 +@msg there is already a toolbar named `{to}` 已經有名為 `{to}` 的工具列 +@msg a workspace keeps at most {MAX} toolbars 一個工作區最多保留 {MAX} 個工具列 +@msg name (a toolbar's name) must be a string name (工具列的名稱) 必須是字串 +@msg name (a toolbar's name) is required 需要 name (工具列的名稱) +@msg to (the new name) is required 需要 to (新名稱) +@msg name must be a toolbar's name name 必須是工具列的名稱 Edit Custom Dictionary 編輯自訂字典 Entry: 項目: # Script Console diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 296bd84b2b..4d684612e3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -882,6 +882,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). + - The status bar shows the errors of the toolbars made with New Toolbar (a missing, empty, too long or taken name, the 64-toolbar limit, a `side` or `order` that `window.toolbar.dock` does not take, and New Toolbar's dialog and Manage Toolbars) in every language that translates every message, with the toolbar's name, the parameter key and the value given kept as they are; the error the command returns stays English (`custom_toolbar_command_errors_are_translated`). - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. From c7e6b5426e0e3b8025a7dbe6383c26dc6c901f87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:26:52 -0800 Subject: [PATCH 03/41] i18n: drop toolbar rows that main already has Main added the custom toolbar messages to the cs, fr, ko, nl and zh-hant catalogs, so the branch's copies of the same 13 rows in each are removed. --- crates/ui-egui/src/i18n/cs.tsv | 13 ------------- crates/ui-egui/src/i18n/fr.tsv | 13 ------------- crates/ui-egui/src/i18n/ko.tsv | 13 ------------- crates/ui-egui/src/i18n/nl.tsv | 13 ------------- crates/ui-egui/src/i18n/zh-hant.tsv | 13 ------------- 5 files changed, 65 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f0e677e551..d95879fc03 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7417,19 +7417,6 @@ breakText Glyphs Glyfy Not Aligned to Pixel Grid Nezarovnané na mřížku obrazových bodů @msg only paths and compound paths can be aligned to the pixel grid na mřížku obrazových bodů lze zarovnat jen cesty a složené cesty @msg side is left or right, not `{s}` side je left nebo right, ne `{s}` -@msg side is left or right, not `{v}` side je left nebo right, ne `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order je celé číslo od 0 do {others}, ne `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (název panelu nástrojů) musí být řetězec -@msg no toolbar named `{name}` panel nástrojů s názvem `{name}` neexistuje -@msg toolbar name can't be empty název panelu nástrojů nesmí být prázdný -@msg a toolbar name has at most {MAX_NAME} characters název panelu nástrojů má nejvýše {MAX_NAME} znaků -@msg there is already a toolbar named `{name}` panel nástrojů s názvem `{name}` už existuje -@msg there is already a toolbar named `{to}` panel nástrojů s názvem `{to}` už existuje -@msg a workspace keeps at most {MAX} toolbars pracovní prostor obsahuje nejvýše {MAX} panelů nástrojů -@msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec -@msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné -@msg to (the new name) is required to (nový název) je povinné -@msg name must be a toolbar's name name musí být název panelu nástrojů Ignore All Ignorovat vše Add to Dictionary Přidat do slovníku No Suggestions Žádné návrhy diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 579cc008b1..3dfd5ad5d9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7412,19 +7412,6 @@ breakText Glyphs Glyphes Not Aligned to Pixel Grid Non aligné sur la grille de pixels @msg only paths and compound paths can be aligned to the pixel grid seuls les tracés et les tracés transparents peuvent être alignés sur la grille de pixels @msg side is left or right, not `{s}` side vaut left ou right, pas `{s}` -@msg side is left or right, not `{v}` side vaut left ou right, pas `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order est un nombre entier de 0 à {others}, pas `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (le nom d’une barre d’outils) doit être une chaîne de caractères -@msg no toolbar named `{name}` aucune barre d’outils nommée `{name}` -@msg toolbar name can't be empty le nom de la barre d’outils ne peut pas être vide -@msg a toolbar name has at most {MAX_NAME} characters un nom de barre d’outils compte au plus {MAX_NAME} caractères -@msg there is already a toolbar named `{name}` il existe déjà une barre d’outils nommée `{name}` -@msg there is already a toolbar named `{to}` il existe déjà une barre d’outils nommée `{to}` -@msg a workspace keeps at most {MAX} toolbars un espace de travail contient au plus {MAX} barres d’outils -@msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne de caractères -@msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est requis -@msg to (the new name) is required to (le nouveau nom) est requis -@msg name must be a toolbar's name name doit être le nom d’une barre d’outils Ignore All Tout ignorer Add to Dictionary Ajouter au dictionnaire No Suggestions Aucune suggestion diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a694df6890..8af8d3f53d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7008,19 +7008,6 @@ breakText Glyphs 글리프 Not Aligned to Pixel Grid 픽셀 격자에 정렬되지 않음 @msg only paths and compound paths can be aligned to the pixel grid 패스와 컴파운드 패스만 픽셀 격자에 정렬할 수 있습니다 @msg side is left or right, not `{s}` side는 left 또는 right입니다(`{s}` 아님) -@msg side is left or right, not `{v}` side는 left 또는 right입니다(`{v}` 아님) -@msg order is a whole number from 0 to {others}, not `{v}` order는 0부터 {others}까지의 정수입니다(`{v}` 아님) -@msg toolbar (a toolbar's name) must be a string toolbar(도구 막대 이름)은 문자열이어야 합니다 -@msg no toolbar named `{name}` `{name}` 도구 막대가 없습니다 -@msg toolbar name can't be empty 도구 막대 이름은 비워 둘 수 없습니다 -@msg a toolbar name has at most {MAX_NAME} characters 도구 막대 이름은 최대 {MAX_NAME}자입니다 -@msg there is already a toolbar named `{name}` `{name}` 도구 막대가 이미 있습니다 -@msg there is already a toolbar named `{to}` `{to}` 도구 막대가 이미 있습니다 -@msg a workspace keeps at most {MAX} toolbars 작업 영역에는 도구 막대를 최대 {MAX}개까지 둘 수 있습니다 -@msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 -@msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 -@msg to (the new name) is required to(새 이름)가 필요합니다 -@msg name must be a toolbar's name name은 도구 막대 이름이어야 합니다 Ignore All 모두 무시 Add to Dictionary 사전에 추가 No Suggestions 제안 없음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d83896807d..c8b777d01b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9272,19 +9272,6 @@ breakText Glyphs Glyphs Align New Objects to Pixel Grid Nieuwe objecten uitlijnen op pixelraster Not Aligned to Pixel Grid Niet uitgelijnd op pixelraster @msg side is left or right, not `{s}` side is left of right, niet `{s}` -@msg side is left or right, not `{v}` side is left of right, niet `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order is een geheel getal van 0 tot en met {others}, niet `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (de naam van een werkbalk) moet een string zijn -@msg no toolbar named `{name}` geen werkbalk met de naam `{name}` -@msg toolbar name can't be empty de naam van een werkbalk mag niet leeg zijn -@msg a toolbar name has at most {MAX_NAME} characters een werkbalknaam heeft hoogstens {MAX_NAME} tekens -@msg there is already a toolbar named `{name}` er is al een werkbalk met de naam `{name}` -@msg there is already a toolbar named `{to}` er is al een werkbalk met de naam `{to}` -@msg a workspace keeps at most {MAX} toolbars een werkruimte bevat hoogstens {MAX} werkbalken -@msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn -@msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist -@msg to (the new name) is required to (de nieuwe naam) is vereist -@msg name must be a toolbar's name name moet de naam van een werkbalk zijn Edit Custom Dictionary Aangepast woordenboek bewerken Entry: Item: # Script Console diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3a35d60161..264a252f18 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7067,19 +7067,6 @@ breakText Glyphs 字符 Not Aligned to Pixel Grid 未對齊像素格點 @msg only paths and compound paths can be aligned to the pixel grid 只有路徑和複合路徑可以對齊像素格點 @msg side is left or right, not `{s}` side 應為 left 或 right,而不是 `{s}` -@msg side is left or right, not `{v}` side 應為 left 或 right,而不是 `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order 應為 0 到 {others} 之間的整數,而不是 `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (工具列的名稱) 必須是字串 -@msg no toolbar named `{name}` 沒有名為 `{name}` 的工具列 -@msg toolbar name can't be empty 工具列名稱不能是空的 -@msg a toolbar name has at most {MAX_NAME} characters 工具列名稱最多 {MAX_NAME} 個字元 -@msg there is already a toolbar named `{name}` 已經有名為 `{name}` 的工具列 -@msg there is already a toolbar named `{to}` 已經有名為 `{to}` 的工具列 -@msg a workspace keeps at most {MAX} toolbars 一個工作區最多保留 {MAX} 個工具列 -@msg name (a toolbar's name) must be a string name (工具列的名稱) 必須是字串 -@msg name (a toolbar's name) is required 需要 name (工具列的名稱) -@msg to (the new name) is required 需要 to (新名稱) -@msg name must be a toolbar's name name 必須是工具列的名稱 Edit Custom Dictionary 編輯自訂字典 Entry: 項目: # Script Console From 37cb0e3f5b42bdb43fa73da6831152ec4d87ab78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:55:17 -0800 Subject: [PATCH 04/41] i18n: drop the ja and hu toolbar error rows that main now carries main added the same 13 custom-toolbar `@msg` rows to ja.tsv and hu.tsv, so the branch's copies made `bundled_catalogs_are_consistent` fail with a duplicate key. Keep main's rows and remove the branch's. --- crates/ui-egui/src/i18n/hu.tsv | 13 ------------- crates/ui-egui/src/i18n/ja.tsv | 13 ------------- 2 files changed, 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1f1bb6cd89..bea893c5ff 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7404,19 +7404,6 @@ breakText Glyphs Glifák Not Aligned to Pixel Grid Pixelrácshoz nem igazított @msg only paths and compound paths can be aligned to the pixel grid csak útvonalak és összetett útvonalak igazíthatók a pixelrácshoz @msg side is left or right, not `{s}` a side értéke left vagy right lehet, nem `{s}` -@msg side is left or right, not `{v}` a side értéke left vagy right lehet, nem `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` az order értéke 0 és {others} közötti egész szám lehet, nem `{v}` -@msg toolbar (a toolbar's name) must be a string a toolbar értéke (egy eszköztár neve) szöveg lehet -@msg no toolbar named `{name}` nincs ilyen nevű eszköztár: `{name}` -@msg toolbar name can't be empty az eszköztár neve nem lehet üres -@msg a toolbar name has at most {MAX_NAME} characters egy eszköztár neve legfeljebb {MAX_NAME} karakter lehet -@msg there is already a toolbar named `{name}` már van ilyen nevű eszköztár: `{name}` -@msg there is already a toolbar named `{to}` már van ilyen nevű eszköztár: `{to}` -@msg a workspace keeps at most {MAX} toolbars egy munkaterület legfeljebb {MAX} eszköztárat tartalmazhat -@msg name (a toolbar's name) must be a string a name értéke (egy eszköztár neve) szöveg lehet -@msg name (a toolbar's name) is required a name (egy eszköztár neve) kötelező -@msg to (the new name) is required a to (az új név) kötelező -@msg name must be a toolbar's name a name értéke egy eszköztár neve lehet Ignore All Az összes kihagyása Add to Dictionary Hozzáadás a szótárhoz No Suggestions Nincs javaslat diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6c4b6ff9c4..6b59f5a370 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8920,19 +8920,6 @@ breakText Glyphs 字形 Not Aligned to Pixel Grid ピクセルグリッドに未整合 @msg only paths and compound paths can be aligned to the pixel grid ピクセルグリッドに整合できるのはパスと複合パスのみです @msg side is left or right, not `{s}` side は left または right です(`{s}` ではありません) -@msg side is left or right, not `{v}` side は left または right です(`{v}` ではありません) -@msg order is a whole number from 0 to {others}, not `{v}` order は 0 から {others} までの整数です(`{v}` ではありません) -@msg toolbar (a toolbar's name) must be a string toolbar(ツールバーの名前)は文字列にしてください -@msg no toolbar named `{name}` `{name}` という名前のツールバーが見つかりません -@msg toolbar name can't be empty ツールバー名を空にすることはできません -@msg a toolbar name has at most {MAX_NAME} characters ツールバー名は {MAX_NAME} 文字以内です -@msg there is already a toolbar named `{name}` `{name}` という名前のツールバーはすでにあります -@msg there is already a toolbar named `{to}` `{to}` という名前のツールバーはすでにあります -@msg a workspace keeps at most {MAX} toolbars ワークスペースに置けるツールバーは {MAX} 個までです -@msg name (a toolbar's name) must be a string name(ツールバーの名前)は文字列にしてください -@msg name (a toolbar's name) is required name(ツールバーの名前)を指定してください -@msg to (the new name) is required to(新しい名前)を指定してください -@msg name must be a toolbar's name name はツールバーの名前にしてください Ignore All すべて無視 Add to Dictionary 辞書に追加 No Suggestions 候補なし From 1bbca6efb5d5c21412bc6b3ff8c32a8acff9b1b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:17:16 -0800 Subject: [PATCH 05/41] i18n: Danish rows for unused-answers and Liquify skip messages --- crates/ui-egui/src/i18n/da.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..6f708cdeca 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -131,6 +131,8 @@ @msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en dialog kan ikke åbne i et tilbagekald fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode @msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: det næste svar i `answers` er til {_1}, ikke til {name} @msg {name}: `answers` has no answer left for this dialog {name}: `answers` har intet svar tilbage til denne dialog +@msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` har {n} svar, som scriptet ikke brugte|`answers` har {n} svar, som scriptet ikke brugte +@msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} lod {n} objekt under penslen være uændret ({_2}): det omformer kun kurver|{_1} lod {n} objekter under penslen være uændrede ({_2}): det omformer kun kurver @msg vc.document{place} is too large for a script vc.document{place} er for stort til et script @msg vc.log: the log of this run is full vc.log: loggen for denne kørsel er fuld @msg this function's script run has ended denne funktions scriptkørsel er afsluttet From 7e2246f6d44ccce605175cb9e448dcddc577182d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:26:01 -0800 Subject: [PATCH 06/41] i18n: Danish rows for the custom toolbar errors --- crates/ui-egui/src/i18n/da.tsv | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..5c3dd27d34 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7457,6 +7457,19 @@ breakText Glyphs Glyffer Align New Objects to Pixel Grid Juster nye objekter efter pixelgitter Not Aligned to Pixel Grid Ikke justeret efter pixelgitter @msg side is left or right, not `{s}` side er left eller right, ikke `{s}` +@msg side is left or right, not `{v}` side er left eller right, ikke `{v}` +@msg order is a whole number from 0 to {others}, not `{v}` order er et heltal fra 0 til {others}, ikke `{v}` +@msg toolbar (a toolbar's name) must be a string toolbar (navnet på en værktøjslinje) skal være en streng +@msg no toolbar named `{name}` ingen værktøjslinje med navnet `{name}` +@msg toolbar name can't be empty navnet på en værktøjslinje må ikke være tomt +@msg a toolbar name has at most {MAX_NAME} characters navnet på en værktøjslinje har højst {MAX_NAME} tegn +@msg there is already a toolbar named `{name}` der findes allerede en værktøjslinje med navnet `{name}` +@msg there is already a toolbar named `{to}` der findes allerede en værktøjslinje med navnet `{to}` +@msg a workspace keeps at most {MAX} toolbars et arbejdsområde gemmer højst {MAX} værktøjslinjer +@msg name (a toolbar's name) must be a string name (navnet på en værktøjslinje) skal være en streng +@msg name (a toolbar's name) is required name (navnet på en værktøjslinje) er påkrævet +@msg to (the new name) is required to (det nye navn) er påkrævet +@msg name must be a toolbar's name name skal være navnet på en værktøjslinje Edit Custom Dictionary Redigér egen ordliste Entry: Opslag: # Script Console From 80d82612bdc164d21085f3476c02fb39b7b26416 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:43:20 -0800 Subject: [PATCH 07/41] i18n: drop the tr toolbar error rows that main now carries main added Turkish rows for the custom toolbar command errors, so the branch's copies made bundled_catalogs_are_consistent fail on a duplicate @msg row. --- crates/ui-egui/src/i18n/tr.tsv | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6a197927d6..4a6b37a170 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9316,19 +9316,6 @@ breakText Glyphs Glifler Not Aligned to Pixel Grid Piksel Izgarasına Hizalanmamış @msg only paths and compound paths can be aligned to the pixel grid piksel ızgarasına yalnızca yollar ve bileşik yollar hizalanabilir @msg side is left or right, not `{s}` side left veya right olmalıdır, `{s}` değil -@msg side is left or right, not `{v}` side left veya right olmalıdır, `{v}` değil -@msg order is a whole number from 0 to {others}, not `{v}` order 0 ile {others} arasında bir tam sayı olmalıdır, `{v}` değil -@msg toolbar (a toolbar's name) must be a string toolbar (bir araç çubuğunun adı) bir dize olmalıdır -@msg no toolbar named `{name}` `{name}` adlı araç çubuğu yok -@msg toolbar name can't be empty araç çubuğu adı boş olamaz -@msg a toolbar name has at most {MAX_NAME} characters bir araç çubuğu adı en fazla {MAX_NAME} karakter olabilir -@msg there is already a toolbar named `{name}` `{name}` adlı bir araç çubuğu zaten var -@msg there is already a toolbar named `{to}` `{to}` adlı bir araç çubuğu zaten var -@msg a workspace keeps at most {MAX} toolbars bir çalışma alanı en fazla {MAX} araç çubuğu tutar -@msg name (a toolbar's name) must be a string name (bir araç çubuğunun adı) bir dize olmalıdır -@msg name (a toolbar's name) is required name (bir araç çubuğunun adı) gerekli -@msg to (the new name) is required to (yeni ad) gerekli -@msg name must be a toolbar's name name bir araç çubuğunun adı olmalıdır Ignore All Tümünü Yoksay Add to Dictionary Sözlüğe Ekle No Suggestions Öneri Yok From b3a056b7fdf7d30e31f0f8a6b98cd219311c2262 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:59:36 -0800 Subject: [PATCH 08/41] i18n: Liquify's skip warning shows its tool and object kinds in the interface language The status bar translated the sentence of Liquify's warning about the objects under the brush that it left as they were, but kept the tool's name and the list of object kinds in English. The warning now translates the tool through a liquify-tool row and each kind through a liquify-kind row, keeps the kinds in the order the command lists them, and joins them with the liquify-list-two, liquify-list-middle and liquify-list-end rows. Every complete-message catalog has the rows. The English the command returns is unchanged, and a kind the warning does not list leaves the tool and the list in English. --- crates/ui-egui/src/i18n.rs | 55 +++++++++++++++++- crates/ui-egui/src/i18n/ca.tsv | 19 +++++++ crates/ui-egui/src/i18n/cs.tsv | 19 +++++++ crates/ui-egui/src/i18n/da.tsv | 19 +++++++ crates/ui-egui/src/i18n/de.tsv | 19 +++++++ crates/ui-egui/src/i18n/el.tsv | 19 +++++++ crates/ui-egui/src/i18n/es.tsv | 19 +++++++ crates/ui-egui/src/i18n/fi.tsv | 19 +++++++ crates/ui-egui/src/i18n/fr.tsv | 19 +++++++ crates/ui-egui/src/i18n/hi.tsv | 19 +++++++ crates/ui-egui/src/i18n/hu.tsv | 19 +++++++ crates/ui-egui/src/i18n/it.tsv | 19 +++++++ crates/ui-egui/src/i18n/ja.tsv | 19 +++++++ crates/ui-egui/src/i18n/ka.tsv | 19 +++++++ crates/ui-egui/src/i18n/ko.tsv | 19 +++++++ crates/ui-egui/src/i18n/nl.tsv | 19 +++++++ crates/ui-egui/src/i18n/pl.tsv | 19 +++++++ crates/ui-egui/src/i18n/pt-br.tsv | 19 +++++++ crates/ui-egui/src/i18n/ru.tsv | 19 +++++++ crates/ui-egui/src/i18n/sv.tsv | 19 +++++++ crates/ui-egui/src/i18n/tests.rs | 87 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 19 +++++++ crates/ui-egui/src/i18n/uk.tsv | 19 +++++++ crates/ui-egui/src/i18n/vi.tsv | 19 +++++++ crates/ui-egui/src/i18n/zh-hans.tsv | 19 +++++++ crates/ui-egui/src/i18n/zh-hant.tsv | 19 +++++++ docs/target-app-parity.md | 1 + 27 files changed, 598 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 377df81a72..b5ab28b88a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -703,11 +703,64 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { message_at(lang, v, depth - 1) } }; - let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, nested(v))).collect(); + let liquify = liquify_skip_values(lang, s, &caps); + let values: Vec<(&str, String)> = caps + .into_iter() + .map(|(k, v)| match (&liquify, k) { + (Some((tool, _)), "_1") => (k, tool.clone()), + (Some((_, kinds)), "_2") => (k, kinds.clone()), + _ => (k, nested(v)), + }) + .collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); fill_once(template, &args) } +/// The tool labels in Liquify's warning about the objects under the brush that it left as they +/// were, each translated by its `liquify-tool` row. +const LIQUIFY_TOOLS: [&str; 7] = ["Warp", "Twirl", "Pucker", "Bloat", "Scallop", "Crystallize", "Wrinkle"]; + +/// The kinds of object that warning lists (the engine's `not_liquified` in +/// `crates/engine/src/cmd/distortcmds.rs`), each translated by its `liquify-kind` row. +const LIQUIFY_KINDS: [&str; 9] = ["graphs", "type", "symbols", "images", "meshes", "envelopes", "repeats", "placed documents", "blends"]; + +/// The tool and the list of kinds in `lang` when `s` is Liquify's warning about the objects under +/// the brush that it left as they were and `caps` are its captures. The kinds keep their order and +/// are joined with the `liquify-list-two` row for two, and the `liquify-list-middle` and +/// `liquify-list-end` rows for more; a missing row leaves its part in English. `None` for any +/// other message, or a tool or kind that is not one of Liquify's. +fn liquify_skip_values(lang: Lang, s: &str, caps: &[(&str, &str)]) -> Option<(String, String)> { + let cap = |name: &str| caps.iter().find(|(k, _)| *k == name).map(|(_, v)| *v); + let (tool, n, kinds) = (cap("_1")?, cap("n")?, cap("_2")?); + let english = if n == "1" { + format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only") + } else { + format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only") + }; + if caps.len() != 3 || english != s || !LIQUIFY_TOOLS.contains(&tool) { + return None; + } + let catalog = lang.catalog(); + let words = kinds + .split(", ") + .map(|k| LIQUIFY_KINDS.contains(&k).then(|| catalog.contextual("liquify-kind", k).unwrap_or(k))) + .collect::>>()?; + let join = |context: &str, a: &str, b: &str| { + let pattern = "{0}, {1}"; + fill_once(catalog.contextual(context, pattern).unwrap_or(pattern), &[("0", a), ("1", b)]) + }; + let list = match words.as_slice() { + [] => return None, + [one] => (*one).to_string(), + [a, b] => join("liquify-list-two", a, b), + [first, middle @ .., last] => { + let head = middle.iter().fold((*first).to_string(), |acc, w| join("liquify-list-middle", &acc, w)); + join("liquify-list-end", &head, last) + } + }; + Some((catalog.contextual("liquify-tool", tool).unwrap_or(tool).to_string(), list)) +} + /// The translation of a message with an exact `@msg` row in `catalog`, its `{{` and `}}` shown as /// `{` and `}`. fn exact_translation(catalog: &Catalog, s: &str) -> Option { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index bba846f082..ee7baa4717 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5585,6 +5585,25 @@ digits Malayalam Malaiàlam @msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no queden respostes per a aquest quadre de diàleg @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` conté {n} resposta que l'script no ha utilitzat|`answers` conté {n} respostes que l'script no ha utilitzat @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ha deixat {n} objecte sota el pinzell sense canvis ({_2}): només remodela traçats|{_1} ha deixat {n} objectes sota el pinzell sense canvis ({_2}): només remodela traçats +liquify-tool Warp Deformació +liquify-tool Twirl Remolí +liquify-tool Pucker Arrufament +liquify-tool Bloat Inflament +liquify-tool Scallop Festonat +liquify-tool Crystallize Cristal·lització +liquify-tool Wrinkle Arruga +liquify-kind graphs gràfics +liquify-kind type text +liquify-kind symbols símbols +liquify-kind images imatges +liquify-kind meshes malles +liquify-kind envelopes embolcalls +liquify-kind repeats repeticions +liquify-kind placed documents documents col·locats +liquify-kind blends fusions +liquify-list-two {0}, {1} {0} i {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} i {1} @msg vc.document{place} is too large for a script vc.document{place} és massa gran per a un script @msg vc.log: the log of this run is full vc.log: el registre d'aquesta execució és ple @msg this function's script run has ended l'execució de l'script d'aquesta funció ha acabat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bf4352716d..141ff0a218 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4691,6 +4691,25 @@ imageTrace Outline Obrys @msg {name}: `answers` has no answer left for this dialog {name}: `answers` už nemá pro tento dialog žádnou odpověď @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use V `answers` je {n} odpověď, kterou skript nepoužil|V `answers` jsou {n} odpovědi, které skript nepoužil|V `answers` je {n} odpovědí, které skript nepoužil @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ponechal {n} objekt pod štětcem beze změny ({_2}): mění pouze cesty|{_1} ponechal {n} objekty pod štětcem beze změny ({_2}): mění pouze cesty|{_1} ponechal {n} objektů pod štětcem beze změny ({_2}): mění pouze cesty +liquify-tool Warp Nástroj Pokřivení +liquify-tool Twirl Nástroj Zatočení +liquify-tool Pucker Nástroj Smrštění +liquify-tool Bloat Nástroj Vyboulení +liquify-tool Scallop Nástroj Vroubkování +liquify-tool Crystallize Nástroj Krystalizace +liquify-tool Wrinkle Nástroj Zvrásnění +liquify-kind graphs grafy +liquify-kind type text +liquify-kind symbols symboly +liquify-kind images obrazy +liquify-kind meshes sítě +liquify-kind envelopes obálky +liquify-kind repeats opakování +liquify-kind placed documents umístěné dokumenty +liquify-kind blends prolnutí +liquify-list-two {0}, {1} {0} a {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} a {1} @msg vc.document{place} is too large for a script vc.document{place} je pro skript příliš velký @msg vc.log: the log of this run is full vc.log: protokol tohoto běhu je plný @msg this function's script run has ended běh skriptu této funkce skončil diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0e9031efa7..6d9c03489d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -133,6 +133,25 @@ @msg {name}: `answers` has no answer left for this dialog {name}: `answers` har intet svar tilbage til denne dialog @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` har {n} svar, som scriptet ikke brugte|`answers` har {n} svar, som scriptet ikke brugte @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} lod {n} objekt under penslen være uændret ({_2}): det omformer kun kurver|{_1} lod {n} objekter under penslen være uændrede ({_2}): det omformer kun kurver +liquify-tool Warp Vridning +liquify-tool Twirl Hvirvel +liquify-tool Pucker Krymp +liquify-tool Bloat Opsvulm +liquify-tool Scallop Muslingekant +liquify-tool Crystallize Krystallisering +liquify-tool Wrinkle Rynke +liquify-kind graphs diagrammer +liquify-kind type tekst +liquify-kind symbols symboler +liquify-kind images billeder +liquify-kind meshes net +liquify-kind envelopes konvolutter +liquify-kind repeats gentagelser +liquify-kind placed documents placerede dokumenter +liquify-kind blends blandinger +liquify-list-two {0}, {1} {0} og {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} og {1} @msg vc.document{place} is too large for a script vc.document{place} er for stort til et script @msg vc.log: the log of this run is full vc.log: loggen for denne kørsel er fuld @msg this function's script run has ended denne funktions scriptkørsel er afsluttet diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 003823f110..55a974118c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4303,6 +4303,25 @@ theme Appearance Erscheinungsbild @msg {name}: `answers` has no answer left for this dialog {name}: `answers` hat keine Antwort mehr für diesen Dialog @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` enthält {n} Antwort, die das Skript nicht verwendet hat|`answers` enthält {n} Antworten, die das Skript nicht verwendet hat @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ließ {n} Objekt unter dem Pinsel unverändert ({_2}): es formt nur Pfade um|{_1} ließ {n} Objekte unter dem Pinsel unverändert ({_2}): es formt nur Pfade um +liquify-tool Warp Verkrümmung +liquify-tool Twirl Strudel +liquify-tool Pucker Zusammenziehen +liquify-tool Bloat Aufblasen +liquify-tool Scallop Ausbuchten +liquify-tool Crystallize Kristallisieren +liquify-tool Wrinkle Zerknittern +liquify-kind graphs Diagramme +liquify-kind type Text +liquify-kind symbols Symbole +liquify-kind images Bilder +liquify-kind meshes Gitter +liquify-kind envelopes Hüllen +liquify-kind repeats Wiederholungen +liquify-kind placed documents platzierte Dokumente +liquify-kind blends Angleichungen +liquify-list-two {0}, {1} {0} und {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} und {1} @msg vc.document{place} is too large for a script vc.document{place} ist zu groß für ein Skript @msg vc.log: the log of this run is full vc.log: Das Protokoll dieses Laufs ist voll @msg this function's script run has ended der Skriptlauf dieser Funktion ist beendet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 40124eb3a5..7ec4182da6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2436,6 +2436,25 @@ axis Both Και τα δύο @msg {name}: `answers` has no answer left for this dialog {name}: το `answers` δεν έχει άλλη απάντηση για αυτό το παράθυρο διαλόγου @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use Το `answers` περιέχει {n} απάντηση που δεν χρησιμοποίησε το σενάριο|Το `answers` περιέχει {n} απαντήσεις που δεν χρησιμοποίησε το σενάριο @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only Το {_1} άφησε {n} αντικείμενο κάτω από το πινέλο χωρίς αλλαγή ({_2}): αναδιαμορφώνει μόνο διαδρομές|Το {_1} άφησε {n} αντικείμενα κάτω από το πινέλο χωρίς αλλαγή ({_2}): αναδιαμορφώνει μόνο διαδρομές +liquify-tool Warp εργαλείο Παραμόρφωση +liquify-tool Twirl εργαλείο Στροβιλισμός +liquify-tool Pucker εργαλείο Συρρίκνωση +liquify-tool Bloat εργαλείο Διόγκωση +liquify-tool Scallop εργαλείο Κυματιστά άκρα +liquify-tool Crystallize εργαλείο Κρυσταλλοποίηση +liquify-tool Wrinkle εργαλείο Πτυχώσεις +liquify-kind graphs γραφήματα +liquify-kind type κείμενο +liquify-kind symbols σύμβολα +liquify-kind images εικόνες +liquify-kind meshes πλέγματα +liquify-kind envelopes περιβλήματα +liquify-kind repeats επαναλήψεις +liquify-kind placed documents τοποθετημένα έγγραφα +liquify-kind blends αναμείξεις +liquify-list-two {0}, {1} {0} και {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} και {1} @msg vc.document{place} is too large for a script το vc.document{place} είναι πολύ μεγάλο για σενάριο @msg vc.log: the log of this run is full vc.log: το αρχείο καταγραφής αυτής της εκτέλεσης είναι γεμάτο @msg this function's script run has ended η εκτέλεση σεναρίου αυτής της συνάρτησης έχει τελειώσει diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7bb1dcee9a..f3276881cc 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4380,6 +4380,25 @@ axis Both Ambos @msg {name}: `answers` has no answer left for this dialog {name}: a `answers` no le quedan respuestas para este cuadro de diálogo @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contiene {n} respuesta que el script no usó|`answers` contiene {n} respuestas que el script no usó @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} dejó {n} objeto bajo el pincel sin cambios ({_2}): solo modifica trazados|{_1} dejó {n} objetos bajo el pincel sin cambios ({_2}): solo modifica trazados +liquify-tool Warp Deformar +liquify-tool Twirl Molinete +liquify-tool Pucker Fruncir +liquify-tool Bloat Engordar +liquify-tool Scallop Festonear +liquify-tool Crystallize Cristalizar +liquify-tool Wrinkle Arrugar +liquify-kind graphs gráficos +liquify-kind type texto +liquify-kind symbols símbolos +liquify-kind images imágenes +liquify-kind meshes mallas +liquify-kind envelopes envolventes +liquify-kind repeats repeticiones +liquify-kind placed documents documentos colocados +liquify-kind blends fusiones +liquify-list-two {0}, {1} {0}, {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0}, {1} @msg vc.document{place} is too large for a script vc.document{place} es demasiado grande para un script @msg vc.log: the log of this run is full vc.log: el registro de esta ejecución está lleno @msg this function's script run has ended la ejecución del script de esta función ha terminado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 5710132818..8d426cc2b3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4605,6 +4605,25 @@ imageTrace Outline Ääriviiva @msg {name}: `answers` has no answer left for this dialog {name}: kohteessa `answers` ei ole enää vastausta tälle valintaikkunalle @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` sisältää {n} vastauksen, jota komentosarja ei käyttänyt|`answers` sisältää {n} vastausta, joita komentosarja ei käyttänyt @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} jätti {n} objektin siveltimen alla muuttamatta ({_2}): se muokkaa vain polkuja|{_1} jätti {n} objektia siveltimen alla muuttamatta ({_2}): se muokkaa vain polkuja +liquify-tool Warp Vääristys +liquify-tool Twirl Pyöritys +liquify-tool Pucker Rypistys +liquify-tool Bloat Pullistus +liquify-tool Scallop Simpukointi +liquify-tool Crystallize Kiteytys +liquify-tool Wrinkle Ryppyistys +liquify-kind graphs kaaviot +liquify-kind type teksti +liquify-kind symbols symbolit +liquify-kind images kuvat +liquify-kind meshes verkot +liquify-kind envelopes vääristyskuoret +liquify-kind repeats toistot +liquify-kind placed documents sijoitetut asiakirjat +liquify-kind blends sulautukset +liquify-list-two {0}, {1} {0} ja {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} ja {1} @msg vc.document{place} is too large for a script vc.document{place} on liian suuri skriptille @msg vc.log: the log of this run is full vc.log: tämän ajon loki on täynnä @msg this function's script run has ended tämän funktion skriptiajo on päättynyt diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5da321ea07..e89f0e43ce 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4369,6 +4369,25 @@ axis Both Les deux @msg {name}: `answers` has no answer left for this dialog {name} : `answers` n'a plus de réponse pour cette boîte de dialogue @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contient {n} réponse que le script n'a pas utilisée|`answers` contient {n} réponses que le script n'a pas utilisées @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} a laissé {n} objet sous le pinceau sans changement ({_2}) : il ne remodèle que les tracés|{_1} a laissé {n} objets sous le pinceau sans changement ({_2}) : il ne remodèle que les tracés +liquify-tool Warp Déformation +liquify-tool Twirl Tourbillon +liquify-tool Pucker Contraction +liquify-tool Bloat Dilatation +liquify-tool Scallop Feston +liquify-tool Crystallize Cristallisation +liquify-tool Wrinkle Fronces +liquify-kind graphs graphes +liquify-kind type texte +liquify-kind symbols symboles +liquify-kind images images +liquify-kind meshes filets +liquify-kind envelopes enveloppes +liquify-kind repeats répétitions +liquify-kind placed documents documents importés +liquify-kind blends dégradés de formes +liquify-list-two {0}, {1} {0} et {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} et {1} @msg vc.document{place} is too large for a script vc.document{place} est trop volumineux pour un script @msg vc.log: the log of this run is full vc.log : le journal de cette exécution est plein @msg this function's script run has ended l'exécution du script de cette fonction est terminée diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index d5456c6b4a..3e2df2979b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6697,6 +6697,25 @@ antiAlias Sharp शार्प @msg {name}: `answers` has no answer left for this dialog {name}: `answers` में इस डायलॉग के लिए कोई उत्तर नहीं बचा है @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` में {n} उत्तर है जिसका स्क्रिप्ट ने उपयोग नहीं किया|`answers` में {n} उत्तर हैं जिनका स्क्रिप्ट ने उपयोग नहीं किया @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ने ब्रश के नीचे {n} ऑब्जेक्ट को अपरिवर्तित छोड़ा ({_2}): यह केवल पाथ को नया आकार देता है|{_1} ने ब्रश के नीचे {n} ऑब्जेक्ट्स को अपरिवर्तित छोड़ा ({_2}): यह केवल पाथ्स को नया आकार देता है +liquify-tool Warp वार्प टूल +liquify-tool Twirl ट्वर्ल टूल +liquify-tool Pucker सिकोड़ें टूल +liquify-tool Bloat फुलाएँ टूल +liquify-tool Scallop स्कैलप टूल +liquify-tool Crystallize क्रिस्टलीकरण टूल +liquify-tool Wrinkle शिकन टूल +liquify-kind graphs ग्राफ़ +liquify-kind type टाइप +liquify-kind symbols सिंबल्स +liquify-kind images चित्र +liquify-kind meshes मेश +liquify-kind envelopes एन्वेलप्स +liquify-kind repeats दोहराव +liquify-kind placed documents प्लेस्ड डॉक्यूमेंट्स +liquify-kind blends ब्लेंड्स +liquify-list-two {0}, {1} {0} और {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} और {1} @msg vc.document{place} is too large for a script vc.document{place} स्क्रिप्ट के लिए बहुत बड़ा है @msg vc.log: the log of this run is full vc.log: इस रन का लॉग भर गया है @msg this function's script run has ended इस फ़ंक्शन का स्क्रिप्ट रन समाप्त हो गया है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 5248a654bb..ac1e52f29b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5192,6 +5192,25 @@ imageTrace Outline Körvonal @msg {name}: `answers` has no answer left for this dialog {name}: az `answers` listában nem maradt válasz ehhez a párbeszédpanelhez @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use Az `answers` listában {n} válasz maradt, amelyet a parancsfájl nem használt fel @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}: az ecset alatt {n} objektum változatlan maradt ({_2}); csak útvonalakat alakít át +liquify-tool Warp Hajlítás +liquify-tool Twirl Örvénylés +liquify-tool Pucker Összehúzás +liquify-tool Bloat Felfújás +liquify-tool Scallop Csipkézés +liquify-tool Crystallize Kristályosítás +liquify-tool Wrinkle Gyűrés +liquify-kind graphs grafikonok +liquify-kind type szöveg +liquify-kind symbols szimbólumok +liquify-kind images képek +liquify-kind meshes rácsok +liquify-kind envelopes burkolók +liquify-kind repeats ismétlések +liquify-kind placed documents elhelyezett dokumentumok +liquify-kind blends összemosások +liquify-list-two {0}, {1} {0} és {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} és {1} @msg vc.document{place} is too large for a script a vc.document{place} túl nagy egy parancsfájlhoz @msg vc.log: the log of this run is full vc.log: ennek a futásnak a naplója megtelt @msg this function's script run has ended ennek a függvénynek a parancsfájl-futása véget ért diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8d679d2b9b..a69ba79cb7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4432,6 +4432,25 @@ axis Both Entrambi @msg {name}: `answers` has no answer left for this dialog {name}: in `answers` non rimangono risposte per questa finestra di dialogo @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contiene {n} risposta che lo script non ha usato|`answers` contiene {n} risposte che lo script non ha usato @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} ha lasciato {n} oggetto sotto il pennello senza modifiche ({_2}): rimodella solo i tracciati|{_1} ha lasciato {n} oggetti sotto il pennello senza modifiche ({_2}): rimodella solo i tracciati +liquify-tool Warp Altera +liquify-tool Twirl Vortice +liquify-tool Pucker Contrai +liquify-tool Bloat Gonfia +liquify-tool Scallop Smerla +liquify-tool Crystallize Cristallizza +liquify-tool Wrinkle Grinza +liquify-kind graphs grafici +liquify-kind type testo +liquify-kind symbols simboli +liquify-kind images immagini +liquify-kind meshes trame +liquify-kind envelopes involucri +liquify-kind repeats ripetizioni +liquify-kind placed documents documenti inseriti +liquify-kind blends fusioni +liquify-list-two {0}, {1} {0} e {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} e {1} @msg vc.document{place} is too large for a script vc.document{place} è troppo grande per uno script @msg vc.log: the log of this run is full vc.log: il registro di questa esecuzione è pieno @msg this function's script run has ended l'esecuzione dello script di questa funzione è terminata diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 319efabab8..d42fbdf9d2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5197,6 +5197,25 @@ swatch Bright Violet ビビッドバイオレット @msg {name}: `answers` has no answer left for this dialog {name}: `answers` にこのダイアログの回答が残っていません @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` にスクリプトが使用しなかった回答が {n} 件あります @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} はブラシの下にある {n} 個のオブジェクトを変更せずに残しました({_2})。パスのみを変形します +liquify-tool Warp ワープ +liquify-tool Twirl 旋回 +liquify-tool Pucker 収縮 +liquify-tool Bloat 膨張 +liquify-tool Scallop ギザギザ +liquify-tool Crystallize 結晶化 +liquify-tool Wrinkle しわ +liquify-kind graphs グラフ +liquify-kind type テキスト +liquify-kind symbols シンボル +liquify-kind images 画像 +liquify-kind meshes メッシュ +liquify-kind envelopes エンベロープ +liquify-kind repeats リピート +liquify-kind placed documents 配置ドキュメント +liquify-kind blends ブレンド +liquify-list-two {0}, {1} {0}、{1} +liquify-list-middle {0}, {1} {0}、{1} +liquify-list-end {0}, {1} {0}、{1} @msg vc.document{place} is too large for a script vc.document{place} はスクリプトには大きすぎます @msg vc.log: the log of this run is full vc.log: この実行のログがいっぱいです @msg this function's script run has ended この関数のスクリプトの実行は終了しています diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index aa274a1708..3afb6166fd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5604,6 +5604,25 @@ imageTrace Outline კონტური @msg {name}: `answers` has no answer left for this dialog {name}: `answers`-ში ამ დიალოგისთვის პასუხი აღარ დარჩა @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers`-ში დარჩა {n} პასუხი, რომელიც სკრიპტს არ გამოუყენებია @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}-მა ფუნჯის ქვეშ უცვლელი დატოვა {n} ობიექტი ({_2}): ის მხოლოდ ტრაექტორიებს ცვლის +liquify-tool Warp გაღუნვა +liquify-tool Twirl დახვევა +liquify-tool Pucker შეკუმშვა +liquify-tool Bloat გაბერვა +liquify-tool Scallop დაკბილვა +liquify-tool Crystallize კრისტალიზაცია +liquify-tool Wrinkle დანაოჭება +liquify-kind graphs დიაგრამები +liquify-kind type ტექსტი +liquify-kind symbols სიმბოლოები +liquify-kind images გამოსახულებები +liquify-kind meshes ბადეები +liquify-kind envelopes გარსები +liquify-kind repeats გამეორებები +liquify-kind placed documents განთავსებული დოკუმენტები +liquify-kind blends გადასვლები +liquify-list-two {0}, {1} {0} და {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} და {1} @msg vc.document{place} is too large for a script vc.document{place} ზედმეტად დიდია სკრიპტისთვის @msg vc.log: the log of this run is full vc.log: ამ გაშვების ჟურნალი სავსეა @msg this function's script run has ended ამ ფუნქციის სკრიპტის გაშვება დასრულდა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f51f7ea2bf..a9399ba8e5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5124,6 +5124,25 @@ theme Appearance 외관 @msg {name}: `answers` has no answer left for this dialog {name}: `answers`에 이 대화 상자에 대한 답이 남아 있지 않습니다 @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers`에 스크립트가 사용하지 않은 답이 {n}개 있습니다 @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}은(는) 브러시 아래의 개체 {n}개를 변경하지 않았습니다({_2}). 패스만 변형합니다 +liquify-tool Warp 왜곡 +liquify-tool Twirl 돌리기 +liquify-tool Pucker 오므리기 +liquify-tool Bloat 부풀리기 +liquify-tool Scallop 스캘럽 +liquify-tool Crystallize 결정화 +liquify-tool Wrinkle 주름 +liquify-kind graphs 그래프 +liquify-kind type 문자 +liquify-kind symbols 심볼 +liquify-kind images 이미지 +liquify-kind meshes 메시 +liquify-kind envelopes 엔벨로프 +liquify-kind repeats 반복 +liquify-kind placed documents 가져온 문서 +liquify-kind blends 블렌드 +liquify-list-two {0}, {1} {0} 및 {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} 및 {1} @msg vc.document{place} is too large for a script vc.document{place}이(가) 스크립트에 비해 너무 큽니다 @msg vc.log: the log of this run is full vc.log: 이 실행의 로그가 가득 찼습니다 @msg this function's script run has ended 이 함수의 스크립트 실행이 끝났습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e3b6672d1d..1d340eaf32 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -133,6 +133,25 @@ @msg {name}: `answers` has no answer left for this dialog {name}: `answers` heeft geen antwoord meer voor dit dialoogvenster @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` bevat {n} antwoord dat het script niet heeft gebruikt|`answers` bevat {n} antwoorden die het script niet heeft gebruikt @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} liet {n} object onder het penseel ongewijzigd ({_2}): het vervormt alleen paden|{_1} liet {n} objecten onder het penseel ongewijzigd ({_2}): het vervormt alleen paden +liquify-tool Warp Vervormen +liquify-tool Twirl Draaien +liquify-tool Pucker Krimpen +liquify-tool Bloat Opblazen +liquify-tool Scallop Schulpen +liquify-tool Crystallize Kristalliseren +liquify-tool Wrinkle Rimpelen +liquify-kind graphs grafieken +liquify-kind type tekst +liquify-kind symbols symbolen +liquify-kind images afbeeldingen +liquify-kind meshes rasters +liquify-kind envelopes omvormingen +liquify-kind repeats herhalingen +liquify-kind placed documents geplaatste documenten +liquify-kind blends vermengingen +liquify-list-two {0}, {1} {0} en {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} en {1} @msg vc.document{place} is too large for a script vc.document{place} is te groot voor een script @msg vc.log: the log of this run is full vc.log: het logboek van deze uitvoering is vol @msg this function's script run has ended de scriptuitvoering van deze functie is beëindigd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index cc99d78ae0..dd24eca95f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4515,6 +4515,25 @@ imageTrace Outline Kontur @msg {name}: `answers` has no answer left for this dialog {name}: w `answers` nie została żadna odpowiedź dla tego okna dialogowego @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` zawiera {n} odpowiedź, której skrypt nie użył|`answers` zawiera {n} odpowiedzi, których skrypt nie użył|`answers` zawiera {n} odpowiedzi, których skrypt nie użył @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} pozostawił {n} obiekt pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki|{_1} pozostawił {n} obiekty pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki|{_1} pozostawił {n} obiektów pod pędzlem bez zmian ({_2}): przekształca tylko ścieżki +liquify-tool Warp Wypaczenie +liquify-tool Twirl Wir +liquify-tool Pucker Ściągnięcie +liquify-tool Bloat Nadmuchanie +liquify-tool Scallop Ząbkowanie +liquify-tool Crystallize Krystalizacja +liquify-tool Wrinkle Marszczenie +liquify-kind graphs wykresy +liquify-kind type tekst +liquify-kind symbols symbole +liquify-kind images obrazy +liquify-kind meshes siatki +liquify-kind envelopes koperty +liquify-kind repeats powtórzenia +liquify-kind placed documents umieszczone dokumenty +liquify-kind blends przejścia +liquify-list-two {0}, {1} {0} i {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} i {1} @msg vc.document{place} is too large for a script vc.document{place} jest za duży dla skryptu @msg vc.log: the log of this run is full vc.log: dziennik tego uruchomienia jest pełny @msg this function's script run has ended uruchomienie skryptu tej funkcji zakończyło się diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e713ec6699..c587b5b0cd 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5413,6 +5413,25 @@ axis Both Ambos @msg {name}: `answers` has no answer left for this dialog {name}: `answers` não tem mais respostas para esta caixa de diálogo @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` contém {n} resposta que o script não usou|`answers` contém {n} respostas que o script não usou @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} deixou {n} objeto sob o pincel sem alteração ({_2}): remodela apenas caminhos|{_1} deixou {n} objetos sob o pincel sem alteração ({_2}): remodela apenas caminhos +liquify-tool Warp Distorcer +liquify-tool Twirl Redemoinho +liquify-tool Pucker Encolher +liquify-tool Bloat Estufar +liquify-tool Scallop Vieira +liquify-tool Crystallize Cristalizar +liquify-tool Wrinkle Rugas +liquify-kind graphs gráficos +liquify-kind type texto +liquify-kind symbols símbolos +liquify-kind images imagens +liquify-kind meshes malhas +liquify-kind envelopes envelopes +liquify-kind repeats repetições +liquify-kind placed documents documentos colocados +liquify-kind blends mesclagens +liquify-list-two {0}, {1} {0} e {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} e {1} @msg vc.document{place} is too large for a script vc.document{place} é grande demais para um script @msg vc.log: the log of this run is full vc.log: o registro desta execução está cheio @msg this function's script run has ended a execução do script desta função terminou diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9f93c41543..e290a6c167 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4417,6 +4417,25 @@ axis Both Оба @msg {name}: `answers` has no answer left for this dialog {name}: в `answers` не осталось ответа для этого диалогового окна @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use В `answers` остался {n} ответ, который скрипт не использовал|В `answers` осталось {n} ответа, которые скрипт не использовал|В `answers` осталось {n} ответов, которые скрипт не использовал @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} оставил без изменений {n} объект под кистью ({_2}): он изменяет только контуры|{_1} оставил без изменений {n} объекта под кистью ({_2}): он изменяет только контуры|{_1} оставил без изменений {n} объектов под кистью ({_2}): он изменяет только контуры +liquify-tool Warp Инструмент «Деформация» +liquify-tool Twirl Инструмент «Закручивание» +liquify-tool Pucker Инструмент «Сморщивание» +liquify-tool Bloat Инструмент «Раздувание» +liquify-tool Scallop Инструмент «Фестоны» +liquify-tool Crystallize Инструмент «Кристаллизация» +liquify-tool Wrinkle Инструмент «Морщины» +liquify-kind graphs диаграммы +liquify-kind type текст +liquify-kind symbols символы +liquify-kind images изображения +liquify-kind meshes сетки +liquify-kind envelopes оболочки +liquify-kind repeats повторы +liquify-kind placed documents размещённые документы +liquify-kind blends переходы +liquify-list-two {0}, {1} {0} и {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} и {1} @msg vc.document{place} is too large for a script vc.document{place} слишком велик для скрипта @msg vc.log: the log of this run is full vc.log: журнал этого запуска заполнен @msg this function's script run has ended запуск скрипта этой функции завершён diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8b91d803fb..c2a3a9a0a4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4290,6 +4290,25 @@ axis Both Båda @msg {name}: `answers` has no answer left for this dialog {name}: `answers` har inget svar kvar för den här dialogrutan @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` har {n} svar som skriptet inte använde|`answers` har {n} svar som skriptet inte använde @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} lämnade {n} objekt under penseln utan ändring ({_2}): bara banor formas om|{_1} lämnade {n} objekt under penseln utan ändring ({_2}): bara banor formas om +liquify-tool Warp Förvräng +liquify-tool Twirl Virvel +liquify-tool Pucker Dra ihop +liquify-tool Bloat Svullnad +liquify-tool Scallop Bågkant +liquify-tool Crystallize Kristallisera +liquify-tool Wrinkle Skrynkla +liquify-kind graphs diagram +liquify-kind type text +liquify-kind symbols symboler +liquify-kind images bilder +liquify-kind meshes nät +liquify-kind envelopes kuvert +liquify-kind repeats upprepningar +liquify-kind placed documents placerade dokument +liquify-kind blends blandningar +liquify-list-two {0}, {1} {0} och {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} och {1} @msg vc.document{place} is too large for a script vc.document{place} är för stort för ett skript @msg vc.log: the log of this run is full vc.log: loggen för den här körningen är full @msg this function's script run has ended skriptkörningen för den här funktionen har avslutats diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ea42234fec..f77537b22b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2177,6 +2177,93 @@ fn messages_with_one_or_several_items_translate_in_every_complete_catalog() { assert!(message(cs, "`answers` has 5 answers the script did not use").contains("5 odpovědí,")); } +/// Liquify's warning about the objects under the brush that it left as they were shows its tool +/// and each kind of object in the interface language, the kinds in their order and joined as the +/// language joins a list, in every complete-message language; the count stays. +#[test] +fn liquify_warning_translates_its_tool_and_kinds_in_every_complete_catalog() { + const TOOLS: [&str; 7] = ["Warp", "Twirl", "Pucker", "Bloat", "Scallop", "Crystallize", "Wrinkle"]; + const KINDS: [&str; 9] = ["graphs", "type", "symbols", "images", "meshes", "envelopes", "repeats", "placed documents", "blends"]; + let warning = |tool: &str, n: usize, kinds: &str| { + if n == 1 { + format!("{tool} left {n} object under the brush as it was ({kinds}): it reshapes paths only") + } else { + format!("{tool} left {n} objects under the brush as they were ({kinds}): it reshapes paths only") + } + }; + let words = |s: &str| s.split(|c: char| !c.is_alphabetic()).filter(|w| !w.is_empty()).map(str::to_string).collect::>(); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let cat = lang.catalog(); + for ctx in ["liquify-list-two", "liquify-list-middle", "liquify-list-end"] { + assert!(cat.contextual(ctx, "{0}, {1}").is_some(), "{code} has no {ctx} row"); + } + let kind = |k: &str| cat.contextual("liquify-kind", k).unwrap_or_else(|| panic!("{code} has no liquify-kind row for {k}")); + // No English word of `sources` is left in `shown`, unless a translation uses it too. + let english_left = |shown: &str, sources: &[&str], translated: &[&str]| { + let shown = words(shown); + for source in sources { + let kept = translated.iter().any(|t| words(t).iter().any(|w| words(source).contains(w))); + assert!(kept || words(source).iter().all(|w| !shown.contains(w)), "{code}: {source} stays English in {shown:?}"); + } + }; + for tool in TOOLS { + let label = cat.contextual("liquify-tool", tool).unwrap_or_else(|| panic!("{code} has no liquify-tool row for {tool}")); + // All nine kinds, in the engine's order and in reverse. + for kinds in [KINDS.to_vec(), KINDS.iter().rev().copied().collect()] { + let shown = message(lang, &warning(tool, kinds.len(), &kinds.join(", "))); + assert!(shown.contains(label) && shown.contains('9'), "{code}: {shown}"); + let translated: Vec<&str> = kinds.iter().map(|k| kind(k)).collect(); + let mut from = 0; + for t in &translated { + let at = shown[from..].find(t).unwrap_or_else(|| panic!("{code}: {t} missing or out of order in {shown}")); + from += at + t.len(); + } + english_left(&shown, &kinds, &translated); + english_left(&shown, &[tool], &[label]); + } + } + // One kind, for one object and for several. + for k in KINDS { + for n in [1, 2, 5] { + let shown = message(lang, &warning("Bloat", n, k)); + assert!(shown.contains(kind(k)) && shown.contains(&n.to_string()), "{code}: {shown}"); + english_left(&shown, &[k], &[kind(k)]); + } + } + } + let de = Lang::from_code("de").expect("registered"); + assert_eq!( + message(de, &warning("Warp", 1, "symbols")), + "Verkrümmung ließ 1 Objekt unter dem Pinsel unverändert (Symbole): es formt nur Pfade um" + ); + assert_eq!( + message(de, &warning("Twirl", 2, "type, images")), + "Strudel ließ 2 Objekte unter dem Pinsel unverändert (Text und Bilder): es formt nur Pfade um" + ); + assert_eq!( + message(de, &warning("Pucker", 4, "graphs, type, symbols, images")), + "Zusammenziehen ließ 4 Objekte unter dem Pinsel unverändert (Diagramme, Text, Symbole und Bilder): es formt nur Pfade um" + ); + // The count picks the language's form. + assert_eq!( + message(cs(), &warning("Crystallize", 5, "meshes, placed documents")), + "Nástroj Krystalizace ponechal 5 objektů pod štětcem beze změny (sítě a umístěné dokumenty): mění pouze cesty" + ); + let ja = Lang::from_code("ja").expect("registered"); + assert_eq!( + message(ja, &warning("Wrinkle", 3, "blends, repeats, envelopes")), + "しわ はブラシの下にある 3 個のオブジェクトを変更せずに残しました(ブレンド、リピート、エンベロープ)。パスのみを変形します" + ); + // A kind Liquify does not list leaves the tool and the list as they are. + assert_eq!( + message(de, &warning("Warp", 2, "type, widgets")), + "Warp ließ 2 Objekte unter dem Pinsel unverändert (type, widgets): es formt nur Pfade um" + ); + // English shows the warning as the engine wrote it. + assert_eq!(message(Lang::EN, &warning("Warp", 2, "type, images")), warning("Warp", 2, "type, images")); +} + /// Spanish shows the image encoders', color profiles', swatch exchange files', Revolve's, DXF /// import's, the script engine's and the parameter checks' errors in Spanish, with their values, /// backticked names and accepted values kept as the English writes them. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2d2bfc431..23d6d92b66 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4153,6 +4153,25 @@ axis Both Her İkisi @msg {name}: `answers` has no answer left for this dialog {name}: `answers` içinde bu iletişim kutusu için yanıt kalmadı @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` içinde betiğin kullanmadığı {n} yanıt var @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1}, fırçanın altındaki {n} nesneyi değiştirmeden bıraktı ({_2}): yalnızca yolları yeniden şekillendirir +liquify-tool Warp Çarpıtma +liquify-tool Twirl Burgu +liquify-tool Pucker Büzülme +liquify-tool Bloat Şişkinlik +liquify-tool Scallop Tarak +liquify-tool Crystallize Kristalleştirme +liquify-tool Wrinkle Kırışıklık +liquify-kind graphs grafikler +liquify-kind type yazı +liquify-kind symbols semboller +liquify-kind images görseller +liquify-kind meshes ağlar +liquify-kind envelopes zarflar +liquify-kind repeats tekrarlar +liquify-kind placed documents yerleştirilen belgeler +liquify-kind blends karışımlar +liquify-list-two {0}, {1} {0} ve {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} ve {1} @msg vc.document{place} is too large for a script vc.document{place} bir betik için çok büyük @msg vc.log: the log of this run is full vc.log: bu çalıştırmanın günlüğü dolu @msg this function's script run has ended bu işlevin betik çalıştırması sona erdi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8f56b3444e..2370847f27 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4416,6 +4416,25 @@ axis Both Обидві @msg {name}: `answers` has no answer left for this dialog {name}: у `answers` не залишилося відповіді для цього діалогового вікна @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use У `answers` залишилася {n} відповідь, яку скрипт не використав|У `answers` залишилися {n} відповіді, які скрипт не використав|У `answers` залишилося {n} відповідей, які скрипт не використав @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} залишив без змін {n} об’єкт під пензлем ({_2}): він змінює форму лише контурів|{_1} залишив без змін {n} об’єкти під пензлем ({_2}): він змінює форму лише контурів|{_1} залишив без змін {n} об’єктів під пензлем ({_2}): він змінює форму лише контурів +liquify-tool Warp Інструмент «Деформація» +liquify-tool Twirl Інструмент «Закручування» +liquify-tool Pucker Інструмент «Зморщування» +liquify-tool Bloat Інструмент «Роздування» +liquify-tool Scallop Інструмент «Фестон» +liquify-tool Crystallize Інструмент «Кристалізація» +liquify-tool Wrinkle Інструмент «Зморшки» +liquify-kind graphs діаграми +liquify-kind type текст +liquify-kind symbols символи +liquify-kind images зображення +liquify-kind meshes сітки +liquify-kind envelopes оболонки +liquify-kind repeats повтори +liquify-kind placed documents розміщені документи +liquify-kind blends переходи +liquify-list-two {0}, {1} {0} і {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} і {1} @msg vc.document{place} is too large for a script vc.document{place} завеликий для скрипту @msg vc.log: the log of this run is full vc.log: журнал цього запуску заповнений @msg this function's script run has ended запуск скрипту цієї функції завершився diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ec61f79511..e9a5fc1c19 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4846,6 +4846,25 @@ theme Appearance Giao diện @msg {name}: `answers` has no answer left for this dialog {name}: `answers` không còn câu trả lời nào cho hộp thoại này @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` có {n} câu trả lời mà tập lệnh không dùng @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} giữ nguyên {n} đối tượng dưới cọ ({_2}): chỉ biến dạng đường dẫn +liquify-tool Warp Biến dạng +liquify-tool Twirl Xoáy +liquify-tool Pucker Nhíu +liquify-tool Bloat Phình +liquify-tool Scallop Vỏ sò +liquify-tool Crystallize Kết tinh +liquify-tool Wrinkle Nhăn +liquify-kind graphs biểu đồ +liquify-kind type chữ +liquify-kind symbols ký hiệu +liquify-kind images hình ảnh +liquify-kind meshes lưới +liquify-kind envelopes bao hình +liquify-kind repeats lặp lại +liquify-kind placed documents tài liệu đã đặt +liquify-kind blends hòa trộn +liquify-list-two {0}, {1} {0} và {1} +liquify-list-middle {0}, {1} {0}, {1} +liquify-list-end {0}, {1} {0} và {1} @msg vc.document{place} is too large for a script vc.document{place} quá lớn đối với tập lệnh @msg vc.log: the log of this run is full vc.log: nhật ký của lần chạy này đã đầy @msg this function's script run has ended lần chạy tập lệnh của hàm này đã kết thúc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2881dd9374..d329bef791 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4876,6 +4876,25 @@ imageTrace Outline 轮廓 @msg {name}: `answers` has no answer left for this dialog {name}:`answers` 中已没有此对话框的回答 @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` 中有 {n} 个脚本未使用的回答 @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} 未更改画笔下的 {n} 个对象({_2}):它只重塑路径 +liquify-tool Warp 变形 +liquify-tool Twirl 旋转扭曲 +liquify-tool Pucker 收缩 +liquify-tool Bloat 膨胀 +liquify-tool Scallop 扇贝 +liquify-tool Crystallize 晶格化 +liquify-tool Wrinkle 褶皱 +liquify-kind graphs 图表 +liquify-kind type 文字 +liquify-kind symbols 符号 +liquify-kind images 图像 +liquify-kind meshes 网格 +liquify-kind envelopes 封套 +liquify-kind repeats 重复 +liquify-kind placed documents 置入的文档 +liquify-kind blends 混合 +liquify-list-two {0}, {1} {0}和{1} +liquify-list-middle {0}, {1} {0}、{1} +liquify-list-end {0}, {1} {0}和{1} @msg vc.document{place} is too large for a script vc.document{place}对脚本来说过大 @msg vc.log: the log of this run is full vc.log:本次运行的日志已满 @msg this function's script run has ended 此函数的脚本运行已结束 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2218782e1e..a7bb321e70 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2577,6 +2577,25 @@ file-filter Templates 範本 @msg {name}: `answers` has no answer left for this dialog {name}:`answers` 中已沒有此對話框的回答 @msgplural `answers` has {n} answer the script did not use|`answers` has {n} answers the script did not use `answers` 中有 {n} 個指令碼未使用的回答 @msgplural {_1} left {n} object under the brush as it was ({_2}): it reshapes paths only|{_1} left {n} objects under the brush as they were ({_2}): it reshapes paths only {_1} 未變更筆刷下的 {n} 個物件({_2}):它只重塑路徑 +liquify-tool Warp 彎曲 +liquify-tool Twirl 旋轉扭曲 +liquify-tool Pucker 縮攏 +liquify-tool Bloat 膨脹 +liquify-tool Scallop 扇形化 +liquify-tool Crystallize 結晶化 +liquify-tool Wrinkle 皺摺 +liquify-kind graphs 圖表 +liquify-kind type 文字 +liquify-kind symbols 符號 +liquify-kind images 影像 +liquify-kind meshes 網格 +liquify-kind envelopes 封套 +liquify-kind repeats 重複 +liquify-kind placed documents 已置入的文件 +liquify-kind blends 漸變 +liquify-list-two {0}, {1} {0}和{1} +liquify-list-middle {0}, {1} {0}、{1} +liquify-list-end {0}, {1} {0}和{1} @msg vc.document{place} is too large for a script vc.document{place}對指令碼來說太大 @msg vc.log: the log of this run is full vc.log:本次執行的記錄已滿 @msg this function's script run has ended 此函式的指令碼執行已結束 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c287e6c920..87bb5dc621 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -966,6 +966,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The errors of the parameter checks that many commands share show in the status bar in the interface language: a value that is not a number where a number goes (`object.move` with `"dx": "60 mm"`, and `object.rotate`, `object.setBounds` and the other commands that call `check_numbers`), a missing number or index, `ids` that are not a list of object ids, an object id that is not a non-negative integer or names no object, and a date that is not Unix seconds. Each has a row in every catalog that translates all status and error messages, and in Bulgarian, Danish, Indonesian and Dutch (`shared_param_check_errors_are_translated`). - A parameter schema's errors show in the status bar with what the value must be in the interface language, for every type a schema has (a number with each kind of range and with a unit, an integer and its range, true or false, a string, a list of names, an object id, a list of object ids, a color, a point, an object and a list), in every catalog that translates all status and error messages; the path, the refused value, the bounds, the unit and the names stay as the English gives them. The error for a value that is not one of its names is also translated in Bulgarian, Bosnian, Danish, Indonesian and Dutch (`parameter_schema_expected_phrases_are_translated`, `bracketed_message_parts_translate_only_as_exact_messages`). - A script's error about answers in `answers` that it did not use, and Liquify's warning about the objects under the brush that it left as they were, show in the status bar in the interface language for one answer or object as well as for several, with the count's own form in each catalog that translates all status and error messages; the English the commands return stays as it was (`messages_with_one_or_several_items_translate_in_every_complete_catalog`, `unused_answers_are_counted_in_the_singular_and_the_plural`, `liquify_warns_about_one_or_several_skipped_objects`). + - In that Liquify warning, the tool's name and each kind of object it left (graphs, type, symbols, images, meshes, envelopes, repeats, placed documents, blends) are shown in the interface language too, in the order the command lists them and joined as the language joins a list, in each catalog that translates all status and error messages (`liquify-tool`, `liquify-kind` and `liquify-list-*` rows); a kind that Liquify does not list leaves the tool and the list in English (`liquify_warning_translates_its_tool_and_kinds_in_every_complete_catalog`). - The untranslated report lists the status and error messages of the effects, swatch libraries, raster sizes and encoders, 3D solids and path operations that a catalog lacks, the messages that a `.map_err` closure or a named error handler returns, and the phrases a parameter schema's error builds for what a value must be (`untranslated_report_checks_every_message_crate_and_schema_phrase`, `message_scan_reads_map_err_closures`, `message_scan_reads_named_map_err_handlers`). - Spanish messages (2026-11-13): the Spanish catalog (`crates/ui-egui/src/i18n/es.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211 and #7378 translate 51 of the others (the composite font and SVG filter errors), and 2 stay in English. The rows keep the placeholders, backticked names, accepted values and limits of their English (`spanish_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - Export commands run through MCP, the control channel or the CLI refuse a key that no format takes, and warn about a key that only another format takes (`{"format": "pdf", "quality": 80}` writes the PDF with the warning "`quality` was not used: PDF files don't read it"; `an_option_only_another_format_reads_gets_a_note`, `control_export_notes_an_option_the_format_does_not_read`, `convert_warns_about_an_unused_option_only_when_one_was_given`), and a command that writes one format (`document.exportPdf`, `document.exportEps`, `document.exportDxf`) or takes one format's options (`document.pdfSettings`, `pdf.preset.save`) refuses a key that format doesn't take. An unknown key inside `marks`, `bleed`, `compression`, `output`, `advanced`, `security` or `flattener` is refused by its path. From 147b744845d152ebca8bcd7adcb7d3143d98a6e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:10:52 -0800 Subject: [PATCH 09/41] Graph Data: dragging a column's edge sets that column's width In the Graph Data window, the pointer becomes a column-resize arrow over a column's right edge, and dragging the edge sets that column's width in whole digits, from 0 to 20 as Cell Style's Column Width allows. The columns after it move along. Cell Style's Column Width, in the dialog or set as the `width` field, still sets every column. The dialog keeps the dragged widths in a `widths` field by column. --- crates/ui-egui/src/dialogs.rs | 5 + crates/ui-egui/src/dialogs/graph_data.rs | 237 +++++++++++++++++++---- docs/target-app-parity.md | 1 + 3 files changed, 209 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d958f18c1b..b67a27fa00 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -584,6 +584,7 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Options setting set this way for several rows is sent to every row (Template also sets Lock /// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as /// one picked from its menu does, and the preset it shows follows the DXF options set this way. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -598,10 +599,14 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { crate::prefs_dialog::note_set(d, &field, &value); } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); + let graph = (d.kind == graph_data::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { dxf_options::note_set(d, &field); } + if let Some(field) = graph { + graph_data::note_set(d, &field); + } } /// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ecfb0c303e..935ce60bd9 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -7,13 +7,15 @@ //! don't move the caret in the entry box). Pasting tab- or line-separated text fills the cells from //! the picked one. Import Data reads a tab-separated text file, Transpose row/column swaps rows and //! columns, Switch x/y swaps a scatter graph's y and x columns, Cell Style sets the number of -//! decimals the sheet shows and its columns' width, and Revert reads the graph's data again. Apply -//! (`graph.setData` with its series, categories and rows) redraws the graph and leaves the window -//! open. +//! decimals the sheet shows and the width of every column, dragging a column's right edge sets that +//! column's width (in whole digits, 0 to 20, as Cell Style), and Revert reads the graph's data +//! again. Apply (`graph.setData` with its series, categories and rows) redraws the graph and leaves +//! the window open. //! //! Fields: `grid` (rows of cell texts), `sel` ([row, column]), `entry` (the picked cell's text -//! being edited), `decimals` (null: as typed), `width` (digits), `__graph` (the graph's id) and -//! `__scatter`. +//! being edited), `decimals` (null: as typed), `width` (digits), `widths` (a column's own width in +//! digits by its index, null or missing: `width`; setting `width` empties it), `__graph` (the graph's +//! id) and `__scatter`. use serde_json::{Value, json}; use vectorcraft_doc::{MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES}; @@ -62,7 +64,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let entry = cell(&grid, 0, 1); app.ui.dialog = Some(Dialog::new( KIND, - json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "__graph": id, "__scatter": scatter }), + json!({ "grid": grid, "sel": [0, 1], "entry": entry, "decimals": null, "width": 7, "widths": [], "__graph": id, "__scatter": scatter }), )); Ok(Value::Null) } @@ -355,7 +357,7 @@ fn import(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { } /// Draw the graph-data sheet: keyboard cell movement, block paste, import, transpose, switch-x/y -/// and revert actions, decimals and column width, and only the cells in view. +/// and revert actions, decimals and column widths, and only the cells in view. fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let entry_id = egui::Id::unique("graph-data-entry"); if ui.memory(|m| m.has_focus(entry_id)) { @@ -436,36 +438,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::dim_label(ui, tl!("Column Width:")); let mut w = d.fields.get("width").and_then(Value::as_u64).unwrap_or(7); if ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)).changed() { - d.fields.insert("width".into(), json!(w)); + set_width(d, w); } }); ui.add_space(6.0); - let at = sel(d); - let (rows, cols) = extent(d, at); - let decimals = d.fields.get("decimals").and_then(Value::as_u64); - let w = (d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0); - let mut clicked = None; - widgets::list_box(ui, |ui| { - // Only the cells in view are drawn: a graph's sheet can be 10,001 × 257. - egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| { - let (cw, ch) = (w + 1.0, ROW_H); - ui.set_min_size(egui::vec2(cols as f32 * cw, rows as f32 * ch)); - let origin = ui.max_rect().min; - let span = |lo: f32, hi: f32, size: f32, n: usize| ((lo / size).floor().max(0.0) as usize, ((hi / size).ceil().max(0.0) as usize).min(n)); - let (r0, r1) = span(view.min.y, view.max.y, ch, rows); - let (c0, c1) = span(view.min.x, view.max.x, cw, cols); - for r in r0..r1 { - for c in c0..c1 { - let rect = egui::Rect::from_min_size(origin + egui::vec2(c as f32 * cw, r as f32 * ch), egui::vec2(w, ch - 1.0)); - let text = shown(cell_at(d, r, c), decimals); - let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate(); - if ui.put(rect, b).clicked() && (r, c) != (0, 0) { - clicked = Some((r, c)); - } - } - } - }); - }); + let (clicked, resized) = sheet(ui, d); + if let Some((c, n)) = resized + && n != col_digits(d, c) + { + set_col_digits(d, c, n); + } if let Some(to) = clicked { pick(d, to); ui.memory_mut(|mem| mem.request_focus(entry_id)); @@ -479,6 +461,123 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// Cell Style's Column Width in digits. +fn width(d: &Dialog) -> u64 { + d.fields.get("width").and_then(Value::as_u64).unwrap_or(7).min(MAX_WIDTH) +} + +/// A column's width in digits: its own when its edge was dragged, else Cell Style's. +fn col_digits(d: &Dialog, c: usize) -> u64 { + d.fields.get("widths").and_then(|w| w.get(c)).and_then(Value::as_u64).unwrap_or_else(|| width(d)).min(MAX_WIDTH) +} + +/// Cell Style's Column Width: every column `n` digits wide, the ones given their own width too. +fn set_width(d: &mut Dialog, n: u64) { + d.fields.insert("width".into(), json!(n.min(MAX_WIDTH))); + note_set(d, "width"); +} + +/// `ui.dialog.set` set `field`: a Column Width sets every column, as Cell Style's does. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if field == "width" { + d.fields.insert("widths".into(), json!([])); + } +} + +/// Set column `c`'s own width in digits (at most MAX_WIDTH). +fn set_col_digits(d: &mut Dialog, c: usize, n: u64) { + if c >= MAX_COLS { + return; + } + let widths = d.fields.entry("widths").or_insert_with(|| json!([])); + if !widths.is_array() { + *widths = json!([]); + } + let Some(widths) = widths.as_array_mut() else { return }; + if widths.len() <= c { + widths.resize(c + 1, Value::Null); + } + if let Some(w) = widths.get_mut(c) { + *w = json!(n.min(MAX_WIDTH)); + } +} + +/// A column `n` digits wide, in points on the sheet. +fn digits_px(n: u64) -> f32 { + (n.min(MAX_WIDTH) as f32 * 7.0 + 10.0).max(12.0) +} + +/// The width in digits nearest to `px` points, within Cell Style's 0 to MAX_WIDTH. +fn px_digits(px: f32) -> u64 { + if px.is_finite() { ((px - 10.0) / 7.0).round().clamp(0.0, MAX_WIDTH as f32) as u64 } else { 0 } +} + +/// The id of column `c`'s right edge on the sheet. +fn edge_id(c: usize) -> egui::Id { + egui::Id::unique(("graph-data-column-edge", c)) +} + +/// The cell clicked on the sheet ([row, column]), and the column whose edge is dragged with its width +/// in digits. +type SheetInput = (Option<(usize, usize)>, Option<(usize, u64)>); + +/// Draw the sheet's cells in view, each column at its own width. Returns the cell clicked, and the +/// column whose right edge is being dragged with the width in digits the pointer gives it. +fn sheet(ui: &mut egui::Ui, d: &Dialog) -> SheetInput { + let at = sel(d); + let (rows, cols) = extent(d, at); + let decimals = d.fields.get("decimals").and_then(Value::as_u64); + // Each column's left edge, and the sheet's width last: a column is its width and a 1-point gap. + let mut xs = Vec::with_capacity(cols + 1); + let mut x = 0.0; + xs.push(x); + for c in 0..cols { + x += digits_px(col_digits(d, c)) + 1.0; + xs.push(x); + } + let left = |c: usize| xs.get(c).copied().unwrap_or(x); + let (mut clicked, mut resized) = (None, None); + widgets::list_box(ui, |ui| { + // Only the cells in view are drawn: a graph's sheet can be 10,001 × 257. + egui::ScrollArea::both().id_salt("graph-data-sheet").max_height(280.0).auto_shrink([false, false]).show_viewport(ui, |ui, view| { + let ch = ROW_H; + ui.set_min_size(egui::vec2(x, rows as f32 * ch)); + let origin = ui.max_rect().min; + let (r0, r1) = ((view.min.y / ch).floor().max(0.0) as usize, ((view.max.y / ch).ceil().max(0.0) as usize).min(rows)); + // The columns that reach into the view. + let c0 = (0..cols).find(|&c| left(c + 1) > view.min.x).unwrap_or(cols); + let c1 = (c0..cols).find(|&c| left(c) >= view.max.x).unwrap_or(cols); + for r in r0..r1 { + for c in c0..c1 { + let size = egui::vec2(left(c + 1) - left(c) - 1.0, ch - 1.0); + let rect = egui::Rect::from_min_size(origin + egui::vec2(left(c), r as f32 * ch), size); + let text = shown(cell_at(d, r, c), decimals); + let b = egui::Button::selectable((r, c) == at, egui::RichText::new(text).monospace()).truncate(); + if ui.put(rect, b).clicked() && (r, c) != (0, 0) { + clicked = Some((r, c)); + } + } + } + // A column's right edge, over the rows in view: dragging it sets that column's width. The + // edge being dragged stays in the loop when it leaves the view, so the drag goes on. + let (top, bottom) = (origin.y + r0 as f32 * ch, origin.y + r1 as f32 * ch); + let dragged = ui.ctx().dragged_id().and_then(|id| (0..cols).find(|&c| edge_id(c) == id)).filter(|c| !(c0..c1).contains(c)); + for c in (c0..c1).chain(dragged) { + let gap = origin.x + left(c + 1) - 0.5; + let edge = egui::Rect::from_x_y_ranges(gap - 3.0..=gap + 3.0, top..=bottom); + let h = ui.interact(edge, edge_id(c), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeColumn); + if h.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeColumn); + if let Some(p) = h.interact_pointer_pos() { + resized = Some((c, px_digits(p.x - origin.x - left(c)))); + } + } + } + }); + }); + (clicked, resized) +} + #[cfg(test)] mod tests { use serde_json::json; @@ -685,6 +784,76 @@ mod tests { assert_eq!(sel(app.ui.dialog.as_ref().unwrap()), (0, 1), "Up"); } + /// Dragging a column's right edge shows the column-resize pointer and sets that column's width in + /// whole digits, the columns after it moving along; the other columns keep Cell Style's width. + /// A drag past 20 digits stops at 20, and Cell Style's Column Width then sets every column. + #[test] + fn dragging_a_column_edge_sets_that_columns_width() { + let (mut app, _) = app_with(",a,b\nQ1,1,2", "column"); + open(&mut app).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.platform_output.cursor_icon + }; + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn")); + let drag = |app: &mut VectorcraftApp, c: usize, dx: f32| { + let at = edge(c).center(); + frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]); + for step in 1..=4 { + frame(app, vec![egui::Event::PointerMoved(at + egui::vec2(dx * step as f32 / 4.0, 0.0))]); + } + frame(app, vec![button(at + egui::vec2(dx, 0.0), false)]); + frame(app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + }; + let digits = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().unwrap(); + (0..4).map(|c| col_digits(d, c)).collect::>() + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // The window takes its place over the first frames: hover where the edge is now. + let hovered = (0..10).any(|_| frame(&mut app, vec![egui::Event::PointerMoved(edge(1).center())]) == egui::CursorIcon::ResizeColumn); + assert!(hovered, "hovering an edge shows the column-resize pointer"); + let (one, two) = (edge(1).center().x, edge(2).center().x); + // 70 points is 10 digits. + drag(&mut app, 1, 70.0); + assert_eq!(digits(&app), [7, 17, 7, 7]); + let moved = [edge(1).center().x - one, edge(2).center().x - two]; + assert!(moved.iter().all(|m| (m - 70.0).abs() < 0.01), "the columns after it move along: {moved:?}"); + drag(&mut app, 2, -500.0); + assert_eq!(digits(&app), [7, 17, 0, 7], "no narrower than 0 digits"); + drag(&mut app, 0, 500.0); + assert_eq!(digits(&app), [20, 17, 0, 7], "no wider than 20 digits"); + let d = app.ui.dialog.as_mut().unwrap(); + set_width(d, 9); + assert_eq!(digits(&app), [9; 4], "Cell Style sets every column"); + } + + #[test] + fn a_column_width_in_points_maps_to_whole_digits() { + for n in 0..=MAX_WIDTH { + assert_eq!(px_digits(digits_px(n)), n); + } + assert_eq!((px_digits(-40.0), px_digits(1e9), px_digits(f32::NAN)), (0, MAX_WIDTH, 0)); + let mut d = Dialog::new(KIND, json!({ "width": 7 })); + set_col_digits(&mut d, 3, 99); + set_col_digits(&mut d, MAX_COLS, 5); + assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (7, MAX_WIDTH)); + assert_eq!(d.fields["widths"].as_array().map(Vec::len), Some(4), "a column past the sheet is left alone"); + // `width` set by `ui.dialog.set` sets every column too, also when set back to the width before. + for w in [12, 7] { + crate::dialogs::set_field(&mut d, "width".into(), json!(w)); + assert_eq!((col_digits(&d, 2), col_digits(&d, 3)), (w, w)); + } + set_col_digits(&mut d, 1, 4); + assert_eq!((col_digits(&d, 1), col_digits(&d, 3)), (4, 7), "a drag after it gives that column its own width"); + } + /// How many buttons (the sheet's cells and the window's own) Graph Data draws in the second of two /// frames in a 1280 × 900 window, for a graph of `categories` rows of `series` values. fn buttons_drawn(categories: usize, series: usize) -> usize { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8b5cb97e8..f6ff79070a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -827,6 +827,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Import Data Sets… (`dataset.import`) reads tab-separated files as well as comma-separated ones. Every header cell is a variable, and the rows replace the document's data sets as Data Set 1, Data Set 2 and so on. An import error about a row's values gives the file line the row starts on. - Variables: Import Data Sets… (`dataset.import`) reads a UTF-16 file without a byte-order mark, instead of refusing it, when at least half of its two-byte units hold a NUL byte; it uses the byte order that reads its line breaks. - Graphs: the Graph Data window's Import Data reads a UTF-16 text file without a byte-order mark by the same rule as Import Data Sets…, instead of filling the cells with NUL characters. It reads a file cut short by one byte, or with an unpaired surrogate, as it reads one after a byte-order mark. + - Graphs: in the Graph Data window, the pointer becomes a column-resize arrow over a column's right edge, and dragging the edge sets that column's width in whole digits, from 0 to 20 as Cell Style's Column Width allows. The columns after it move along. Cell Style's Column Width still sets every column, the dragged ones included ([Adjust decimal digits and column width](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/adjust-column-width.html)). - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values. From 3492976910b7a12f288661a074f59cb6a908e28b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:16:59 +0000 Subject: [PATCH 10/41] Use shared streaming native format writer --- Cargo.lock | 11 +- Cargo.toml | 3 +- crates/format/Cargo.toml | 1 + crates/format/src/lib.rs | 110 +++++-------- crates/format/src/stream.rs | 301 +----------------------------------- 5 files changed, 57 insertions(+), 369 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 887b10ab11..9fe89b8d81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1010,6 +1010,14 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6" +[[package]] +name = "craft-gzip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=424a2dc2be7a90467bca0f62b2f161b6bed57bb0#424a2dc2be7a90467bca0f62b2f161b6bed57bb0" +dependencies = [ + "flate2", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -1156,7 +1164,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" +source = "git+https://github.com/storytold/craft-libs?rev=560b6f8268e2c5285c161be52dacfe877b08cf1b#560b6f8268e2c5285c161be52dacfe877b08cf1b" dependencies = [ "flate2", "serde", @@ -6625,6 +6633,7 @@ dependencies = [ name = "vectorcraft-format" version = "0.24.1" dependencies = [ + "craft-gzip", "craft-vectorcraft-format", "flate2", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 610e2b462c..c4e09e8678 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637 # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "560b6f8268e2c5285c161be52dacfe877b08cf1b" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "424a2dc2be7a90467bca0f62b2f161b6bed57bb0" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" } diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index bd004d2d1e..e020dda9c3 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -12,6 +12,7 @@ workspace = true vectorcraft-doc = { workspace = true } vectorcraft-brush = { workspace = true } craft-vectorcraft-format = { workspace = true } +craft-gzip = { workspace = true } serde ={ workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9add0798c7..a8c7358aa7 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -57,12 +57,14 @@ use vectorcraft_doc::{Document, ImageBlob}; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; +use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; pub use craft_vectorcraft_format::{ BLOB_MAGIC, COMPRESSED_SINCE, EXTENSION, ICC_MIME, INLINE_MAX, LEGACY_EXTENSION, MIN_VERSION, PREVIEW_MAX, VERSION, is_compressed, json_part, sniff, }; -use stream::{Gz, Indent, KeyScan, Out}; +use stream::Out; /// Most bytes the JSON of a compressed file may unpack to (a guard against decompression bombs, /// as are [`MAX_BLOB`] and [`MAX_BLOBS`]). A compressed save refuses a document past any of them, @@ -367,35 +369,44 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For let profiles: BTreeMap<&str, Image> = o.profiles.iter().map(|(name, icc)| (name.as_str(), out_blobs.image(ICC_MIME, icc, false))).collect(); let pdf = o.pdf.as_deref().map(|p| out_blobs.image("application/pdf", p, false)); let mut out = if o.compress { Out::Gz(Box::new(Gz::new(w).map_err(encode_err)?)) } else { Out::Plain(w) }; - let mut env = Envelope { pretty, first: true }; - // Older apps only know the name from before the rename. - env.field(&mut out, "format", &if o.version < 3 { LEGACY_EXTENSION } else { EXTENSION })?; - env.field(&mut out, "version", &o.version)?; - env.field(&mut out, "generator", &format!("VectorCraft {}", env!("CARGO_PKG_VERSION")))?; - if let Some(compatible) = o.pdf_compatible { - env.field(&mut out, "pdfCompatible", &compatible)?; - } - if let Some(png) = &o.preview { - env.field(&mut out, "preview", &Image::inline("image/png", png))?; - } - if !profiles.is_empty() { - env.field(&mut out, "profiles", &profiles)?; - } - if let Some(pdf) = &pdf { - env.field(&mut out, "pdf", pdf)?; - } - env.key(&mut out, "document")?; - let mut scan = KeyScan::new(Indent { inner: &mut out, on: pretty }); - // Without blobs no key matters. - scan.active = images.is_none() && !blobs.is_empty(); - let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan); - write_body(&mut buffered, v1.as_ref(), &d, pretty)?; - buffered.flush().map_err(encode_err)?; - drop(buffered); - let used = std::mem::take(&mut scan.keys); - let images = images.unwrap_or_else(|| entries.images(&used, &mut out_blobs)); - env.field(&mut out, "images", &images)?; - env.finish(&mut out)?; + let generator = format!("VectorCraft {}", env!("CARGO_PKG_VERSION")); + let preview = o.preview.as_deref().map(|png| Image::inline("image/png", png)); + let header = FileHeader { + version: o.version, + generator: &generator, + pdf_compatible: o.pdf_compatible, + preview: preview.as_ref(), + profiles: &profiles, + pdf: pdf.as_ref(), + }; + write_file_json(&mut out, &header, pretty, |document| { + let mut scan = KeyScan::new(document); + // Without blobs no key matters. + scan.active = images.is_none() && !blobs.is_empty(); + let mut buffered = std::io::BufWriter::with_capacity(JSON_CHUNK, &mut scan); + match v1.as_ref() { + Some(v) => { + if pretty { + serde_json::to_writer_pretty(&mut buffered, v) + } else { + serde_json::to_writer(&mut buffered, v) + } + } + None => { + if pretty { + serde_json::to_writer_pretty(&mut buffered, &d) + } else { + serde_json::to_writer(&mut buffered, &d) + } + } + } + .map_err(std::io::Error::other)?; + buffered.flush()?; + drop(buffered); + let used = std::mem::take(&mut scan.keys); + Ok(images.unwrap_or_else(|| entries.images(&used, &mut out_blobs))) + }) + .map_err(encode_err)?; if o.compress { let json = out.written().unwrap_or(0); let tail: Vec = out_blobs.parts().iter().map(|p| p.bytes.len() as u64).collect(); @@ -409,13 +420,7 @@ pub fn save_to(doc: &Document, o: &SaveOptions, w: impl Write) -> Result<(), For return Err(FormatError::TooBigToCompress(format!("{} MB of images, at most {} MB", out_blobs.len() >> 20, MAX_BLOBS >> 20))); } } - if !out_blobs.is_empty() { - out.write_all(BLOB_MAGIC).map_err(encode_err)?; - for part in out_blobs.parts() { - out.packed(is_packed(&part.mime)).map_err(encode_err)?; - out.write_all(part.bytes).map_err(encode_err)?; - } - } + out_blobs.write_to_with(&mut out, |out, mime| out.packed(is_packed(mime))).map_err(encode_err)?; out.finish().map_err(encode_err) } @@ -450,10 +455,6 @@ fn encode_err(e: impl std::fmt::Display) -> FormatError { FormatError::Encode(e.to_string()) } -fn to_json(v: &impl Serialize, pretty: bool) -> Result, FormatError> { - if pretty { serde_json::to_vec_pretty(v) } else { serde_json::to_vec(v) }.map_err(encode_err) -} - /// The document's JSON: its version 1 form `v1`, else `d` (generic, not `dyn Write`: serde_json /// writes token by token). fn write_body(w: impl Write, v1: Option<&serde_json::Value>, d: &Document, pretty: bool) -> Result<(), FormatError> { @@ -467,33 +468,6 @@ fn write_json(w: impl Write, v: &impl Serialize, pretty: bool) -> Result<(), For if pretty { serde_json::to_writer_pretty(w, v) } else { serde_json::to_writer(w, v) }.map_err(encode_err) } -/// The file's top-level object, written member by member (the document is streamed in). -struct Envelope { - pretty: bool, - first: bool, -} - -impl Envelope { - fn field(&mut self, out: &mut impl Write, key: &str, value: &impl Serialize) -> Result<(), FormatError> { - let json = to_json(value, self.pretty)?; - self.key(out, key)?; - Indent { inner: out, on: self.pretty }.write_all(&json).map_err(encode_err) - } - - /// The start of member `key` (a plain name): its value follows, indented one level when - /// pretty (as serde_json would: see [`Indent`]). - fn key(&mut self, out: &mut impl Write, key: &str) -> Result<(), FormatError> { - let sep: &[u8] = if std::mem::take(&mut self.first) { b"{" } else { b"," }; - let indent: &[u8] = if self.pretty { b"\n " } else { b"" }; - let colon: &[u8] = if self.pretty { b"\": " } else { b"\":" }; - [sep, indent, b"\"", key.as_bytes(), colon].iter().try_for_each(|part| out.write_all(part)).map_err(encode_err) - } - - fn finish(self, out: &mut impl Write) -> Result<(), FormatError> { - out.write_all(if self.pretty { b"\n}" } else { b"}" }).map_err(encode_err) - } -} - pub fn load(bytes: &[u8]) -> Result { load_info(bytes).map(|(doc, _)| doc) } diff --git a/crates/format/src/stream.rs b/crates/format/src/stream.rs index bed508601f..bc24a67aed 100644 --- a/crates/format/src/stream.rs +++ b/crates/format/src/stream.rs @@ -2,10 +2,9 @@ //! not) and the data after it is copied in from the document's own buffers, so a save holds no //! copy of the file in memory besides what the caller's writer keeps. -use std::collections::HashSet; use std::io::{self, Write}; -use flate2::{Compress, Compression, Crc, FlushCompress, Status}; +use craft_gzip::Gz; /// The output of a save: plain, or gzip ([`Gz`]). pub(crate) enum Out { @@ -26,7 +25,7 @@ impl Out { pub(crate) fn written(&self) -> Option { match self { Out::Plain(_) => None, - Out::Gz(gz) => Some(gz.total), + Out::Gz(gz) => Some(gz.written()), } } @@ -61,299 +60,3 @@ impl Write for Out { } } } - -/// Bytes of compressed output gathered before they go to the writer. -const OUT_CHUNK: usize = 64 << 10; - -/// A gzip stream, written as [`flate2::write::GzEncoder`] at the default level writes it (the -/// same header and the same data; the deflate blocks are the same too where flate2 deflates with -/// miniz_oxide, not with zlib-rs, which writes them by how the data is fed), except that data which -/// is compressed already ([`Gz::packed`]) is stored as it is: the default level spends a second -/// or more per photo on it for next to nothing, and makes it slower to unpack. Where the level -/// changes the deflate blocks so far end with a sync flush and a fresh compressor writes on, -/// which makes one valid deflate stream that every reader unpacks. -pub(crate) struct Gz { - out: W, - deflate: Compress, - /// What `deflate` writes: stored blocks (packed data), else the default level. - stored: bool, - crc: Crc, - buf: Vec, - /// Bytes written (unpacked). - total: u64, -} - -impl Gz { - pub(crate) fn new(mut out: W) -> io::Result { - // flate2's header for the default level: no name, no time, unknown OS. - out.write_all(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255])?; - Ok(Self { - out, - deflate: Compress::new(Compression::default(), false), - stored: false, - crc: Crc::new(), - buf: Vec::with_capacity(OUT_CHUNK), - total: 0, - }) - } - - /// Run the compressor over `input` with `flush` until it has taken it all (and, flushing, - /// written everything out). - fn deflate(&mut self, mut input: &[u8], flush: FlushCompress) -> io::Result<()> { - loop { - if self.buf.len() == self.buf.capacity() { - self.out.write_all(&self.buf)?; - self.buf.clear(); - } - let (before_in, before_out) = (self.deflate.total_in(), self.deflate.total_out()); - let status = self.deflate.compress_vec(input, &mut self.buf, flush).map_err(io::Error::other)?; - let taken = usize::try_from(self.deflate.total_in() - before_in).unwrap_or(input.len()).min(input.len()); - input = input.get(taken..).unwrap_or_default(); - let made = self.deflate.total_out() - before_out; - let full = self.buf.len() == self.buf.capacity(); - match flush { - FlushCompress::None if input.is_empty() => return Ok(()), - FlushCompress::Finish if status == Status::StreamEnd => return Ok(()), - // A flush is done once it left room in the output. - FlushCompress::Sync if input.is_empty() && !full => return Ok(()), - _ => {} - } - if taken == 0 && made == 0 && !full { - return Err(io::Error::other("the compressor made no progress")); - } - } - } - - /// What is written next is compressed already (stored as it is), or not (compressed at the - /// default level). - fn packed(&mut self, packed: bool) -> io::Result<()> { - if packed == self.stored { - return Ok(()); - } - self.deflate(&[], FlushCompress::Sync)?; - self.deflate = Compress::new(if packed { Compression::none() } else { Compression::default() }, false); - self.stored = packed; - Ok(()) - } - - fn finish(mut self) -> io::Result<()> { - self.deflate(&[], FlushCompress::Finish)?; - self.out.write_all(&self.buf)?; - self.out.write_all(&self.crc.sum().to_le_bytes())?; - self.out.write_all(&self.crc.amount().to_le_bytes())?; - self.out.flush() - } -} - -impl Write for Gz { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.crc.update(buf); - self.total += buf.len() as u64; - self.deflate(buf, FlushCompress::None) - } - - fn flush(&mut self) -> io::Result<()> { - // Flushing would end a deflate block: the stream is flushed when it is finished. - Ok(()) - } -} - -/// Indents JSON text written through it one level (two spaces after each newline), as a member -/// of the file's top-level object; newlines only occur between tokens, inside strings they are -/// escaped. -pub(crate) struct Indent { - pub(crate) inner: W, - pub(crate) on: bool, -} - -impl Write for Indent { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - if !self.on { - return self.inner.write_all(buf); - } - let mut lines = buf.split(|&b| b == b'\n'); - self.inner.write_all(lines.next().unwrap_or_default())?; - for line in lines { - self.inner.write_all(b"\n ")?; - self.inner.write_all(line)?; - } - Ok(()) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -/// The member that names an image. -const TAG: &[u8] = b"\"key\":"; - -/// Passes JSON text through, collecting the string values of every `"key": "…"` member at any -/// depth (what the images a document uses are named by). Quotes inside JSON strings are escaped, -/// so every match is a real member. -pub(crate) struct KeyScan { - pub(crate) inner: W, - pub(crate) keys: HashSet, - /// Looking for keys (else it only passes the text on). - pub(crate) active: bool, - /// How much of [`TAG`] the last bytes matched. - matched: usize, - /// Right after a tag: skipping whitespace to its value. - after_tag: bool, - /// The value string so far, quotes included. - value: Option>, - escaped: bool, -} - -impl KeyScan { - pub(crate) fn new(inner: W) -> Self { - Self { inner, keys: HashSet::new(), active: true, matched: 0, after_tag: false, value: None, escaped: false } - } - - fn scan(&mut self, buf: &[u8]) { - if !self.active { - return; - } - let mut i = 0; - while let Some(&b) = buf.get(i) { - // Nothing in progress: skip to the next quote. - if self.matched == 0 && !self.after_tag && self.value.is_none() { - match buf.get(i..).and_then(|r| r.iter().position(|&c| c == b'"')) { - Some(at) => i += at, - None => return, - } - self.matched = 1; - i += 1; - continue; - } - self.step(b); - i += 1; - } - } - - fn step(&mut self, b: u8) { - if let Some(v) = self.value.as_mut() { - v.push(b); - if self.escaped { - self.escaped = false; - } else if b == b'\\' { - self.escaped = true; - } else if b == b'"' - && let Some(v) = self.value.take() - && let Ok(s) = serde_json::from_slice::(&v) - { - self.keys.insert(s); - } - } else if self.after_tag && !b.is_ascii_whitespace() { - self.after_tag = false; - if b == b'"' { - self.value = Some(vec![b]); - } - } - if TAG.get(self.matched) == Some(&b) { - self.matched += 1; - if self.matched == TAG.len() { - self.matched = 0; - self.after_tag = true; - self.value = None; - self.escaped = false; - } - } else { - self.matched = usize::from(b == b'"'); - } - } -} - -impl Write for KeyScan { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.write_all(buf)?; - Ok(buf.len()) - } - - fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - self.scan(buf); - self.inner.write_all(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -#[cfg(test)] -mod tests { - use proptest::prelude::*; - - use super::*; - - /// How the keys were found before saves were streamed: in the whole JSON text at once. - fn string_members(json: &[u8]) -> HashSet { - let mut out = HashSet::new(); - let mut rest = json; - while let Some(at) = rest.windows(TAG.len()).position(|w| w == TAG) { - rest = rest.get(at + TAG.len()..).unwrap_or_default(); - let value = rest.trim_ascii_start(); - if value.first() == Some(&b'"') - && let Some(Ok(s)) = serde_json::Deserializer::from_slice(value).into_iter::().next() - { - out.insert(s); - } - } - out - } - - /// The keys `KeyScan` finds in `json` written in pieces of `chunk` bytes. - fn scanned(json: &[u8], chunk: usize) -> HashSet { - let mut scan = KeyScan::new(Vec::new()); - for piece in json.chunks(chunk.max(1)) { - scan.write_all(piece).unwrap(); - } - assert_eq!(scan.inner, json, "the text passes through"); - scan.keys - } - - #[test] - fn finds_the_keys_the_whole_text_search_found() { - let v = serde_json::json!({"key": "a", "x": [{"key": "b \"q\" \\ é"}, {"monkey": "no"}, {"k": "key"}], "s": "\"key\": \"no\"", "key2": "n", "o": {"key": 3}}); - for json in [serde_json::to_vec(&v).unwrap(), serde_json::to_vec_pretty(&v).unwrap()] { - let want = string_members(&json); - assert_eq!(want, HashSet::from(["a".to_string(), "b \"q\" \\ é".to_string()])); - for chunk in [1, 2, 3, 7, 64, json.len()] { - assert_eq!(scanned(&json, chunk), want, "chunk {chunk}"); - } - } - } - - fn arb_json() -> impl Strategy { - let key = prop::sample::select(vec!["key", "k", "kkey", "key ", "x"]).prop_map(str::to_string); - let leaf = prop_oneof![ - Just(serde_json::Value::Null), - any::().prop_map(serde_json::Value::from), - "[a-z\"\\\\: ké\n]{0,8}".prop_map(serde_json::Value::from), - ]; - leaf.prop_recursive(4, 32, 6, move |inner| { - prop_oneof![ - prop::collection::vec(inner.clone(), 0..5).prop_map(serde_json::Value::from), - prop::collection::vec((key.clone(), inner), 0..5).prop_map(|m| serde_json::Value::Object(m.into_iter().collect())), - ] - }) - } - - proptest! { - #[test] - fn scanning_in_pieces_finds_what_the_whole_text_search_found(v in arb_json(), chunk in 1usize..40, pretty in any::()) { - let json = if pretty { serde_json::to_vec_pretty(&v) } else { serde_json::to_vec(&v) }.unwrap(); - prop_assert_eq!(scanned(&json, chunk), string_members(&json)); - } - } -} From d1801950c53defea7beba29ee92e037affacc39d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:18:42 -0800 Subject: [PATCH 11/41] Graph Data: a column drag keeps its width while scrolling and ends where released A column's dragged width is now its width when the drag started plus how far the pointer has moved since. Before, it was measured from the sheet's scroll origin, so with the sheet scrolled to its right end a held drag that narrowed a column kept narrowing it to 0 as the scroll offset followed the narrower sheet. A release that comes in the same frame as the last move now sets the width to where the pointer was released, also for an edge dragged out of view. Entering the width Column Width already shows, with Enter, now sets every column, the dragged ones too. Clicking into the field and away without a new value keeps the columns' own widths. --- crates/ui-egui/src/dialogs/graph_data.rs | 130 +++++++++++++++++++++-- 1 file changed, 124 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 935ce60bd9..90cc7d9f55 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -437,7 +437,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(12.0); widgets::dim_label(ui, tl!("Column Width:")); let mut w = d.fields.get("width").and_then(Value::as_u64).unwrap_or(7); - if ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)).changed() { + let r = ui.add(egui::DragValue::new(&mut w).range(0..=MAX_WIDTH)); + // A value entered with Enter sets every column, also when it is the width shown. Leaving the + // field without a new value keeps the columns' own widths. + if r.changed() || (r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) { set_width(d, w); } }); @@ -559,18 +562,38 @@ fn sheet(ui: &mut egui::Ui, d: &Dialog) -> SheetInput { } } // A column's right edge, over the rows in view: dragging it sets that column's width. The - // edge being dragged stays in the loop when it leaves the view, so the drag goes on. + // edge being dragged stays in the loop when it leaves the view, so the drag goes on, also in + // the frame it is released. let (top, bottom) = (origin.y + r0 as f32 * ch, origin.y + r1 as f32 * ch); - let dragged = ui.ctx().dragged_id().and_then(|id| (0..cols).find(|&c| edge_id(c) == id)).filter(|c| !(c0..c1).contains(c)); + let dragged = ui + .ctx() + .dragged_id() + .or_else(|| ui.ctx().drag_stopped_id()) + .and_then(|id| (0..cols).find(|&c| edge_id(c) == id)) + .filter(|c| !(c0..c1).contains(c)); for c in (c0..c1).chain(dragged) { let gap = origin.x + left(c + 1) - 0.5; let edge = egui::Rect::from_x_y_ranges(gap - 3.0..=gap + 3.0, top..=bottom); let h = ui.interact(edge, edge_id(c), egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeColumn); + // The width is the column's width when the drag started plus how far the pointer has + // moved since, so a scroll offset that changes with the sheet's width doesn't change it. + if h.drag_started() + && let Some(p) = ui.input(|i| i.pointer.press_origin()).or_else(|| h.interact_pointer_pos()) + { + ui.data_mut(|m| m.insert_temp(edge_id(c), (p.x, left(c + 1) - left(c) - 1.0))); + } if h.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeColumn); - if let Some(p) = h.interact_pointer_pos() { - resized = Some((c, px_digits(p.x - origin.x - left(c)))); - } + } + // The release can come in the same frame as the last move: it sets the width too. + if (h.dragged() || h.drag_stopped()) + && let Some(p) = h.interact_pointer_pos() + && let Some((x0, w0)) = ui.data(|m| m.get_temp::<(f32, f32)>(edge_id(c))) + { + resized = Some((c, px_digits(w0 + p.x - x0))); + } + if h.drag_stopped() { + ui.data_mut(|m| m.remove::<(f32, f32)>(edge_id(c))); } } }); @@ -834,6 +857,101 @@ mod tests { assert_eq!(digits(&app), [9; 4], "Cell Style sets every column"); } + /// A drag whose last move comes in the frame it is released sets the width to where it was + /// released. A held drag on a sheet scrolled to its right end keeps its width while the scroll + /// offset follows the narrower sheet. Entering the width that Column Width shows sets every + /// column, the dragged ones too. + #[test] + fn a_column_drag_ends_where_released_and_the_shown_width_entered_sets_every_column() { + let rows: Vec> = (0..3).map(|i| vec![i as f64; 30]).collect(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "rows": rows})).unwrap(); + open(&mut app).unwrap(); + let cols = extent(app.ui.dialog.as_ref().unwrap(), (0, 1)).1; + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let edge = |c: usize| ctx.read_response(edge_id(c)).map(|r| r.rect).unwrap_or_else(|| panic!("column {c}'s edge is drawn")); + let digits = |app: &VectorcraftApp, c: usize| col_digits(app.ui.dialog.as_ref().unwrap(), c); + for _ in 0..3 { + frame(&mut app, vec![]); + } + // The last move and the release in one frame: 70 points is 10 digits. + let at = edge(1).center(); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]); + let to = at + egui::vec2(70.0, 0.0); + frame(&mut app, vec![egui::Event::PointerMoved(to), button(to, false)]); + frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + assert_eq!(digits(&app, 1), 17, "the width where the drag was released"); + // Scroll the sheet to its right end, then narrow a column by 5 digits and hold the pointer still. + let over = edge(1).center() - egui::vec2(20.0, 0.0); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-100_000.0, 0.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + frame(&mut app, vec![egui::Event::PointerMoved(over), wheel]); + for _ in 0..30 { + frame(&mut app, vec![]); + } + let c = cols - 2; + let at = edge(c).center(); + frame(&mut app, vec![egui::Event::PointerMoved(at), button(at, true)]); + for step in 1..=5 { + frame(&mut app, vec![egui::Event::PointerMoved(at - egui::vec2(7.0 * step as f32, 0.0))]); + } + for _ in 0..10 { + frame(&mut app, vec![]); + } + assert_eq!(digits(&app, c), 2, "a held drag keeps its width"); + let to = at - egui::vec2(35.0, 0.0); + frame(&mut app, vec![button(to, false)]); + frame(&mut app, vec![egui::Event::PointerMoved(egui::pos2(0.0, 0.0))]); + assert_eq!(digits(&app, c), 2, "the width where the drag was released"); + // Column Width still shows 7: entering 7 there sets every column to 7. + let nodes = frame(&mut app, vec![]); + let label = nodes + .iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::Label && n.value() == Some("Column Width:")) + .and_then(|(_, n)| n.bounds()) + .expect("the Column Width label is drawn"); + let field = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::SpinButton) + .filter_map(|(_, n)| n.bounds()) + .filter(|b| b.x0 >= label.x1 && b.y0 < label.y1 && b.y1 > label.y0) + .min_by(|a, b| a.x0.total_cmp(&b.x0)) + .expect("the Column Width field is drawn"); + let at = egui::pos2(((field.x0 + field.x1) / 2.0) as f32, ((field.y0 + field.y1) / 2.0) as f32); + let click = |app: &mut VectorcraftApp, at| { + frame(app, vec![egui::Event::PointerMoved(at), button(at, true)]); + frame(app, vec![button(at, false)]); + frame(app, vec![]); + }; + // Clicking into the field and away from it, without a new value, keeps the columns' widths. + click(&mut app, at); + click(&mut app, egui::pos2(((label.x0 + label.x1) / 2.0) as f32, ((label.y0 + label.y1) / 2.0) as f32)); + assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (17, 2, 7), "leaving the field keeps the widths"); + click(&mut app, at); + frame(&mut app, vec![egui::Event::Text("7".into())]); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame(&mut app, vec![enter]); + frame(&mut app, vec![]); + assert_eq!((digits(&app, 1), digits(&app, c), digits(&app, 0)), (7, 7, 7), "Column Width sets every column"); + } + #[test] fn a_column_width_in_points_maps_to_whole_digits() { for n in 0..=MAX_WIDTH { From 4f09041edc55696daf4f2ed439619f0a3874506d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:31:47 -0800 Subject: [PATCH 12/41] 3D and Materials: the Bevel section's Reset restores only the bevel settings A Reset button next to Extrude & Bevel's Bevel heading, on the Object tab of the options dialog and of the 3D and Materials panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults. Depth, Twist, Taper, Cap, the rotation, the lights and the graphics keep their values. In the panel the reset goes to each selected Extrude & Bevel as one undo step. The button is unavailable while every bevel setting is at its default, and a setting the selected effects hold with different values counts as changed. --- crates/ui-egui/src/dialogs/revolve.rs | 49 ++++++++++++++++++++- crates/ui-egui/src/dialogs/revolve/tests.rs | 36 +++++++++++++++ crates/ui-egui/src/panels/tests_three_d.rs | 43 ++++++++++++++++++ docs/target-app-parity.md | 1 + docs/three-d.md | 1 + 5 files changed, 129 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 8978805ac8..885135bf18 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -248,7 +248,7 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { number(ui, d, "taper", tl!("Taper"), (1.0, 100.0), "%", 1, None); choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]); ui.add_space(10.0); - heading(ui, c3("Bevel")); + bevel_heading(ui, d); let shapes: Vec<(Value, &str)> = super::effect::own_choices(EXTRUDE, "bevel", false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect(); choice(ui, d, "bevel", tl!("Bevel Shape"), &shapes); @@ -262,6 +262,53 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { }); } +/// Extrude & Bevel's bevel settings (every parameter named `bevel…`) with their defaults. +fn bevel_defaults() -> serde_json::Map { + match vectorcraft_effects::default_params(EXTRUDE) { + Some(Value::Object(m)) => m.into_iter().filter(|(k, _)| k.starts_with("bevel")).collect(), + _ => serde_json::Map::new(), + } +} + +/// Does any setting in `defaults` differ from its default in `d`? A setting the 3D and Materials +/// panel's selected effects hold with different values (null) counts as changed. +fn differs_from(d: &Dialog, defaults: &serde_json::Map) -> bool { + defaults.iter().any(|(k, v)| match (d.fields.get(k), v.as_f64()) { + (Some(Value::Null), _) => true, + (_, Some(default)) => (d.f64(k, default) - default).abs() > 1e-6, + (field, None) => field.is_some_and(|f| f != v), + }) +} + +/// The Bevel heading with its Reset button, which puts every bevel setting back to its default and +/// leaves the other settings as they are. The button is off while every bevel setting is at its +/// default. +fn bevel_heading(ui: &mut egui::Ui, d: &mut Dialog) { + let defaults = bevel_defaults(); + let changed = differs_from(d, &defaults); + let mut reset = false; + ui.horizontal(|ui| { + heading(ui, c3("Bevel")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(changed, |ui| { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(56.0, 20.0), Sense::hover()); + let response = ui.interact(r, Id::unique("revolve-reset-bevel"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset"))); + if response.hovered() { + ui.painter().rect_filled(r, 3.0, t.hover); + } + let color = if ui.is_enabled() { t.text } else { t.text_disabled }; + ui.painter().text(r.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, tl!("Reset"), FontId::proportional(11.5), color); + reset = response.clicked(); + }); + }); + }); + if reset { + d.fields.extend(defaults); + } +} + /// Rotation presets, rotation and perspective for Extrude & Bevel, Inflate and Rotate. fn view_controls(ui: &mut egui::Ui, d: &mut Dialog) { heading(ui, tl!("Rotation")); diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index fd802f83f0..1a879f2618 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -472,6 +472,42 @@ fn extrude_bevel_options_enable_with_a_bevel_shape() { assert_eq!(h.response(("revolve-reset", "bevelWidth")), width); } +#[test] +fn the_bevel_reset_restores_the_bevel_settings_and_keeps_the_others() { + let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", vectorcraft_effects::EXTRUDE, vec2(1400.0, 1000.0)); + let before = h.app.session.doc().unwrap().doc.clone(); + h.settle(); + let enabled = |h: &Harness| h.ctx.read_response(Id::unique("revolve-reset-bevel")).unwrap().enabled(); + assert!(!enabled(&h), "every bevel setting at its default: Reset is off"); + let changed = json!({"bevel": "step", "bevelWidth": 12.0, "bevelHeight": 3.0, "bevelRepeat": 4, "bevelSpace": 30.0, "bevelInside": true, "bevelBothSides": true, "depth": 90.0, "twist": 45.0, "rotationX": 10.0}); + h.app.ui.dialog.as_mut().unwrap().fields.extend(changed.as_object().unwrap().clone()); + h.settle(); + assert!(enabled(&h)); + h.click(h.response("revolve-reset-bevel").center()); + let defaults = vectorcraft_effects::default_params(vectorcraft_effects::EXTRUDE).unwrap(); + let dialog = h.app.ui.dialog.as_ref().unwrap(); + for key in ["bevel", "bevelWidth", "bevelHeight", "bevelRepeat", "bevelSpace", "bevelInside", "bevelBothSides"] { + assert_eq!(dialog.fields.get(key), defaults.get(key), "reset: {key}"); + } + for key in ["depth", "twist", "rotationX"] { + assert_eq!(dialog.fields.get(key), changed.get(key), "kept: {key}"); + } + assert!(!enabled(&h), "Reset turns itself off"); + // One bevel setting off its default is enough to turn Reset on again. + h.app.ui.dialog.as_mut().unwrap().fields.insert("bevelBothSides".into(), json!(true)); + h.settle(); + assert!(enabled(&h)); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let params = vectorcraft_effects::merged_params( + vectorcraft_effects::EXTRUDE, + &state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0].params, + ); + assert_eq!((params["depth"].clone(), params["bevelBothSides"].clone(), params["bevel"].clone()), (json!(90.0), json!(true), json!("none"))); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc().unwrap().doc, before); +} + #[test] fn cap_checkbox_previews_resets_and_respects_cancel_and_one_step_undo() { for confirm in [false, true] { diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 6146bc4852..b5e08663e7 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -426,6 +426,49 @@ fn a_mixed_checkbox_shows_a_dash_and_another_change_keeps_each_effects_value() { assert!(named(&controls(&mut app, &ctx), "Add Light").is_disabled()); } +/// The Bevel heading's Reset sets every bevel setting back to its default on each selected Extrude & +/// Bevel, as one undo step, and leaves Depth and the rotation as each effect has them. With every +/// bevel setting at its default it is off and records nothing. +#[test] +fn the_bevel_reset_restores_only_the_bevel_settings_of_each_selected_effect() { + use crate::panels::tests_appearance::click; + let mut app = app(); + let bevelled = json!({"bevel": "rounded", "bevelWidth": 9.0, "bevelHeight": 6.0, "bevelRepeat": 3, "bevelSpace": 20.0, "bevelInside": true, "bevelBothSides": true, "depth": 70.0, "rotationX": 15.0}); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": bevelled})).unwrap(); + let a = app.session.active().unwrap().selection.objects[0].0; + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"bevel": "cove", "bevelWidth": 2.0, "depth": 30.0}})) + .unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.enable_accesskit(); + let nodes = controls(&mut app, &ctx); + let reset = named(&nodes, "Reset"); + assert!(!reset.is_disabled(), "changed bevel settings turn Reset on"); + let at = reset.bounds().map(|r| egui::pos2(((r.x0 + r.x1) / 2.0) as f32, ((r.y0 + r.y1) / 2.0) as f32)).unwrap(); + let history = undo_len(&app); + click(&ctx, &mut app, at, show); + assert_eq!(undo_len(&app), history + 1, "one undo step for both objects"); + let defaults = vectorcraft_effects::default_params("threeD.extrude").unwrap(); + let merged = |app: &VectorcraftApp, id: u64| { + let params = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params.clone(); + vectorcraft_effects::merged_params("threeD.extrude", ¶ms) + }; + for id in [a, b] { + for key in ["bevel", "bevelWidth", "bevelHeight", "bevelRepeat", "bevelSpace", "bevelInside", "bevelBothSides"] { + assert_eq!(merged(&app, id)[key], defaults[key], "{key} of {id}"); + } + } + assert_eq!((merged(&app, a)["depth"].clone(), merged(&app, b)["depth"].clone()), (json!(70.0), json!(30.0))); + assert_eq!(merged(&app, a)["rotationX"], 15.0); + let nodes = controls(&mut app, &ctx); + assert!(named(&nodes, "Reset").is_disabled(), "every bevel setting at its default: Reset is off"); + let history = undo_len(&app); + click(&ctx, &mut app, at, show); + assert_eq!(undo_len(&app), history, "an unavailable Reset records nothing"); +} + /// Revolve's Cap checkbox shows a dash when the selected effects disagree on it. #[test] fn a_mixed_revolve_cap_shows_a_dash() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 72de21a43c..ee77be41e0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -594,6 +594,7 @@ since 2026-10-01. - 3D shadows: with Shadows on, Revolve, Extrude & Bevel, Inflate and Rotate cast the shadow from the faces kept by the build that draws each solid, so drawing an object builds each of its solids once. The art and the shadow are unchanged. Evidence: `crates/three-d/src/shadow/tests.rs` (`a_solid_and_its_shadow_are_built_once` and the tests that compare each solid and its shadow with the two built apart), `solids::tests_shadow::a_shadowed_3d_object_builds_each_solid_once`, `solids::tests_shadow::the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it`, `revolve::tests::the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it`. Scores unchanged. - 3D shadows: in Revolve, Extrude & Bevel, Inflate and Rotate, a fill, stroke or member whose opacity is NaN or infinite casts no part of the shadow, as one at 0 % does, whether the shadow is cast from the solids drawn or from solids built for it alone; the art beside it still casts. This is VectorCraft's own rule. Evidence: `solids::tests_shadow::art_whose_opacity_is_not_a_finite_number_casts_no_shadow`, `revolve::tests::a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow`. Scores unchanged. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. +- 3D and Materials › Object › Bevel › Reset: the button next to Extrude & Bevel's Bevel heading, in the options dialog and the panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults and leaves the other settings as they are, as one undo step in the panel; it is unavailable while every bevel setting is at its default ([three-d.md](three-d.md#extrude--bevel)); `crates/ui-egui/src/dialogs/revolve/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. diff --git a/docs/three-d.md b/docs/three-d.md index 2861bee0b7..37693c6e0a 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -100,6 +100,7 @@ object is where the art was. | Repeat, Space | The cross-section repeated 1–32 times across the width, with a share (0–90 %) of the width flat between repeats. | | Bevel Inside | The bevel carved into the shape (the front face shrinks) instead of added around it (the walls stand outside the art). | | Bevel both sides | The back is bevelled too. | +| Reset | Next to the Bevel heading, in the dialog and the panel. It sets every bevel setting above back to its default (Bevel Shape None, Width and Height 4 pt, Repeat 1, Space 0 %, both checkboxes off) and leaves Depth, Twist, Taper, Cap, the rotation, the lights and the graphics as they are, as the public [3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html) page describes. In the panel it sets them on each selected Extrude & Bevel as one undo step. It is unavailable while every bevel setting is at its default. | Holes stay holes, with walls of their own. Bevels move each corner along its bisector. A corner the bevel opens (a sharp point with the bevel outside, a narrow notch with it inside) whose miter would reach past four times the width is From f1f4d629e89881bac271d6b4572be4254e958b53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:39:43 -0800 Subject: [PATCH 13/41] Panels: the double triangle on a panel's tab strip cycles its display sizes A double triangle at the right end of the tab strip of Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency steps the active panel through its display sizes. The sizes are the states the panel menu's Show/Hide Options items set (Transparency: thumbnails and options, thumbnails alone, neither), largest first, and the smallest goes back to the largest. window.panel.cycleOptions {panel} does the same and returns {panel, size, sizes}. An unknown panel or a panel without sizes is an error and changes nothing. Docs: docs/mcp.md, docs/control-protocol.md, docs/ui-parity.md. --- crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + 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/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 1 + 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/menus/ui_commands.rs | 6 + crates/ui-egui/src/panel_docking.rs | 18 ++- crates/ui-egui/src/panel_docking/sizes.rs | 128 ++++++++++++++++++++++ crates/ui-egui/src/panel_docking/tests.rs | 113 +++++++++++++++++++ docs/control-protocol.md | 1 + docs/mcp.md | 8 ++ docs/ui-parity.md | 1 + 36 files changed, 353 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/panel_docking/sizes.rs diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ecbdf780fb..ae0f0c3a5a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -650,6 +650,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", ), + ( + "window.panel.cycleOptions", + "Cycle Display Sizes", + "", + "{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}", + ), ( "window.panel.float", "Float Panel", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..e6d1474af0 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5150,6 +5150,7 @@ effect Soft Меко Change Panel Layout Промяна на оформлението на панела Close Panel Затваряне на панела Collapse Panel Group Свиване на групата панели + Cycle Display Sizes Превключване на размерите на показване Move Panel Преместване на панела Group with Групиране с Resize panels Преоразмеряване на панели diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..b46a82203a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1015,6 +1015,7 @@ Change Panel Layout Promijeni raspored panela Close Panel Zatvori panel Collapse Panel Group Skupi grupu panela + Cycle Display Sizes Mijenjaj veličine prikaza Move Panel Pomakni panel Group with Grupiši sa Resize panels Promijeni veličinu panela diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..0865ac739e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -772,6 +772,7 @@ antiAlias Sharp Nítid Preserve Numbers Conserva els números Coarse Dots Punts gruixuts Collapse Panel Group Replega el grup de panells + Cycle Display Sizes Alterna les mides de visualització Collapse Panels to Icons Replega els panells a icones Collapse to Icons Replega a icones Collate Intercala @@ -6542,6 +6543,8 @@ digits Malayalam Malaiàlam @msg unknown option `{path}.{k}` opció desconeguda `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressions desconegudes `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` panell desconegut `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` no té mides de visualització per alternar +@msg the panels are not shown els panells no es mostren @msg panels can't be shown in Presentation Mode els panells no es poden mostrar en el mode de presentació @msg unknown parameter `{key}`; did you mean `{near}`? paràmetre desconegut `{key}`; volies dir `{near}`? @msg unknown parameter `{key}`; the command takes no parameters paràmetre desconegut `{key}`; l’ordre no admet cap paràmetre diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..b1cb31d433 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1035,6 +1035,7 @@ Change Panel Layout Změnit rozložení panelů Close Panel Zavřít panel Collapse Panel Group Sbalit skupinu panelů + Cycle Display Sizes Přepínat velikosti zobrazení Move Panel Přesunout panel Group with Seskupit s Resize panels Změnit velikost panelů @@ -5434,6 +5435,8 @@ imageTrace Outline Obrys @msg unknown option `{path}.{k}` neznámá možnost `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) neznámé přetisky `{o}` (preserve, simulate nebo discard) @msg unknown panel `{raw}` neznámý panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` nemá velikosti zobrazení k přepínání +@msg the panels are not shown panely nejsou zobrazeny @msg panels can't be shown in Presentation Mode v režimu prezentace nelze panely zobrazit @msg unknown preference `{key}` neznámá předvolba `{key}` @msg Preferences imported. Předvolby byly importovány. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..ec858a8d29 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1581,6 +1581,7 @@ Change Panel Layout Skift panelets layout Close Panel Luk panel Collapse Panel Group Skjul panelgruppe + Cycle Display Sizes Skift mellem visningsstørrelser Move Panel Flyt panel Group with Gruppér med Resize panels Tilpas størrelse på paneler @@ -5549,6 +5550,8 @@ imageTrace Outline Kontur @msg unknown option `{path}.{k}` ukendt indstilling `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ukendt overprint `{o}` (preserve, simulate eller discard) @msg unknown panel `{raw}` ukendt panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` har ingen visningsstørrelser at skifte mellem +@msg the panels are not shown panelerne vises ikke @msg unknown preference `{key}` ukendt præference `{key}` @msg Preferences imported. Præferencerne er importeret. @msg not a preferences file: {e} ikke en præferencefil: {e} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..4bc6a0c484 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5042,6 +5042,8 @@ theme Appearance Erscheinungsbild @msg unknown option `{path}.{k}` unbekannte Option `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) unbekannter Wert für overprints `{o}` (preserve, simulate oder discard) @msg unknown panel `{raw}` unbekanntes Bedienfeld `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` hat keine Anzeigegrößen zum Durchlaufen +@msg the panels are not shown die Bedienfelder werden nicht angezeigt @msg panels can't be shown in Presentation Mode im Präsentationsmodus können keine Bedienfelder angezeigt werden @msg unknown preference `{key}` unbekannte Voreinstellung `{key}` @msg Preferences imported. Voreinstellungen importiert. @@ -5501,6 +5503,7 @@ theme Appearance Erscheinungsbild Change Panel Layout Bedienfeldanordnung ändern Close Panel Bedienfeld schließen Collapse Panel Group Bedienfeldgruppe minimieren + Cycle Display Sizes Anzeigegrößen durchlaufen Move Panel Bedienfeld verschieben Group with Gruppieren mit Resize panel window Bedienfeldfenster skalieren diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..743cacbfac 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2726,6 +2726,7 @@ effect Soft Απαλό Change Panel Layout Αλλαγή διάταξης πάνελ Close Panel Κλείσιμο πάνελ Collapse Panel Group Σύμπτυξη ομάδας πάνελ + Cycle Display Sizes Εναλλαγή μεγεθών εμφάνισης Move Panel Μετακίνηση πάνελ Group with Ομαδοποίηση με Resize panels Αλλαγή μεγέθους πάνελ @@ -5082,6 +5083,8 @@ digits Malayalam Μαλαγιάλαμ @msg unknown option `{path}.{k}` άγνωστη επιλογή `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) άγνωστη επιλογή υπερεκτύπωσης `{o}` (preserve, simulate ή discard) @msg unknown panel `{raw}` άγνωστος πίνακας `{raw}` +@msg `{panel}` has no display sizes to cycle ο πίνακας `{panel}` δεν έχει μεγέθη εμφάνισης για εναλλαγή +@msg the panels are not shown οι πίνακες δεν εμφανίζονται @msg panels can't be shown in Presentation Mode τα πλαίσια δεν μπορούν να εμφανιστούν στη λειτουργία παρουσίασης @msg unknown preference `{key}` άγνωστη προτίμηση `{key}` @msg Preferences imported. Οι προτιμήσεις εισήχθησαν. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..bcc5114697 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5132,6 +5132,8 @@ axis Both Ambos @msg unknown option `{path}.{k}` opción desconocida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpresiones desconocidas `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` panel desconocido `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` no tiene tamaños de visualización que alternar +@msg the panels are not shown los paneles no se muestran @msg panels can't be shown in Presentation Mode los paneles no se pueden mostrar en el modo de presentación @msg unknown preference `{key}` preferencia desconocida `{key}` @msg Preferences imported. Preferencias importadas. @@ -5507,6 +5509,7 @@ axis Both Ambos Change Panel Layout Cambiar distribución de paneles Close Panel Cerrar panel Collapse Panel Group Contraer grupo de paneles + Cycle Display Sizes Alternar tamaños de visualización Move Panel Mover panel Group with Agrupar con Resize panels Cambiar tamaño de los paneles diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..05ec936c53 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1018,6 +1018,7 @@ Change Panel Layout Muuta paneelien asettelua Close Panel Sulje paneeli Collapse Panel Group Kutista paneeliryhmä + Cycle Display Sizes Vaihda näyttökokoa Move Panel Siirrä paneelia Group with Ryhmitä kohteen kanssa Resize panels Muuta paneelien kokoa @@ -5345,6 +5346,8 @@ imageTrace Outline Ääriviiva @msg unknown option `{path}.{k}` tuntematon asetus `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) tuntematon päällepainatusten käsittely `{o}` (preserve, simulate tai discard) @msg unknown panel `{raw}` tuntematon paneeli `{raw}` +@msg `{panel}` has no display sizes to cycle paneelissa `{panel}` ei ole vaihdettavia näyttökokoja +@msg the panels are not shown paneelit eivät ole näkyvissä @msg panels can't be shown in Presentation Mode paneeleja ei voi näyttää esitystilassa @msg unknown preference `{key}` tuntematon asetus `{key}` @msg Preferences imported. Asetukset tuotiin. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..2958fd842e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5109,6 +5109,8 @@ axis Both Les deux @msg unknown option `{path}.{k}` option inconnue `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) surimpressions inconnues `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` panneau inconnu `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` n’a pas de tailles d’affichage à parcourir +@msg the panels are not shown les panneaux ne sont pas affichés @msg panels can't be shown in Presentation Mode les panneaux ne peuvent pas être affichés en mode Présentation @msg unknown preference `{key}` préférence inconnue `{key}` @msg Preferences imported. Préférences importées. @@ -5503,6 +5505,7 @@ effect Soft Doux Change Panel Layout Modifier la disposition des panneaux Close Panel Fermer le panneau Collapse Panel Group Réduire le groupe de panneaux + Cycle Display Sizes Parcourir les tailles d’affichage Move Panel Déplacer le panneau Group with Regrouper avec Resize panels Redimensionner les panneaux diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..b97abaddb0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -611,6 +611,7 @@ Closing bracket with no opening one ખુલતા કૌંસ વગરનો બંધ થતો કૌંસ Coincidence: સંયોગ: Collapse Panel Group પેનલ ગ્રૂપ સંકોચો + Cycle Display Sizes પ્રદર્શન કદ બદલો Collapse Panels to Icons પેનલ્સને આઇકનમાં સંકોચો Collapse to Icons આઇકનમાં સંકોચો Collate ક્રમમાં ગોઠવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..5df953bd5c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -900,6 +900,7 @@ antiAlias Sharp शार्प Coarse Dots मोटे बिंदु Coincidence: संयोग: Collapse Panel Group पैनल समूह संक्षिप्त करें + Cycle Display Sizes प्रदर्शन आकार बदलें Collapse Panels to Icons सिकोड़ें करने के लिए पैनल Collapse to Icons प्रतीक के लिए पतन Collate कोलेट @@ -8620,6 +8621,8 @@ antiAlias Sharp शार्प @msg unknown overprints `{v}` (preserve, simulate or discard) अज्ञात ओवरप्रिंट `{v}` (preserve, simulate या discard) @msg unknown panel अज्ञात पैनल @msg unknown panel `{raw}` अज्ञात पैनल `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` के पास बदलने के लिए कोई प्रदर्शन आकार नहीं है +@msg the panels are not shown पैनल नहीं दिखाए गए हैं @msg panels can't be shown in Presentation Mode प्रस्तुति मोड में पैनल्स नहीं दिखाए जा सकते @msg unknown parameter `{key}`; did you mean `{near}`? अज्ञात पैरामीटर `{key}`; क्या आपको `{near}` का मतलब है? @msg unknown parameter `{key}`; the command takes no parameters अज्ञात पैरामीटर `{key}`; कमांड कोई पैरामीटर नहीं लेता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..5e4971048e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -686,6 +686,7 @@ font-technology Variable Változó Close Library Könyvtár bezárása Close Panel Panel bezárása Collapse Panel Group Panelcsoport összecsukása + Cycle Display Sizes Megjelenítési méretek váltása Close Path Útvonal lezárása Close paths when ends are within: Útvonalak lezárása, ha a végek távolsága legfeljebb: Clumped Csomós @@ -5949,6 +5950,8 @@ imageTrace Outline Körvonal @msg unknown option `{path}.{k}` ismeretlen beállítás: `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) ismeretlen felülnyomás-kezelés: `{o}` (preserve, simulate vagy discard) @msg unknown panel `{raw}` ismeretlen panel: `{raw}` +@msg `{panel}` has no display sizes to cycle a(z) `{panel}` panelnek nincsenek váltható megjelenítési méretei +@msg the panels are not shown a panelek nem láthatók @msg panels can't be shown in Presentation Mode bemutató módban a panelek nem jeleníthetők meg @msg unknown preference `{key}` ismeretlen beállítás: `{key}` @msg Preferences imported. A beállítások importálva. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..32edb91429 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -957,6 +957,7 @@ Change Panel Layout Ubah tata letak panel Close Panel Tutup panel Collapse Panel Group Ciutkan grup panel + Cycle Display Sizes Ganti ukuran tampilan Move Panel Pindahkan panel Group with Grupkan dengan Resize panels Ubah ukuran panel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..14c6122876 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5171,6 +5171,8 @@ axis Both Entrambi @msg unknown option `{path}.{k}` opzione sconosciuta `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) valore di sovrastampa sconosciuto `{o}` (preserve, simulate o discard) @msg unknown panel `{raw}` pannello sconosciuto `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` non ha dimensioni di visualizzazione da scorrere +@msg the panels are not shown i pannelli non sono visualizzati @msg panels can't be shown in Presentation Mode i pannelli non possono essere mostrati in modalità presentazione @msg unknown preference `{key}` preferenza sconosciuta `{key}` @msg Preferences imported. Preferenze importate. @@ -5548,6 +5550,7 @@ effect Regular Normale Change Panel Layout Modifica disposizione dei pannelli Close Panel Chiudi pannello Collapse Panel Group Comprimi gruppo di pannelli + Cycle Display Sizes Scorri le dimensioni di visualizzazione Move Panel Sposta pannello Group with Raggruppa con Resize panels Ridimensiona pannelli diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..49ee217a66 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5108,6 +5108,8 @@ swatch Bright Violet ビビッドバイオレット @msg give only one of onto, below and above onto、below、above のうち 1 つだけを指定してください @msg column must be true or a number from 1 column には true または 1 以上の数値を指定してください @msg unknown panel `{raw}` `{raw}` は不明なパネルです +@msg `{panel}` has no display sizes to cycle `{panel}` には切り替える表示サイズがありません +@msg the panels are not shown パネルが表示されていません @msg panels can't be shown in Presentation Mode プレゼンテーションモードではパネルを表示できません @msg x and y must both be numbers x と y はどちらも数値で指定してください @msg Downloaded {what} {what} をダウンロードしました @@ -5591,6 +5593,7 @@ effect Vertical 垂直 Change Panel Layout パネルの配置を変更 Close Panel パネルを閉じる Collapse Panel Group パネルグループを折りたたむ + Cycle Display Sizes 表示サイズを切り替え Move Panel パネルを移動 Group with グループ化先 Resize panels パネルのサイズを変更 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2864881e87..0aa64688f5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3008,6 +3008,7 @@ Change Panel Layout პანელების განლაგების შეცვლა Close Panel პანელის დახურვა Collapse Panel Group პანელების ჯგუფის აკეცვა + Cycle Display Sizes ჩვენების ზომების გადართვა Move Panel პანელის გადაადგილება Group with ერთად დაჯგუფება Resize panels პანელების ზომის შეცვლა @@ -6858,6 +6859,8 @@ font-technology Variable ცვლადი @msg unknown option `{path}.{k}` უცნობი პარამეტრი `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) უცნობი ზედდაბეჭდვა `{o}` (preserve, simulate ან discard) @msg unknown panel `{raw}` უცნობი პანელი `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` პანელს არ აქვს გადასართავი ჩვენების ზომები +@msg the panels are not shown პანელები არ ჩანს @msg panels can't be shown in Presentation Mode პრეზენტაციის რეჟიმში პანელების ჩვენება შეუძლებელია @msg unknown preference `{key}` უცნობი პარამეტრი `{key}` @msg Preferences imported. პარამეტრები იმპორტირებულია. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..69513cad5a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5035,6 +5035,8 @@ theme Appearance 외관 @msg give only one of onto, below and above onto, below, above 중 하나만 지정하세요 @msg column must be true or a number from 1 column은 true이거나 1 이상의 숫자여야 합니다 @msg unknown panel `{raw}` 알 수 없는 패널 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}`에는 전환할 표시 크기가 없습니다 +@msg the panels are not shown 패널이 표시되지 않습니다 @msg panels can't be shown in Presentation Mode 프레젠테이션 모드에서는 패널을 표시할 수 없습니다 @msg x and y must both be numbers x와 y는 모두 숫자여야 합니다 @msg Downloaded {what} {what}을(를) 다운로드했습니다 @@ -5516,6 +5518,7 @@ effect Vertical 세로 Change Panel Layout 패널 레이아웃 변경 Close Panel 패널 닫기 Collapse Panel Group 패널 그룹 접기 + Cycle Display Sizes 표시 크기 전환 Move Panel 패널 이동 Group with 함께 그룹화 Resize panels 패널 크기 조절 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..edef345ce1 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1477,6 +1477,7 @@ Change Panel Layout Paneelindeling wijzigen Close Panel Paneel sluiten Collapse Panel Group Paneelgroep samenvouwen + Cycle Display Sizes Weergavegrootten doorlopen Move Panel Paneel verplaatsen Group with Groeperen met Resize panels Panelen van formaat wijzigen @@ -5445,6 +5446,8 @@ imageTrace Outline Contour @msg unknown option `{path}.{k}` onbekende optie `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) onbekende overdruk `{o}` (preserve, simulate of discard) @msg unknown panel `{raw}` onbekend paneel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` heeft geen weergavegrootten om te doorlopen +@msg the panels are not shown de panelen worden niet getoond @msg unknown preference `{key}` onbekende voorkeur `{key}` @msg Preferences imported. Voorkeuren geïmporteerd. @msg not a preferences file: {e} geen voorkeurenbestand: {e} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..7ba2c97742 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -975,6 +975,7 @@ Change Panel Layout Zmień układ paneli Close Panel Zamknij panel Collapse Panel Group Zwiń grupę paneli + Cycle Display Sizes Przełącz rozmiary wyświetlania Move Panel Przesuń panel Group with Grupuj z Resize panels Zmień rozmiar paneli @@ -5260,6 +5261,8 @@ imageTrace Outline Kontur @msg unknown option `{path}.{k}` nieznana opcja `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) nieznana wartość nadruków `{o}` (preserve, simulate lub discard) @msg unknown panel `{raw}` nieznany panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` nie ma rozmiarów wyświetlania do przełączania +@msg the panels are not shown panele nie są wyświetlane @msg panels can't be shown in Presentation Mode w trybie prezentacji nie można wyświetlić paneli @msg unknown preference `{key}` nieznana preferencja `{key}` @msg Preferences imported. Zaimportowano preferencje. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..9a0fd94428 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3544,6 +3544,7 @@ imageTrace Outline Contorno Change Panel Layout Alterar Layout dos Painéis Close Panel Fechar Painel Collapse Panel Group Recolher Grupo de Painéis + Cycle Display Sizes Alternar Tamanhos de Exibição Move Panel Mover Painel Group with Agrupar com Resize panels Redimensionar painéis @@ -4490,6 +4491,8 @@ axis Both Ambos @msg unknown option `{path}.{k}` opção desconhecida `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) sobreimpressões desconhecidas `{o}` (preserve, simulate ou discard) @msg unknown panel `{raw}` painel desconhecido `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` não tem tamanhos de exibição para alternar +@msg the panels are not shown os painéis não estão sendo exibidos @msg panels can't be shown in Presentation Mode os painéis não podem ser mostrados no Modo de Apresentação @msg unknown preference `{key}` preferência desconhecida `{key}` @msg Preferences imported. Preferências importadas. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..b7ce3c4a99 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5169,6 +5169,8 @@ axis Both Оба @msg unknown option `{path}.{k}` неизвестный параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) неизвестные наложения `{o}` (preserve, simulate или discard) @msg unknown panel `{raw}` неизвестная панель `{raw}` +@msg `{panel}` has no display sizes to cycle у панели `{panel}` нет размеров отображения для переключения +@msg the panels are not shown панели не показаны @msg panels can't be shown in Presentation Mode в режиме презентации панели показать нельзя @msg unknown preference `{key}` неизвестная настройка `{key}` @msg Preferences imported. Настройки импортированы. @@ -5546,6 +5548,7 @@ axis Both Оба Change Panel Layout Изменить расположение панелей Close Panel Закрыть панель Collapse Panel Group Свернуть группу панелей + Cycle Display Sizes Переключить размеры отображения Move Panel Переместить панель Group with Сгруппировать с Resize panels Изменить размер панелей diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..343f65b7f5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5024,6 +5024,8 @@ axis Both Båda @msg unknown option `{path}.{k}` okänt alternativ `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) okänt värde för övertryck `{o}` (preserve, simulate eller discard) @msg unknown panel `{raw}` okänd panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` har inga visningsstorlekar att växla mellan +@msg the panels are not shown panelerna visas inte @msg panels can't be shown in Presentation Mode paneler kan inte visas i presentationsläge @msg unknown preference `{key}` okänd inställning `{key}` @msg Preferences imported. Inställningarna har importerats. @@ -5415,6 +5417,7 @@ effect Soft Mjuk Change Panel Layout Ändra panellayout Close Panel Stäng panel Collapse Panel Group Komprimera panelgrupp + Cycle Display Sizes Växla visningsstorlekar Move Panel Flytta panel Group with Gruppera med Resize panels Ändra storlek på paneler diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..1a7e54b161 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4876,6 +4876,8 @@ axis Both Her İkisi @msg unknown option `{path}.{k}` bilinmeyen seçenek `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) bilinmeyen üst baskılar `{o}` (preserve, simulate veya discard) @msg unknown panel `{raw}` bilinmeyen panel `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` panelinde geçiş yapılacak görüntü boyutu yok +@msg the panels are not shown paneller gösterilmiyor @msg panels can't be shown in Presentation Mode Sunum Modunda paneller gösterilemez @msg unknown preference `{key}` bilinmeyen tercih `{key}` @msg Preferences imported. Tercihler içe aktarıldı. @@ -6487,6 +6489,7 @@ theme Appearance Görünüm @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 + Cycle Display Sizes Görüntü Boyutları Arasında Geçiş Yap @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 @msg icon must be true or false icon true veya false olmalı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..0d330a2ad2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5155,6 +5155,8 @@ axis Both Обидві @msg unknown option `{path}.{k}` невідомий параметр `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) невідомі накладення `{o}` (preserve, simulate або discard) @msg unknown panel `{raw}` невідома панель `{raw}` +@msg `{panel}` has no display sizes to cycle панель `{panel}` не має розмірів відображення для перемикання +@msg the panels are not shown панелі не показано @msg panels can't be shown in Presentation Mode у режимі презентації панелі показати не можна @msg unknown preference `{key}` невідоме налаштування `{key}` @msg Preferences imported. Налаштування імпортовано. @@ -5530,6 +5532,7 @@ axis Both Обидві Change Panel Layout Змінити розташування панелей Close Panel Закрити панель Collapse Panel Group Згорнути групу панелей + Cycle Display Sizes Перемкнути розміри відображення Move Panel Перемістити панель Group with Згрупувати з Resize panels Змінити розмір панелей diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..09a41c0cc2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -598,6 +598,7 @@ font-technology Variable Biến thiên Close Library Đóng thư viện Close Panel Đóng bảng Collapse Panel Group Thu gọn nhóm bảng + Cycle Display Sizes Chuyển kích thước hiển thị Close Path Đóng đường dẫn Close paths when ends are within: Đóng đường dẫn khi hai đầu cách nhau trong: Clumped Dạng cụm @@ -5691,6 +5692,8 @@ theme Appearance Giao diện @msg unknown option `{path}.{k}` tùy chọn không xác định `{path}.{k}` @msg unknown overprints `{o}` (preserve, simulate or discard) chế độ in đè không xác định `{o}` (preserve, simulate hoặc discard) @msg unknown panel `{raw}` bảng không xác định `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` không có kích thước hiển thị để chuyển +@msg the panels are not shown các bảng không được hiển thị @msg panels can't be shown in Presentation Mode không thể hiển thị bảng trong chế độ trình bày @msg unknown parameter `{key}`; did you mean `{near}`? tham số không xác định `{key}`; ý bạn là `{near}`? @msg unknown parameter `{key}`; the command takes no parameters tham số không xác định `{key}`; lệnh này không nhận tham số diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..9db0295a11 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4789,6 +4789,8 @@ imageTrace Outline 轮廓 @msg give only one of onto, below and above onto、below 和 above 只能给出一个 @msg column must be true or a number from 1 column 必须是 true 或从 1 开始的数字 @msg unknown panel `{raw}` 未知面板 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` 没有可切换的显示大小 +@msg the panels are not shown 面板未显示 @msg panels can't be shown in Presentation Mode 演示模式下无法显示面板 @msg x and y must both be numbers x 和 y 都必须是数字 @msg Downloaded {what} 已下载 {what} @@ -5830,6 +5832,7 @@ effect Vertical 垂直 Change Panel Layout 更改面板布局 Close Panel 关闭面板 Collapse Panel Group 折叠面板组 + Cycle Display Sizes 切换显示大小 Move Panel 移动面板 Group with 组合到 Resize panels 调整面板大小 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..a2c5a44ed7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2437,6 +2437,8 @@ file-filter Templates 範本 @msg give only one of onto, below and above onto、below 和 above 只能提供其中一個 @msg column must be true or a number from 1 column 必須是 true 或從 1 起算的數字 @msg unknown panel `{raw}` 未知的面板 `{raw}` +@msg `{panel}` has no display sizes to cycle `{panel}` 沒有可切換的顯示大小 +@msg the panels are not shown 面板未顯示 @msg panels can't be shown in Presentation Mode 簡報模式下無法顯示面板 @msg x and y must both be numbers x 和 y 都必須是數字 @msg Downloaded {what} 已下載 {what} @@ -5666,6 +5668,7 @@ effect Soft 柔和 Change Panel Layout 變更面板配置 Close Panel 關閉面板 Collapse Panel Group 摺疊面板群組 + Cycle Display Sizes 切換顯示大小 Move Panel 移動面板 Group with 群組至 Resize panels 調整面板大小 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c099422957..4ecff55718 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -651,6 +651,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", ), + ( + "window.panel.cycleOptions", + "Cycle Display Sizes", + "", + "{panel} show a panel at its next display size, as the double triangle at the right end of its tab strip does: the sizes are the states of its panel menu's Show/Hide Options (Transparency: options and thumbnails, thumbnails alone, neither), largest first, and the smallest goes back to the largest; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency have them. An unknown panel or one without display sizes is an error and changes nothing. Returns {panel, size: 0 for the largest, sizes: how many it has}", + ), ( "window.panel.float", "Float Panel", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 5b4913d552..0a4f01879d 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -316,7 +316,7 @@ fn apply(layout: &mut Layout, action: Action) -> Result Option> { if let Some(result) = crate::tools_float::command(app, id, params) { @@ -326,6 +326,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, params: &Value) -> Opt "window.panel" => return Some(show_panel(app, params)), "window.collapseDock" => return Some(crate::menus::opt_bool(params, "collapsed").and_then(|c| collapse_dock(app, c))), "window.panels.peek" => return Some(peek::command(app, params)), + "window.panel.cycleOptions" => return Some(sizes::command(app, params)), "window.panel.collapse" => { let minimized = match crate::menus::opt_bool(params, "collapsed") { Ok(c) => c, @@ -1472,13 +1473,21 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { crate::panels::panel_menu_items(self.app, ui, id); } - fn group_header_width(&self, panels: &[String], _active: &String, floating: bool, _strip_width: f32) -> f32 { + fn group_header_width(&self, panels: &[String], active: &String, floating: bool, _strip_width: f32) -> f32 { let flyout = self.app.ui.open_panel.as_ref().is_some_and(|panel| panels.contains(panel)); - if floating || flyout { 52.0 } else { 28.0 } + let cycle = if sizes::has_sizes(active) { sizes::CELL } else { 0.0 }; + cycle + if floating || flyout { 52.0 } else { 28.0 } } fn group_header(&mut self, ui: &mut egui::Ui, panels: &[String], active: &String, floating: bool) { - let header = ui.max_rect(); + let mut header = ui.max_rect(); + // The double triangle comes first, for a panel with display sizes. + if sizes::has_sizes(active) { + let split = (header.left() + sizes::CELL).min(header.right()); + let cell = egui::Rect::from_min_max(header.min, egui::pos2(split, header.bottom())); + sizes::button(self.app, ui, cell, active); + header.min.x = split; + } let flyout = self.app.ui.open_panel.clone().filter(|panel| panels.contains(panel)); let menu_cell = if floating || flyout.is_some() { let split = (header.right() - 28.0).max(header.left()); @@ -1523,6 +1532,7 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } mod peek; +mod sizes; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/panel_docking/sizes.rs b/crates/ui-egui/src/panel_docking/sizes.rs new file mode 100644 index 0000000000..283b348696 --- /dev/null +++ b/crates/ui-egui/src/panel_docking/sizes.rs @@ -0,0 +1,128 @@ +//! A panel's display sizes: the double triangle at the end of its tab strip steps through them +//! (`window.panel.cycleOptions`). A size is a set of the panel's Hide Options, Hide Thumbnails +//! and Show Options states, the ones its panel menu already sets, so the menu and the control +//! always agree. The sizes go from the largest to the smallest, and the smallest is followed by +//! the largest again. A panel whose parts are in no size's states goes to its largest size. + +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::panels::{pstate, set_pstate}; + +/// A part of a panel that can be hidden. +#[derive(Clone, Copy, Debug)] +enum Part { + /// A Hide flag the panel keeps with its panel state ([`pstate`]), true while hidden. + Hide(&'static str), + /// The Color panel's Hide Options, kept with the preferences. + ColorOptions, + /// The Flattener Preview panel's Show Options. + FlattenerOptions, +} + +/// A panel that has display sizes: its parts, and the parts each size hides, largest first. +struct Sizes { + panel: &'static str, + parts: &'static [Part], + sizes: &'static [&'static [bool]], +} + +/// Options shown, then hidden. +const OPTIONS: &[&[bool]] = &[&[false], &[true]]; + +/// The panels with display sizes. +const PANELS: &[Sizes] = &[ + Sizes { panel: "align", parts: &[Part::Hide("align-hide-options")], sizes: OPTIONS }, + Sizes { panel: "attributes", parts: &[Part::Hide("attr-hide-options")], sizes: OPTIONS }, + Sizes { panel: "character", parts: &[Part::Hide("ch-hide-options")], sizes: OPTIONS }, + Sizes { panel: "color", parts: &[Part::ColorOptions], sizes: OPTIONS }, + Sizes { panel: crate::panels::flattener_preview::ID, parts: &[Part::FlattenerOptions], sizes: OPTIONS }, + Sizes { panel: "gradient", parts: &[Part::Hide("gradient-hide-options")], sizes: OPTIONS }, + Sizes { panel: "info", parts: &[Part::Hide("info-hide-options")], sizes: OPTIONS }, + Sizes { panel: "paragraph", parts: &[Part::Hide("pa-hide-options")], sizes: OPTIONS }, + Sizes { panel: "stroke", parts: &[Part::Hide("stroke-hide-options")], sizes: OPTIONS }, + Sizes { panel: "transform", parts: &[Part::Hide("xf-hide-options")], sizes: OPTIONS }, + // Thumbnails and options, then thumbnails alone, then neither. + Sizes { + panel: "transparency", + parts: &[Part::Hide("tr-hide-thumbs"), Part::Hide("tr-hide-options")], + sizes: &[&[false, false], &[false, true], &[true, true]], + }, +]; + +fn sizes_of(panel: &str) -> Option<&'static Sizes> { + PANELS.iter().find(|s| s.panel == panel) +} + +/// Does `panel` have display sizes to step through? +pub(crate) fn has_sizes(panel: &str) -> bool { + sizes_of(panel).is_some() +} + +fn hidden(app: &VectorcraftApp, ctx: &egui::Context, part: Part) -> bool { + match part { + Part::Hide(key) => pstate(ctx, key), + Part::ColorOptions => app.ui.color_hide_options, + Part::FlattenerOptions => !app.ui.flattener_preview.show_options, + } +} + +fn set_hidden(app: &mut VectorcraftApp, ctx: &egui::Context, part: Part, hide: bool) { + match part { + Part::Hide(key) => set_pstate(ctx, key, hide), + Part::ColorOptions => app.ui.color_hide_options = hide, + Part::FlattenerOptions => app.ui.flattener_preview.show_options = !hide, + } +} + +/// The size `panel` shows now (0 is the largest), or `None` when its parts match no size. +fn current(app: &VectorcraftApp, ctx: &egui::Context, sizes: &Sizes) -> Option { + let now: Vec = sizes.parts.iter().map(|&part| hidden(app, ctx, part)).collect(); + sizes.sizes.iter().position(|size| *size == now.as_slice()) +} + +/// `window.panel.cycleOptions {panel}`: show `panel` at its next display size, as the double +/// triangle on its tab strip does. An unknown panel, a panel without display sizes, or no panels +/// drawn yet is an error, and then nothing changes. → {panel, size, sizes}: the size shown now +/// (0 is the largest) and how many sizes the panel has. +pub(crate) fn command(app: &mut VectorcraftApp, params: &Value) -> Result { + let raw = params.get("panel").and_then(Value::as_str).unwrap_or_default(); + let panel = super::normalize(raw).ok_or_else(|| format!("unknown panel `{raw}`"))?; + let sizes = sizes_of(panel).ok_or_else(|| format!("`{panel}` has no display sizes to cycle"))?; + let ctx = app.ui_ctx.clone().ok_or("the panels are not shown")?; + let next = current(app, &ctx, sizes).map_or(0, |i| (i + 1) % sizes.sizes.len()); + for (&part, &hide) in sizes.parts.iter().zip(sizes.sizes[next]) { + set_hidden(app, &ctx, part, hide); + } + ctx.request_repaint(); + Ok(json!({"panel": panel, "size": next, "sizes": sizes.sizes.len()})) +} + +/// Width of the double triangle's cell at the start of a group header. +pub(crate) const CELL: f32 = 20.0; + +/// Draw the double triangle for `panel` centered in `cell`; a click shows its next size. +pub(crate) fn button(app: &mut VectorcraftApp, ui: &mut egui::Ui, cell: egui::Rect, panel: &str) { + let rect = egui::Rect::from_center_size(cell.center(), egui::vec2(16.0_f32.min(cell.width()), 22.0_f32.min(cell.height()))); + if !rect.is_positive() { + return; + } + let label = tl!("Cycle Display Sizes"); + let response = ui.interact(rect, ui.scope_id().with(("cycle-display-sizes", panel)), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + let tokens = crate::theme::Tokens::get(ui.ctx()); + let color = if response.hovered() || response.has_focus() { tokens.text_strong } else { tokens.text_dim }; + let c = rect.center(); + let (w, h, gap) = (3.5, 3.5, 1.5); + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + let up = vec![egui::pos2(c.x - w, c.y - gap), egui::pos2(c.x + w, c.y - gap), egui::pos2(c.x, c.y - gap - h)]; + let down = vec![egui::pos2(c.x - w, c.y + gap), egui::pos2(c.x, c.y + gap + h), egui::pos2(c.x + w, c.y + gap)]; + for points in [up, down] { + painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); + } + if response.on_hover_text(label).clicked() + && let Err(error) = app.run("window.panel.cycleOptions", json!({"panel": panel})) + { + app.ui.status = error; + } +} diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 2c95ff0e16..ec9f3d0b5a 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1702,3 +1702,116 @@ fn rail_flyout_collapse_arrow_closes_the_opening_icon_after_switching_tabs() { assert!(craft_ui::docking::flyout::(&h.ctx, area_id()).is_none()); assert_eq!(h.layout(), before, "all tabs and their active state stay in the rail"); } + +/// The texts `panel`'s menu draws, in the harness's context. +fn panel_menu_texts(h: &mut Harness, panel: &str) -> Vec { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().trim().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let app = &mut h.app; + let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(SCREEN), ..Default::default() }, |ui| { + crate::panels::panel_menu_items(app, ui, panel); + }); + out.textures_delta.clear(); + let mut v = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + v +} + +fn cycle_button(h: &Harness, panel: &str) -> Option { + let panel = panel.to_string(); + h.ctx.read_response(area_id().with(("header", &panel)).with(("cycle-display-sizes", &panel))).map(|r| r.rect) +} + +/// Each panel with display sizes steps between the states its panel menu's Show/Hide Options +/// item sets, and the smallest size goes back to the largest. +#[test] +fn cycle_options_steps_through_the_states_the_panel_menu_sets() { + let mut h = Harness::new(); + for panel in ["align", "attributes", "character", "color", "gradient", "info", "paragraph", "stroke", "transform"] { + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Hide Options"), "{panel} starts with its options"); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": panel})).unwrap(); + assert_eq!(r, json!({"panel": panel, "size": 1, "sizes": 2}), "{panel}"); + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Show Options"), "{panel} hides its options"); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": panel})).unwrap(); + assert_eq!(r["size"], 0, "{panel}"); + assert!(panel_menu_texts(&mut h, panel).iter().any(|t| t == "Hide Options"), "{panel} shows them again"); + } + // The Flattener Preview's options start hidden: its first step shows them, as Show Options does. + assert!(!h.app.ui.flattener_preview.show_options); + let r = h.app.run("window.panel.cycleOptions", json!({"panel": "Flattener Preview"})).unwrap(); + assert_eq!(r, json!({"panel": crate::panels::flattener_preview::ID, "size": 0, "sizes": 2})); + assert!(h.app.ui.flattener_preview.show_options); + h.app.run("window.panel.cycleOptions", json!({"panel": crate::panels::flattener_preview::ID})).unwrap(); + assert!(!h.app.ui.flattener_preview.show_options); + // Transparency: thumbnails and options, thumbnails alone, neither, and back. + let shown = |h: &mut Harness| { + let t = panel_menu_texts(h, "transparency"); + (t.iter().any(|t| t == "Hide Thumbnails"), t.iter().any(|t| t == "Hide Options")) + }; + assert_eq!(shown(&mut h), (true, true)); + for (size, want) in [(1, (true, false)), (2, (false, false)), (0, (true, true))] { + let r = h.app.run("window.panel.cycleOptions", json!({"panel": "transparency"})).unwrap(); + assert_eq!((r["size"].clone(), r["sizes"].clone()), (json!(size), json!(3))); + assert_eq!(shown(&mut h), want, "size {size}"); + } + // Options hidden with the thumbnails shown matches no size, so the next step is the largest. + crate::panels::set_pstate(&h.ctx, "tr-hide-thumbs", true); + assert_eq!(h.app.run("window.panel.cycleOptions", json!({"panel": "transparency"})).unwrap()["size"], 0); + assert_eq!(shown(&mut h), (true, true)); +} + +/// An unknown panel, a panel without display sizes or a missing `panel` is an error, and the +/// panels keep their sizes. +#[test] +fn cycle_options_rejects_panels_without_sizes() { + let mut h = Harness::new(); + for (params, error) in [ + (json!({"panel": "nope"}), "unknown panel `nope`"), + (json!({}), "unknown panel ``"), + (json!({"panel": 3}), "unknown panel ``"), + (json!({"panel": "layers"}), "`layers` has no display sizes to cycle"), + (json!({"panel": "swatches"}), "`swatches` has no display sizes to cycle"), + ] { + assert_eq!(h.app.run("window.panel.cycleOptions", params.clone()).unwrap_err(), error, "{params}"); + } + assert!(panel_menu_texts(&mut h, "stroke").iter().any(|t| t == "Hide Options")); + assert!(!h.app.ui.color_hide_options); +} + +/// The double triangle shows on the tab strip of a panel with display sizes, docked or floating, +/// and a click on it shows the panel's next size; other panels have none. +#[test] +fn the_double_triangle_on_the_tab_strip_cycles_the_display_sizes() { + let mut h = Harness::new(); + h.ctx.enable_accesskit(); + h.frame(vec![]); + assert!(cycle_button(&h, "properties").is_none() && cycle_button(&h, "layers").is_none(), "the main column's panels have no sizes"); + h.app.run("window.panel.float", json!({"panel": "stroke"})).unwrap(); + for _ in 0..3 { + h.frame(vec![]); + } + let control = cycle_button(&h, "stroke").expect("a floating Stroke panel has the double triangle"); + assert!(h.nodes.iter().any(|(_, node)| node.label() == Some("Cycle Display Sizes")), "screen readers name it"); + let menu = h.ctx.read_response(area_id().with(("header", &"stroke".to_string())).with(("panel-menu", &"stroke".to_string()))).unwrap().rect; + assert!(!menu.intersects(control), "the double triangle and the menu have separate hit targets"); + h.click(control.center()); + assert!(crate::panels::pstate::(&h.ctx, "stroke-hide-options"), "a click hides the options"); + assert!(floating_window(&h.layout(), "stroke").is_some(), "the panel stays where it is"); + h.click(control.center()); + assert!(!crate::panels::pstate::(&h.ctx, "stroke-hide-options"), "a second click shows them again"); + // A docked panel's tab strip has it too, and a floating panel without sizes does not. + h.app.run("window.panel.dock", json!({"panel": "color", "anchor": "layers", "zone": "below"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "swatches"})).unwrap(); + for _ in 0..3 { + h.frame(vec![]); + } + let control = cycle_button(&h, "color").expect("a docked Color panel has the double triangle"); + h.click(control.center()); + assert!(h.app.ui.color_hide_options); + assert!(cycle_button(&h, "swatches").is_none()); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b0bd90eb59..76ad9628d1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1061,6 +1061,7 @@ Commands (`panel` and every panel parameter take a panel id in any case or its d | `window.panel.activate`, `.close`, `.closeGroup`, `.closeOthers` | `{panel}` | shows and selects, or hides | | `window.panel.minimize` | `{panel, minimized?}` | minimizes a dock group to its tabs, or a floating window to its title bar; omitted toggles | | `window.panel.collapse` | `{panel, collapsed?}` | `window.panel.minimize`; returns `{panel, collapsed, layout}` | +| `window.panel.cycleOptions` | `{panel}` | shows the panel at its next display size (its Show/Hide Options states, largest first), as the double triangle on its tab strip does; a panel without sizes is an error; returns `{panel, size, sizes}` | | `window.panel.iconic` | `{panel, iconic?}` | collapses the panel's dock column to icons, or expands it | | `window.panel.layout`, `ui.dock` | `{action}` | one craft-ui `Action`, externally tagged, e.g. `{"MoveFloating":{"panel":"swatches","rect":[44,66,360,450]}}` or `{"ResizeSplit":{"path":[],"size":{"Ratio":0.35}}}`; `ui.dock` also takes craft-ui's `{operation, …}` | diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..a524cdaf60 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3374,6 +3374,14 @@ already walks Image Trace. Short agent entry points: `largeList`. Without `view` the command answers the current one. Each panel keeps its own view for the session, and the document does not change. An unknown panel or view is an error, and then nothing changes. It answers `{panel, view}`. +- Panel display sizes: `window.panel.cycleOptions {panel}` shows the panel at its next display size, as the double + triangle at the right end of its tab strip does, docked or floating. The sizes are the states its panel menu's Show + Options and Hide Options items set, largest first, and the smallest is followed by the largest. Align, Attributes, + Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke and Transform have two sizes (options shown, + options hidden). Transparency has three: thumbnails and options, thumbnails alone, and neither. A panel whose + states match none of its sizes goes to its largest. An unknown panel or a panel without display sizes is an error, + and then nothing changes. It answers `{panel, size, sizes}`, where `size` 0 is the largest. The order of the sizes + and the panels that have them are VectorCraft's own. - The Brushes panel menu's Select All Unused: `brush.unused` (a query) lists the brushes no stroke paints with, in library order, and the panel selects them. Strokes in the art (opacity masks included), symbols, graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and graphic styles count, and so do the diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 071c8d4719..b3f3b7d86f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -405,6 +405,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Floating groups stack into sets; sets dock as extra dock columns (a multi-column dock); groups drop anywhere in a set or column, or onto its tabs; a column taller than the window scrolls | done | `window.panel.float {below, above}`, `window.panel.dock {column}` | | Panels dragged onto a dock group's tabs join it; onto its upper or lower half they make a new group above or below it (a top/bottom split, resizable); onto the icon column they become icons, the tabbed group's panels too; a dock tab's context menu closes it (Window menu reopens it) | done | `window.panel.dock {anchor, zone}`, `window.panel.dock {icon: true}`, `window.panel.close` | | A double-click on a dock group's tab collapses the group to its tabs (a group below it moves up into the room) and a second one expands it; a click on another of its tabs expands it showing that panel ([helpx: Workspace basics](https://helpx.adobe.com/illustrator/using/workspace-basics.html), panel groups) | done | `window.panel.collapse {panel, collapsed?}`; in dock groups and floating windows; a group beside another (a left/right split) doesn't collapse | +| The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | | Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | | Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | | Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | From 24867f7827cd401e1ecb9069786bbb30d8c66cf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:53:31 -0800 Subject: [PATCH 14/41] Paste: legend labels in a pie's wedges follow wedges that take the document's swatch When a pasted pie's wedge links a global swatch that the document gives another color (swatchConflict "merge", the default), the wedge takes the document's color. Its legend label kept the contrast it had in the copy, so a wedge that turned dark could show a black label, and one that turned light a white label, until the pie was drawn again. Pasting now reads which wedges show a dark fill before the copy is linked to the document's swatches. A pie whose wedges change darkness gets the legend label contrast a redraw sets: white on a dark wedge, black on a light one. Pies whose legend labels have a fill of their own keep it. This applies to every paste command, Paste without Formatting included, and to pies inside opacity masks. --- crates/engine/src/cmd/clipboard/resources.rs | 5 +- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/graph.rs | 6 +- crates/engine/src/cmd/graph/series.rs | 63 ++++++++++++++++ crates/engine/src/tests/clipboard.rs | 78 ++++++++++++++++++++ docs/mcp.md | 6 +- 6 files changed, 153 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f457712415..932ad3a1a3 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1031,10 +1031,13 @@ impl Imported { self.relink.renames.entry(r).or_default().insert(from.to_string(), to.clone()); } } - /// Point a pasted copy at the document's resources. + /// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the + /// other darkness take the contrast a redraw sets there. pub(crate) fn apply(&self, n: &mut Node) { if self.relinks { + let shades = super::super::graph::wedge_shades(n); self.relink.node(n); + super::super::graph::follow_wedge_shades(n, &shades); } } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00b6a338f2..0ac559c874 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 7be0a122df..11a41174c1 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -49,9 +49,9 @@ use generate::generate; use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, - capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art, - label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, - series_marks_in, series_object_opacity_differs, shown_paint, + capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, follow_wedge_shades, + is_design_art, label_object_opacity_differs, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, + series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index ee33f23517..c3cf55ca60 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1,4 +1,5 @@ use vectorcraft_color::BlendMode; +use vectorcraft_doc::swatches::walk_with_masks; use vectorcraft_geom::Shape; use super::axis::radar_axis; @@ -767,6 +768,68 @@ fn set_legend_fills(n: &mut Node, on_dark: &HashMap) { } } +/// Whether each wedge shows a dark fill, for each pie in `n` (`n` itself or one inside it, opacity-mask art included) +/// with Legends in Wedges whose legend labels' fill is not their own, so a redraw sets it by its wedge. Read before a +/// paste links the pie's colors to the document's swatches, for [`follow_wedge_shades`]. +pub(crate) fn wedge_shades(n: &Node) -> HashMap> { + let mut out = HashMap::new(); + walk_with_masks(n, &mut |m| { + if let Some(g) = m.extras().graph.as_deref() + && g.kind == GraphKind::Pie + && g.legend + && g.pie_legend_in_wedges + && !g.label_styles.legend_fill_is_own() + { + out.insert(m.id, pie_wedges(m).iter().map(|w| w.dark).collect()); + } + }); + out +} + +/// Give the legend labels of each pie in `n` that [`wedge_shades`] read as `was` the contrast a redraw sets, where a +/// wedge now shows a fill of the other darkness: white on a dark wedge, black on a light one. Pies whose wedges all kept +/// their darkness keep their labels as they are. +pub(crate) fn follow_wedge_shades(n: &mut Node, was: &HashMap>) { + let mut changed = vec![]; + walk_with_masks(n, &mut |m| { + if let Some(before) = was.get(&m.id) + && pie_wedges(m).iter().map(|w| w.dark).ne(before.iter().copied()) + { + changed.push(m.id); + } + }); + if !changed.is_empty() { + restore_contrast(n, &changed); + } +} + +/// Set the legend labels of the pies `ids` in `n` (`n` itself or ones inside it, opacity-mask art included) as a redraw +/// sets them on their wedges. +fn restore_contrast(n: &mut Node, ids: &[NodeId]) { + if ids.contains(&n.id) { + let on_dark = match n.extras().graph.as_deref() { + Some(g) => redrawn_on_dark(n, g).unwrap_or_else(|| legend_on_dark(n, g)), + None => HashMap::new(), + }; + set_legend_fills(n, &on_dark); + } + let holds = |c: &Node| { + let mut found = false; + walk_with_masks(c, &mut |m| found |= ids.contains(&m.id)); + found + }; + if n.extras().mask.as_ref().is_some_and(|m| holds(&m.art)) + && let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + { + restore_contrast(Arc::make_mut(&mut m.art), ids); + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + restore_contrast(Arc::make_mut(c), ids); + } + } +} + /// The legend labels of graph `n`: the type in its Legend group, as [`own_labels`] finds them. fn legend_labels(n: &Node) -> Vec<&Node> { legend_in(n.children().map_or(&[], |c| c.as_slice())) diff --git a/crates/engine/src/tests/clipboard.rs b/crates/engine/src/tests/clipboard.rs index 368bc6de10..e1232c9a56 100644 --- a/crates/engine/src/tests/clipboard.rs +++ b/crates/engine/src/tests/clipboard.rs @@ -768,6 +768,84 @@ fn a_legend_fill_of_its_own_stays_behind_when_pasted_without_formatting() { assert_eq!(label(&s, p, "North").1, Paint::solid(Color::WHITE), "still white when the pie is drawn again"); } +/// A pie pasted into a document whose swatch of the same name is another color takes that color on its linked wedges +/// (Merge), and its legend labels in those wedges take the contrast a redraw gives them there: white on a wedge that +/// turned dark. Pasting with Add, which keeps the copied color, keeps the labels as they were. +#[test] +fn pie_legend_labels_follow_wedges_that_take_the_documents_swatch() { + let mut s = session(); + let csv = ",North,South\nP,1,1"; + s.execute("swatch.new", &json!({"name": "Brand", "color": "#ffff66", "global": true})).unwrap(); + let g = id_of(&s.execute("graph.create", &json!({"type": "pie", "x": 50, "y": 50, "width": 200, "height": 200, "csv": csv})).unwrap()); + s.execute("graph.setType", &json!({"id": g.0, "pieLegend": "wedges"})).unwrap(); + /// The fill of the legend label of graph `id` that says `name`. + fn label(s: &Session, id: NodeId, name: &str) -> Paint { + let mut out = None; + node(s, id).walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == name + { + out = Some(t.first_style().fill.clone()); + } + }); + out.unwrap() + } + // The North wedge, black when drawn, takes the light Brand swatch, and a redraw sets its label black. + let mut wedges = vec![]; + for c in node(&s, g).children().unwrap().iter().filter(|c| c.extras().series_index == Some(0)) { + c.walk(&mut |m| { + if matches!(m.kind, NodeKind::Path { .. }) { + wedges.push(m.id.0); + } + }); + } + assert!(!wedges.is_empty()); + s.execute("paint.setFill", &json!({"ids": wedges, "swatch": "Brand"})).unwrap(); + s.execute("graph.setData", &json!({"id": g.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, g, "North"), Paint::solid(Color::BLACK), "black on the light wedge"); + assert_eq!(label(&s, g, "South"), Paint::solid(Color::BLACK)); + copy(&mut s, &[g]); + + for (cmd, choice, north) in [ + ("edit.pasteWithoutFormatting", "merge", Color::WHITE), + ("edit.paste", "merge", Color::WHITE), + ("edit.pasteWithoutFormatting", "add", Color::BLACK), + ("edit.paste", "add", Color::BLACK), + ] { + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute(cmd, &json!({"swatchConflict": choice})).unwrap())[0]; + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}"); + assert_eq!(label(&s, p, "South"), Paint::solid(Color::BLACK), "{cmd} {choice}"); + s.execute("graph.setData", &json!({"id": p.0, "csv": csv})).unwrap(); + assert_eq!(label(&s, p, "North"), Paint::solid(north), "{cmd} {choice}: as a redraw sets it"); + } + + // A copy of the pie in the opacity mask of a rectangle follows the same way. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let r = rect(&mut s, 10.0, 10.0, 300.0, 300.0); + let art = { + let d = doc_mut(&mut s); + let pie = d.node(g).unwrap().clone(); + d.reid(&pie) + }; + doc_mut(&mut s).node_mut(r).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + copy(&mut s, &[r]); + new_doc(&mut s); + s.execute("swatch.new", &json!({"name": "Brand", "color": "#202020", "global": true})).unwrap(); + let p = ids_of(&s.execute("edit.paste", &json!({"swatchConflict": "merge"})).unwrap())[0]; + let mask = node(&s, p).extras().mask.as_deref().unwrap().art.clone(); + let mut north = None; + mask.walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && t.plain_text() == "North" + { + north = Some(t.first_style().fill.clone()); + } + }); + assert_eq!(north, Some(Paint::solid(Color::WHITE)), "in an opacity mask"); +} + /// A two-line legend label in a narrow dark wedge, whose text sits off the wedge's middle line, stays white when its graph /// is pasted without formatting. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..f4a0ebc68d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7232,8 +7232,10 @@ graph's art is pasted as it was copied. A global or spot swatch whose name the document gives another colour is a conflict: `clipboard.conflicts` lists them, and `swatchConflict` answers: `"merge"` (the default: the objects take the document's swatch), `"add"` (the -pasted swatch comes in renamed) or one answer per name. Pasting back into the document the objects came from uses -its resources as they are now and raises no conflict. +pasted swatch comes in renamed) or one answer per name. When a merged swatch turns a pie's wedge from light to dark +or back, the legend labels in that pie's wedges take the contrast a redraw gives them (white on a dark wedge, black on +a light one), unless the legend labels have a fill of their own. Pasting back into the document the objects came from +uses its resources as they are now and raises no conflict. Placement: `edit.paste {center}` centres the objects on a point (the app passes the view centre), else offsets them by `dx`/`dy` (the Paste Offset preference). With nothing selected, `edit.pasteInFront` / `edit.pasteInBack` put them From 40518f790ca76496153e9df448bc740bf92e0e30 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:56:16 +0000 Subject: [PATCH 15/41] Pin native writer APIs to merged craft-libs --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9fe89b8d81..28b5815245 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1013,7 +1013,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de5 [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=424a2dc2be7a90467bca0f62b2f161b6bed57bb0#424a2dc2be7a90467bca0f62b2f161b6bed57bb0" +source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" dependencies = [ "flate2", ] @@ -1164,7 +1164,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=560b6f8268e2c5285c161be52dacfe877b08cf1b#560b6f8268e2c5285c161be52dacfe877b08cf1b" +source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" dependencies = [ "flate2", "serde", diff --git a/Cargo.toml b/Cargo.toml index c4e09e8678..fac45ec43e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,8 +21,8 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637 # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "560b6f8268e2c5285c161be52dacfe877b08cf1b" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "424a2dc2be7a90467bca0f62b2f161b6bed57bb0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" } # craft-update: app-specific pretend versions apply to startup and manual checks. # Native Affinity documents (craft-libs#914). craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" } From 65b2129138859a518439ab43f506e421ecc7d7dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:44:08 -0800 Subject: [PATCH 16/41] Live Paint: livePaint.strokeEdge refuses a through id that is not one of the group's edges `through` now takes only the ids of the group's edges, each once: a face's id, an unknown id, another group's edge or an edge given twice is an error and changes nothing. A hidden edge in it is still skipped by the join. For a double-click the Bucket passes only edges of the group, each once, so an earlier click that filled a face whose fill was the edge's stroke paint (Paint Fills and Paint Strokes both on) no longer sends that face. The Bucket finds the faces a fill drag crossed among those whose bounds meet the drag's bounds only. A canvas test covers the middle-button press and the Space-held press between two Bucket clicks. The progress-doc line lists the new tests, and docs/mcp.md says which edges the tool passes in `through`. Follows #7875. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/live_paint.rs | 6 ++ crates/engine/src/tests/build.rs | 39 ++++++++++++- crates/engine/src/tooling.rs | 2 +- crates/tools/src/builder/live_paint.rs | 28 +++++++--- crates/tools/src/lib.rs | 4 +- crates/ui-egui/src/canvas/tests.rs | 55 +++++++++++++++++++ docs/mcp.md | 20 ++++--- docs/target-app-parity.md | 2 +- 9 files changed, 136 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 95c04e39c7..c6bfb608a9 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Live Paint Bucket (Stroke)", [], None, - "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", + "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", has_doc, lp_stroke_edge ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 46a2d37555..a030f5bd8f 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -580,6 +580,12 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { let (eid, count, changed) = { let d = &s.doc()?.doc; let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?; + // Each id in `through` is an edge of the group, given once. + let group_edges: std::collections::HashSet = b::edges(n).iter().map(|e| e.id).collect(); + let mut seen = std::collections::HashSet::new(); + if let Some(id) = through.iter().find(|id| !group_edges.contains(id) || !seen.insert(**id)) { + return Err(bad(C, format!("through: {id} is not an edge of {g}, or is given twice"))); + } let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; let eid = start.id; let like = like.unwrap_or_else(|| b::lp_stroke_paint(start)); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c7160f9316..b09d7fc220 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4272,15 +4272,26 @@ fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() { s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap(); } assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::>(), [green.clone(), green.clone(), green]); - // `through` takes edge ids, with scope "connected" only. + // `through` takes the group's edge ids, each once, with scope "connected" only; a face's id, an + // unknown id or an edge given twice is refused and changes nothing. + let face = vectorcraft_tools::builder::faces(&node(&s, g)).first().map(|f| f.id).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let depth = s.doc().unwrap().history.undo.len(); for p in [ json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}), json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}), json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}), json!({"group": g.0, "point": [15, 50], "through": []}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [face.0]}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [999_999_999]}), + json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0, middle[1].0]}), ] { assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}"); } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [middle[1].0]})).unwrap(); + assert_eq!(r["count"], 3, "an edge of the group is taken"); } /// A double-click whose second press lands on the next joined edge and is released back on the @@ -4318,6 +4329,32 @@ fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joi assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::>(), [green.clone(), green.clone(), green]); } +/// With Paint Fills and Paint Strokes both on, a double-click on an edge after a click that filled +/// a face whose fill was the edge's stroke paint paints the joined edges: the face is not sent as +/// an edge to join through. +#[test] +fn live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0]); + let [a, b] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0)])[..] else { panic!("two faces") }; + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &black, &[(a, black.clone()), (b, black.clone())]); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.set_tool_option("paintStrokes", &json!(true)); + s.paint.fill = green.clone(); + s.paint.stroke = green.clone(); + for (kind, x) in [(PointerKind::Down, 25.0), (PointerKind::Up, 25.0), (PointerKind::Down, 50.0), (PointerKind::Up, 50.0)] { + s.pointer(&PointerEvent::new(kind, x, 25.0), v).unwrap(); + } + assert_eq!(fill_of(&s, a), green, "the first click fills the face"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 50.0, 25.0), v).unwrap(); + assert!(all.iter().all(|e| node(&s, *e).appearance.stroke_paint() == green), "every joined edge is painted"); + assert_eq!(fill_of(&s, b), black); +} + /// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches /// the fill the face had before the first click: the lent press counts as one that paints nothing. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 59eb78a51b..1134f6963a 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -255,7 +255,7 @@ impl Session { } // The Selection and Group Selection tools act on the instance whole. self.select_whole_instance(id); - // The tool lent to does not see the press: it counts as a press elsewhere for the clicks a + // The lending tool does not see the press: it counts as a press elsewhere for the clicks a // double-click or triple-click compares. self.tool.press_elsewhere(); let lent = self.make_tool(id); diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index b32535d83e..a8c0a0ae90 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -256,12 +256,20 @@ enum LpDragFrom { /// The faces among `faces` (a Live Paint group's faces, back to front) that a drag along the path /// chunks `chunks` crosses, as `livePaint.fill` finds them, each with its fill. fn crossed_faces(faces: &[Arc], chunks: &[Vec]) -> Vec<(NodeId, Paint)> { + // Only a face whose bounds meet the drag's bounds can be crossed. + let Some(drag) = chunks.iter().flatten().fold(None, |r: Option, p| Some(r.map_or(Rect::from_points(*p, *p), |r| r.union_pt(*p)))) else { + return vec![]; + }; let mut hit = vec![]; let mut regions = vec![]; // Front first, as visible_face_at looks. for f in faces.iter().rev().filter(|f| f.visible) { if let Some(path) = f.path_data() && let Some(bounds) = path.bounds() + && bounds.x0 <= drag.x1 + && drag.x0 <= bounds.x1 + && bounds.y0 <= drag.y1 + && drag.y0 <= bounds.y1 { hit.push(f); regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds)); @@ -487,8 +495,8 @@ impl LivePaintBucketTool { /// The paint `part` had before the first press of a click sequence of `clicks` presses that /// painted `part`, or before the double-click after a press when that double-click reached it /// (the sequence's first press counts when it made the group `part` is in and the face it - /// filled there is `part`), a press's drag or release crossing `part` included; `now` when the - /// last press did not paint it. + /// filled there is `part`), a press's drag or release crossing `part` included; `now` when no + /// press of the sequence painted `part` and the last press's drag did not cross it. fn before(&self, cx: &ToolContext, part: NodeId, clicks: usize, now: Paint) -> Paint { let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now }; let made_part = |at: Point| live_paint_at(cx.doc, at).and_then(|g| visible_face_at(cx.doc.node(g)?, at)).is_some_and(|f| f.id == part); @@ -541,8 +549,11 @@ impl LivePaintBucketTool { if clicks == 2 && let Some(group) = cx.doc.node(g) { - // The other edge either click painted joins as the stroke paint it had before. - let through: Vec = self + // The other edge of this group either click painted joins as the stroke paint it + // had before. A face either click filled is not an edge and does not join. + let group_edges: std::collections::HashSet = edges(group).iter().map(|x| x.id).collect(); + let mut through: Vec = vec![]; + for id in self .presses .len() .checked_sub(2) @@ -552,8 +563,11 @@ impl LivePaintBucketTool { .flatten() .filter(|q| q.before == like) .filter_map(|q| q.part) - .filter(|id| *id != e.id) - .collect(); + { + if id != e.id && group_edges.contains(&id) && !through.contains(&id) { + through.push(id); + } + } self.note_reached(group, connected_edges_through(group, e.id, &like, &through), true); if !through.is_empty() { v["through"] = json_ids(&through); @@ -797,7 +811,7 @@ impl Tool for LivePaintBucketTool { self.at = None; } - /// A press the view tools took counts as a press that paints no face or edge, for the clicks + /// A press that did not reach the tool counts as a press that paints no face or edge, for the clicks /// a double-click or triple-click compares. fn press_elsewhere(&mut self) { self.note_press(None); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 197d41aaaf..70f6422055 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -291,8 +291,8 @@ pub trait Tool: Send { /// another document became active. The Blend tool drops its first pick and stops adding to the /// blend it just made. fn history_moved(&mut self) {} - /// A press on the canvas went to the view tools (held Space, the middle button) and not to the - /// tool. The Live Paint Bucket counts it among the clicks a triple-click compares. + /// A press on the canvas did not reach the tool: it went to the view tools (held Space, the + /// middle button), or with Cmd/Ctrl held to the selection tool the session lends. The Live Paint Bucket counts it among the clicks a triple-click compares. fn press_elsewhere(&mut self) {} /// Time passes while the pointer button is held (`dt` seconds since the last tick, whether or /// not the pointer moved): tools that keep working while the brush holds still (Twirl, Pucker, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 6803e977a1..0051ded2d3 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -777,6 +777,61 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() { assert!(chips(&mut app) > 0); } +/// A press between a Live Paint Bucket triple-click's clicks that the view tools take (a +/// middle-button pan, a pan with Space held) counts as a press that paints nothing: the +/// triple-click matches the fill the face had before the first click. +#[test] +fn bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before() { + use egui::{Event, Modifiers, PointerButton}; + use vectorcraft_color::{Color, Paint}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + for case in ["middle", "space"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = [0.0, 50.0, 100.0] + .iter() + .map(|x| app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()) + .collect(); + app.session.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = app.session.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + for (x, hex) in [(25, "#ff0000"), (75, "#ff0000"), (125, "#0000ff")] { + app.session.execute("livePaint.fill", &json!({"group": g, "point": [x, 125], "color": hex})).unwrap(); + } + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("livePaintBucket"); + app.session.paint.fill = green.clone(); + if let Some(v) = app.view_mut() { + v.center = Point::new(200.0, 150.0); + v.zoom = 1.0; + v.fitted = true; + } + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = xf.to_screen(Point::new(25.0, 125.0)); + let click = |app: &mut VectorcraftApp, button, pos, modifiers| { + let b = |pressed| Event::PointerButton { pos, button, pressed, modifiers }; + frame(app, &ctx, vec![Event::PointerMoved(pos), b(true)]); + frame(app, &ctx, vec![b(false)]); + }; + click(&mut app, PointerButton::Primary, at, Modifiers::NONE); + if case == "middle" { + click(&mut app, PointerButton::Middle, at, Modifiers::NONE); + } else { + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, &ctx, vec![space(true)]); + click(&mut app, PointerButton::Primary, at, Modifiers::NONE); + frame(&mut app, &ctx, vec![space(false)]); + } + click(&mut app, PointerButton::Primary, at, Modifiers::NONE); + frame(&mut app, &ctx, vec![]); + let group = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(g)).unwrap().clone(); + let fill = |x: f64| vectorcraft_tools::builder::face_at(&group, Point::new(x, 125.0)).unwrap().appearance.fill_paint(); + assert_eq!([fill(25.0), fill(75.0)], [green.clone(), green.clone()], "{case}: the faces that were red"); + assert_eq!(fill(125.0), Paint::solid(Color::from_hex("#0000ff").unwrap()), "{case}: the blue face"); + } +} + /// The Image Trace panel's eye-button hold ends when the pointer is released, even when the /// panel stopped drawing while the button was held, so a later press on the canvas does not /// show the source image. diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..c0131b4a74 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3956,11 +3956,11 @@ already walks Image Trace. Short agent entry points: edges joined to it end to end that draw with the stroke paint `match`, and `samePaint` paints every edge of the group that draws with that stroke paint; the stroke's weight is not compared. An edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully - transparent or has no such stroke. Each click of a double-click or triple-click runs as it - arrives and is its own undo step when it changes a paint. `match` is the paint the face or edge had before the first of - the double-click's two clicks or the triple-click's three that painted it (including a click whose drag or release crossed it), or - before the double-click when the triple-click's double-click - reached it, so the clicks before the last do not change what it matches; + transparent or has no such stroke. Each click of a double-click or triple-click runs as it arrives and is its own + undo step when it changes a paint. `match` is the paint the face or edge had before the first of the double-click's + two clicks or the triple-click's three that painted it (including a click whose drag or release crossed it), or + before the double-click when the triple-click's double-click reached it, so the clicks before the last do not change + what it matches; a first click that made the Live Paint group counts when the face it filled is the clicked face. Hidden faces and edges are not painted. A face that the Bucket fills has all its fills replaced by one fill with the paint, shown, fully opaque and blending normally, in the place of its topmost fill; its strokes, their order and the face's own visibility, opacity and blending mode stay as @@ -3974,10 +3974,12 @@ already walks Image Trace. Short agent entry points: `"samePaint"`; any other value is an error and changes nothing. `match` is a paint in the model JSON that `document.node {id}` writes for an appearance's paints (`{"type": "none"}` for none), taken only with a scope that compares paints, and defaults to the face's fill or the stroke paint the edge draws with. `livePaint.strokeEdge {scope: "connected", through}` - takes `through`, at most 4096 edge ids that the join counts as drawing with `match` whatever they draw with now; the tool - passes the edge the double-click's first click painted when that edge drew with `match` before the click. `through` with another scope, or one that is not an array of ids, is an error. `livePaint.fill` refuses - a `scope` other than `"one"` with `points`. Both replies add `count`, the number of faces or edges the click reaches, including those that already had the - paint. + takes `through`, at most 4096 ids of the group's edges, each given once, that the join counts as drawing with `match` + whatever they draw with now; a hidden edge among them is still skipped. The tool passes each other edge of the group + that either of the double-click's two clicks painted and that drew with `match` before that click. `through` with + another scope, or one that is not an array of the group's edge ids or names an edge twice, is an error and changes + nothing. `livePaint.fill` refuses a `scope` other than `"one"` with `points`. Both replies add `count`, the number of + faces or edges the click reaches, including those that already had the paint. With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or `paint.setStroke` when the Stroke proxy is in front) with the color swatch before or after the active paint in the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..8b007a8304 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1574,7 +1574,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. - Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group that has the face's fill, or paints every edge that draws with the edge's stroke paint, each with the bucket's paint (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step when it changes a paint, and the paint compared is the one the face or edge had before the first of its clicks that painted it, including a click whose drag or release crossed it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before, live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before, live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill, live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill, live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill, live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill, live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill, live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_triple_click_with_a_view_tool_press_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). + Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group that has the face's fill, or paints every edge that draws with the edge's stroke paint, each with the bucket's paint (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step when it changes a paint, and the paint compared is the one the face or edge had before the first of its clicks that painted it, including a click whose drag or release crossed it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before, live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before, live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill, live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill, live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill, live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill, live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill, live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges, live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges, live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges, live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_triple_click_with_a_view_tool_press_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `canvas::tests::bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). Live Paint Bucket Options has Cursor Swatch Preview, as the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) lists: with the Bucket selected, the active fill or stroke shows above the pointer between the color swatches before and after it in the Swatches panel, and the Left and Right arrow keys pick the swatch before or after it, as the page describes. The selected art keeps its paint. As VectorCraft's own rules, the option is on at first, the arrows step the stroke when the Stroke proxy is in front, they wrap around at the ends and still step with the preview off, a color that is no swatch shows alone until Right picks the first swatch or Left the last, and the arrows do nothing during a fill drag or with no color swatch. Evidence: `tests::build::{live_paint_bucket_arrow_keys_step_the_active_paint_through_the_swatches, live_paint_bucket_arrow_keys_handle_unmatched_paint_few_swatches_and_drags, live_paint_bucket_arrow_keys_pass_swatches_of_the_same_color_for_fill_and_stroke, swatch_arrow_keys_leave_modified_arrows_to_the_shortcuts}`. Object › Live Paint › Make turns the selected paths into a Live Paint group of faces and edges ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)). As VectorCraft's own rule, each face takes every fill row that draws (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge every stroke row that draws (also with a weight above 0) of its source, in order with their opacity, blending mode, effects and stroke settings, with gradients kept at their fit on the source and with the source's opacity and blending mode. Where a path is cut into several edges, each edge's dashes go on from where it starts along the path with the lengths set (dashes aligned to corners and path ends are not fitted to the cut edges), the arrowheads stay at the path's own ends, and a width profile or brush stays only on an edge that runs the whole path; each edge runs the way its path does, a gradient applied along a stroke starts again on each cut edge, and an inside or outside stroke is drawn centered on an open piece of a closed path. A painted lower row under an unpainted or hidden top row is kept, a hidden top row does not become visible, and a source in front whose fill does not draw does not hide the fill behind it. Rows that do not draw stay with the stored sources, which Release returns unchanged; the source's object effects are not carried. Evidence: `tests::build::{live_paint_make_keeps_lower_drawn_stroke_rows, live_paint_make_fits_dashes_and_arrowheads_to_each_edge, live_paint_make_starts_a_closed_edge_where_its_path_starts, live_paint_make_keeps_the_direction_of_gradient_strokes, live_paint_make_keeps_all_drawn_fill_rows_and_attributes, live_paint_make_uses_frontmost_source_with_drawn_fill}`. Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. From a9119df4bcb70d3b3302570e2d28e81645602979 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:24:23 -0800 Subject: [PATCH 17/41] i18n: drop the ka and ru toolbar error rows that main already has --- crates/ui-egui/src/i18n/ka.tsv | 13 ------------- crates/ui-egui/src/i18n/ru.tsv | 13 ------------- 2 files changed, 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e3748b43ff..9475bb917c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9763,19 +9763,6 @@ font-script Japanese იაპონური Not Aligned to Pixel Grid პიქსელურ ბადეზე გაუსწორებელი @msg only paths and compound paths can be aligned to the pixel grid პიქსელურ ბადეზე მხოლოდ ტრაექტორიების და შედგენილი ტრაექტორიების გასწორებაა შესაძლებელი @msg side is left or right, not `{s}` side არის left ან right და არა `{s}` -@msg side is left or right, not `{v}` side არის left ან right და არა `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order არის მთელი რიცხვი 0-დან {others}-მდე და არა `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს -@msg no toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` არ არის -@msg toolbar name can't be empty ხელსაწყოთა ზოლის სახელი ცარიელი ვერ იქნება -@msg a toolbar name has at most {MAX_NAME} characters ხელსაწყოთა ზოლის სახელში მაქსიმუმ {MAX_NAME} სიმბოლოა -@msg there is already a toolbar named `{name}` ხელსაწყოთა ზოლი სახელით `{name}` უკვე არსებობს -@msg there is already a toolbar named `{to}` ხელსაწყოთა ზოლი სახელით `{to}` უკვე არსებობს -@msg a workspace keeps at most {MAX} toolbars სამუშაო სივრცე ინახავს მაქსიმუმ {MAX} ხელსაწყოთა ზოლს -@msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) სტრიქონი უნდა იყოს -@msg name (a toolbar's name) is required name (ხელსაწყოთა ზოლის სახელი) აუცილებელია -@msg to (the new name) is required to (ახალი სახელი) აუცილებელია -@msg name must be a toolbar's name name ხელსაწყოთა ზოლის სახელი უნდა იყოს Ignore All ყველას იგნორირება Add to Dictionary ლექსიკონში დამატება No Suggestions შემოთავაზებები არ არის diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 4d8b654b23..02cdb08e31 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7666,19 +7666,6 @@ shape Open Открытый Not Aligned to Pixel Grid Не выровненные по пиксельной сетке @msg only paths and compound paths can be aligned to the pixel grid по пиксельной сетке можно выровнять только контуры и составные контуры @msg side is left or right, not `{s}` side — это left или right, а не `{s}` -@msg side is left or right, not `{v}` side принимает значение left или right, а не `{v}` -@msg order is a whole number from 0 to {others}, not `{v}` order должен быть целым числом от 0 до {others}, а не `{v}` -@msg toolbar (a toolbar's name) must be a string toolbar (имя панели инструментов) должен быть строкой -@msg no toolbar named `{name}` нет панели инструментов с именем `{name}` -@msg toolbar name can't be empty имя панели инструментов не может быть пустым -@msg a toolbar name has at most {MAX_NAME} characters имя панели инструментов содержит не более {MAX_NAME} символов -@msg there is already a toolbar named `{name}` панель инструментов с именем `{name}` уже есть -@msg there is already a toolbar named `{to}` панель инструментов с именем `{to}` уже есть -@msg a workspace keeps at most {MAX} toolbars рабочая среда хранит не более {MAX} панелей инструментов -@msg name (a toolbar's name) must be a string name (имя панели инструментов) должен быть строкой -@msg name (a toolbar's name) is required Необходимо указать name (имя панели инструментов) -@msg to (the new name) is required Необходимо указать to (новое имя) -@msg name must be a toolbar's name name должен быть именем панели инструментов Ignore All Пропустить все Add to Dictionary Добавить в словарь No Suggestions Нет вариантов From 402b62b20d5adccfeaf2b48a952c0fe32ade5aff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:18:36 -0800 Subject: [PATCH 18/41] 3D: a transparent gradient lines up its colors and transparency across the faces Follows #7338. Under colored lights, and under the classic effects' shading, a gradient with transparent stops is drawn opaque on each face under one opacity mask of its transparency. A gradient without a placement of its own fitted its colors to each face's bounds, while the mask fitted the whole solid, so the color and transparency ramps did not line up and the colors started over on each face. Such a gradient is now placed once on all of the solid's faces, grown by 1 pt, before it is split into colors and mask. Opaque gradients and placed gradients are drawn as before. --- crates/effects/src/lighting.rs | 16 +++++++++ crates/effects/src/solids.rs | 11 ++++-- crates/effects/src/solids/classic.rs | 5 +-- crates/effects/src/solids/tests.rs | 51 ++++++++++++++++++++++++++++ docs/three-d.md | 4 ++- 5 files changed, 82 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 257576822a..7e73594d89 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -321,6 +321,22 @@ pub(crate) fn opaque_paint(paint: &Paint) -> (Paint, Option) { (base, transparent.then_some(mask)) } +/// [`opaque_paint`] for a surface of several faces under one opacity mask. A transparent gradient +/// without a placement (or a freeform gradient without points) is first pinned to `bounds`, the +/// faces' bounds together grown by 1 pt, so every face's color and the mask share one placement. +/// An opaque gradient is returned as [`opaque_paint`] returns it. +pub(crate) fn opaque_surface_paint(paint: &Paint, bounds: impl FnOnce() -> vectorcraft_geom::Rect) -> (Paint, Option) { + let (base, mask) = opaque_paint(paint); + if mask.is_none() || !matches!(paint, Paint::Gradient(_)) { + return (base, mask); + } + let mut pinned = paint.clone(); + if let Paint::Gradient(g) = &mut pinned { + g.pin(bounds().inflate(1.0, 1.0)); + } + opaque_paint(&pinned) +} + fn composed_art(id: vectorcraft_doc::NodeId, path: &vectorcraft_geom::PathData, paint: &Paint, light: Ramp, seam: f64) -> vectorcraft_doc::Node { use std::sync::Arc; use vectorcraft_doc::color::BlendMode; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 5a2a179437..e10771a8d0 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -625,7 +625,9 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { /// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid /// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless /// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order -/// with the faces of other solids. +/// with the faces of other solids. Under colored lights a gradient with transparent stops is drawn +/// opaque under one mask of its transparency, placed once on all the facets when it has no +/// placement of its own ([`crate::lighting::opaque_surface_paint`]). fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node { if !faces && composites_facets(&facets, paint, colored) { let mut group = crate::lighting::solid_surface(n.id, &facets, paint); @@ -634,7 +636,7 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble return group; } // Preserve existing white-light paints and alpha composition exactly. - let (opaque, mask) = if colored { crate::lighting::opaque_paint(paint) } else { (paint.clone(), None) }; + let (opaque, mask) = if colored { crate::lighting::opaque_surface_paint(paint, || facets_bounds(&facets)) } else { (paint.clone(), None) }; let paint = &opaque; let children = facets .into_iter() @@ -671,6 +673,11 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// The bounds of every facet of `facets` together (`Rect::ZERO` when none has any). +pub(crate) fn facets_bounds(facets: &[Facet]) -> Rect { + facets.iter().filter_map(|f| f.path().bounds()).reduce(|a, c| a.union(c)).unwrap_or(Rect::ZERO) +} + /// The width of the stroke of a facet's own paint that closes the seams between `face` and its /// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than /// the stroke, and its stroke would then paint over its neighbors. diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index f48b94bce9..0d867462fc 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -231,14 +231,15 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by /// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`] /// draws it). A gradient with transparent stops is shaded opaque and then masked by -/// its own transparency, so the shading follows the gradient's coverage. +/// its own transparency, so the shading follows the gradient's coverage; without a placement of its +/// own, it is placed once on all the faces ([`crate::lighting::opaque_surface_paint`]). pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); let wire = shading.surface == ClassicSurface::Wireframe; - let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; let paint = &paint; let children = facets .into_iter() diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 9b57c989c6..319cdf2949 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1960,6 +1960,57 @@ fn classic_shading_keeps_a_gradients_transparency() { } } +/// A gradient without a placement and with a transparent stop, under colored lights or classic +/// shading, is placed once for the whole surface: every face's color and the surface's opacity mask +/// share one placement, so the color and transparency ramps line up across the faces. A gradient +/// placed in the document keeps its placement. +#[test] +fn a_transparent_unplaced_gradient_has_one_placement_for_color_and_mask() { + use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + // The source's stops carry an unusual midpoint, so its color and mask copies can be told from + // the light ramps. + const MARK: f32 = 0.37; + let mut first = GradientStop::new(0.0, RED); + first.midpoint = MARK; + let mut end = GradientStop::new(1.0, Color::BLACK); + end.opacity = 0.25; + let unplaced = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![first, end])); + let placed = GradientGeom { start: Point::new(90.0, 100.0), end: Point::new(230.0, 140.0), aspect: 1.0, focal: None }; + // The placement of each copy of the source gradient: its own, else its fit on the path it fills. + fn placements(n: &Node, out: &mut Vec) { + n.walk(&mut |c| { + if let Some(mask) = &c.extras().mask { + placements(&mask.art, out); + } + let bounds = c.path_data().and_then(|p| p.bounds()).unwrap_or(Rect::ZERO); + for item in &c.appearance.items { + if let Paint::Gradient(g) = paint_ref(item) + && g.gradient.stops.first().is_some_and(|s| s.midpoint == MARK) + { + out.push(g.resolve(bounds)); + } + } + }); + } + let lit = json!({"lights": [{"color": "#ff8080"}]}); + for (id, params) in [(EXTRUDE, lit.clone()), (INFLATE, lit.clone()), (ROTATE, lit), (CLASSIC_EXTRUDE, json!({}))] { + for geom in [None, Some(placed)] { + let mut n = square_node(); + n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Gradient(Box::new(GradientPaint { geom, ..unplaced.clone() }))))]; + n.appearance.effects.push(fx(id, params.clone())); + let art = solid_art(&n).unwrap_or_else(|| panic!("{id}")); + let mut masks = 0; + art.walk(&mut |c| masks += usize::from(c.extras().mask.is_some())); + assert!(masks > 0, "{id}: the surface carries the gradient's transparency as a mask"); + let mut found = vec![]; + placements(&art, &mut found); + assert!(found.len() > 2, "{id}: the faces' colors and the mask"); + let expected = geom.unwrap_or(found[0]); + assert!(found.iter().all(|g| *g == expected), "{id} {geom:?}: {found:?}"); + } + } +} + /// A group member in a gradient with transparent stops keeps the shared back-to-front order of /// every member's faces: its faces go in runs that carry its opacity mask, and the other member's /// faces are drawn between them where they are in front of some and behind others. Here a square diff --git a/docs/three-d.md b/docs/three-d.md index e30d0ee4b8..437c40d5f3 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -180,7 +180,9 @@ The rest is our reading: curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in this order, in runs that each carry the mask, and a graphic drawn after one of its faces carries the mask too - ([Graphics](#graphics)). A member of a 3D group with its own opacity + ([Graphics](#graphics)). Such a gradient, and a gradient with transparent stops under the classic effects' + shading, is placed once on the whole solid when it has no placement of its own, so its colors and its + transparency line up across the faces. A member of a 3D group with its own opacity mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its From 6bc3249fdfd9f1a890d71167ec850526547ca128 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:20:55 -0800 Subject: [PATCH 19/41] =?UTF-8?q?Keyboard=20Shortcuts:=20Export=20Text?= =?UTF-8?q?=E2=80=A6=20also=20saves=20a=20printable=20shortcut=20sheet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Export Text…'s save dialog in the desktop app offers two file types: Text (the text file as before, still the first and default type) and Shortcut sheet (PDF). The type picked decides the file. The sheet lists the rows that have a shortcut, Tools and then a group per top-level menu, each under a colored band, shortcut on the left and name on the right. The groups flow down four columns of landscape Letter or A4 pages, titled with the set's name. A row with several shortcuts has a line for each, a shortcut too wide for its column is set smaller, and a long name ends in "…". The sheet is laid out as a document and written by the PDF writer. shortcuts.exportText takes `format` ("text" or "sheet"; default text) and `pageSize` ("letter" or "a4"). Without `pageSize` the sheet is on A4 when the current document prints on A4, else on Letter. A `path` is written as given, as text without `format`, and a bad value is an error. When `format` names a format, or the save dialog reports the type picked, the name the dialog returns gets that format's extension, and a file already at the changed path is replaced only after asking. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/shortcut_editor.rs | 330 ++++++++++++++++- crates/ui-egui/src/shortcut_sheet.rs | 462 ++++++++++++++++++++++++ crates/ui-egui/src/tests/picks.rs | 72 +++- crates/ui-egui/src/tests/saveext.rs | 8 +- docs/mcp.md | 40 +- docs/target-app-parity.md | 2 +- 9 files changed, 896 insertions(+), 23 deletions(-) create mode 100644 crates/ui-egui/src/shortcut_sheet.rs diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ecbdf780fb..25158eacca 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -182,7 +182,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + "{path?, format?: \"text\"|\"sheet\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. A `path` is written as given. Without it, pick a file: the desktop save dialog offers both formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3f89789d5d..5ed91270ad 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -71,6 +71,7 @@ pub mod script_runs; pub mod scripts_menu; mod scrub; pub mod shortcut_editor; +pub mod shortcut_sheet; pub mod shortcuts; pub mod state; pub mod stylus; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index c099422957..31abcabb3d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -183,7 +183,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + "{path?, format?: \"text\"|\"sheet\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. A `path` is written as given. Without it, pick a file: the desktop save dialog offers both formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 88a97206c7..5a50525657 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1184,7 +1184,7 @@ pub fn export_text(set: &str, overrides: &Overrides) -> String { let snapshot = snapshot(); let km = crate::keymap::keymap_in(&snapshot, overrides); let backtick = backtick_text(); - let shown_set = if PRESETS.contains(&set) || set == CUSTOM { tl!(set) } else { set }; + let shown_set = shown_set_name(set); let mut out = format!("{}\n{} {shown_set}\n", tl!("Keyboard Shortcuts"), tl!("Set:")); for (tools, heading) in [(true, "Tools"), (false, "Menu Commands")] { out += &format!("\n{}\n", tl!(heading)); @@ -1197,6 +1197,133 @@ pub fn export_text(set: &str, overrides: &Overrides) -> String { out } +/// A set's name as the dialog shows it: the presets and Custom in the UI language. +fn shown_set_name(set: &str) -> &str { + if PRESETS.contains(&set) || set == CUSTOM { tl!(set) } else { set } +} + +/// Export Text's file formats. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextFormat { + /// [`export_text`]'s text file. + Text, + /// The printable shortcut sheet as a PDF ([`crate::shortcut_sheet::sheet_pdf`]). + Sheet, +} + +impl TextFormat { + pub const ALL: [Self; 2] = [Self::Text, Self::Sheet]; + + /// The `format` param's value. + pub fn name(self) -> &'static str { + match self { + Self::Text => "text", + Self::Sheet => "sheet", + } + } + + fn extension(self) -> &'static str { + match self { + Self::Text => "txt", + Self::Sheet => "pdf", + } + } + + /// The save dialog's file type. + fn filter(self) -> crate::FileFilter { + let label = match self { + Self::Text => "Text", + Self::Sheet => "Shortcut sheet", + }; + crate::FilePick::filter(label, &[self.extension()]) + } + + fn file_name(self) -> String { + format!("VectorCraft Shortcuts.{}", self.extension()) + } + + /// `path` with `format`'s extension: kept when it has it in any letter case, the extension of + /// another of these formats replaced, and the extension added to any other path. + fn with_extension(path: &str, format: Self) -> String { + let ext = vectorcraft_engine::cmd::fileio::extension(path); + if ext.eq_ignore_ascii_case(format.extension()) { + path.to_string() + } else if Self::ALL.iter().any(|f| f.extension().eq_ignore_ascii_case(&ext)) { + std::path::Path::new(path).with_extension(format.extension()).to_string_lossy().into_owned() + } else { + format!("{path}.{}", format.extension()) + } + } + + /// The format a save dialog's answer picked: the file type it reports, else the extension of + /// `path`; text for any other. + fn picked(path: &str, file_type: Option<&str>) -> Self { + let ext = file_type.map_or_else(|| vectorcraft_engine::cmd::fileio::extension(path), str::to_string); + Self::ALL.into_iter().find(|f| f.extension().eq_ignore_ascii_case(ext.trim_start_matches('.'))).unwrap_or(Self::Text) + } +} + +/// The section name for menu commands no menu holds, as Export Text's heading has it. +const MENU_COMMANDS: &str = "Menu Commands"; + +/// Export Text's rows in sections, for the shortcut sheet: Tools, then one section per top-level +/// menu in the order the dialog first lists a command of it, with the names and shortcuts as the +/// dialog shows them, each name without its top-level menu. Every row the dialog lists is there, +/// with an empty shortcut when it has none. +pub fn export_sections(overrides: &Overrides) -> Vec { + use crate::shortcut_sheet::{Row, Section}; + let snapshot = snapshot(); + let km = crate::keymap::keymap_in(&snapshot, overrides); + let backtick = backtick_text(); + let mut tools = Section { title: tl!("Tools").to_string(), rows: vec![] }; + let mut menus: Vec
= vec![]; + for e in snapshot.entries.iter().filter(|e| listed(km.overrides(), e)) { + let shortcut = dialog_shortcuts_with(&km, &e.key, backtick.as_deref()).unwrap_or_default(); + if e.is_tool { + tools.rows.push(Row { name: shown_name(e), shortcut }); + continue; + } + let group = shown_group(&e.group); + let (top, rest) = group.split_once(" › ").unwrap_or((group.as_str(), "")); + let top = if top.is_empty() { tl!(MENU_COMMANDS) } else { top }; + let label = shown_label(e); + let inner = if rest.is_empty() { label.to_string() } else { format!("{rest} › {label}") }; + let name = if e.shows_key { format!("{inner} ({})", e.key) } else { inner }; + match menus.iter_mut().find(|s| s.title == top) { + Some(s) => s.rows.push(Row { name, shortcut }), + None => menus.push(Section { title: top.to_string(), rows: vec![Row { name, shortcut }] }), + } + } + std::iter::once(tools).chain(menus).collect() +} + +/// The file `format` writes for `set` with `overrides`: the sheet on `page`. +fn export_text_file(format: TextFormat, set: &str, overrides: &Overrides, page: crate::shortcut_sheet::PageSize) -> Result, String> { + match format { + TextFormat::Text => Ok(export_text(set, overrides).into_bytes()), + TextFormat::Sheet => { + let title = format!("{} · {}", tl!("Keyboard Shortcuts"), shown_set_name(set)); + crate::shortcut_sheet::sheet_pdf(&title, &export_sections(overrides), page) + } + } +} + +/// The sheet's paper when `pageSize` is left out: A4 when the current document prints on A4 (its +/// print settings, or, with none saved, a first artboard of A4 size either way up), else Letter. +fn default_sheet_page(app: &VectorcraftApp) -> crate::shortcut_sheet::PageSize { + use crate::shortcut_sheet::PageSize; + let Some(st) = app.session.active() else { return PageSize::Letter }; + let a4 = match st.doc.print_setup.clone().and_then(|v| serde_json::from_value::(v).ok()) { + Some(settings) => settings.media == vectorcraft_pdf::Media::A4, + None => st.doc.artboards.first().is_some_and(|a| { + let (w, h) = PageSize::A4.landscape(); + let (long, short) = (a.rect.width().max(a.rect.height()), a.rect.width().min(a.rect.height())); + (long - w).abs() < 1.0 && (short - h).abs() < 1.0 + }), + }; + if a4 { PageSize::A4 } else { PageSize::Letter } +} + // ---------- UI commands ---------- pub fn open(app: &mut VectorcraftApp) { @@ -1329,19 +1456,75 @@ pub fn run_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option None, + Ok(Some(f)) => match TextFormat::ALL.into_iter().find(|t| t.name() == f) { + Some(t) => Some(t), + None => { + let key = "format"; + return Some(Err(format!("`{key}` must be one of {}", TextFormat::ALL.map(TextFormat::name).join(", ")))); + } + }, + Err(e) => return Some(Err(e)), + }; + let page = match s("pageSize") { + Ok(None) => default_sheet_page(app), + Ok(Some(n)) => match crate::shortcut_sheet::PageSize::parse(&n) { + Some(page) => page, + None => { + let key = "pageSize"; + return Some(Err(format!( + "`{key}` must be one of {}", + crate::shortcut_sheet::PageSize::ALL.map(crate::shortcut_sheet::PageSize::name).join(", ") + ))); + } + }, + Err(e) => return Some(Err(e)), + }; + // A given path is written as text unless `format` says otherwise; a save dialog offers + // every format (text first) unless `format` names one, and its answer picks the format. + let (path, format) = match path { + Some(path) => (Some(path), format.unwrap_or(TextFormat::Text)), + None => { + let shown = format.unwrap_or(TextFormat::Text); + let filters = format.map_or_else(|| TextFormat::ALL.map(TextFormat::filter).to_vec(), |f| vec![f.filter()]); + let pick = crate::FilePick { filters, ..crate::FilePick::named(&shown.file_name()) }; + match crate::picks::save_with_type(app, &pick) { + Some((answer, file_type)) => { + let picked = format.unwrap_or_else(|| TextFormat::picked(&answer, file_type.as_deref())); + // The format that `format` names, or that a dialog reports as the type + // picked, gives the name its extension. A file already at a path + // changed that way, which the dialog did not check, is replaced only + // after asking. + let typed = format.is_some() || file_type.is_some(); + let path = if typed { TextFormat::with_extension(&answer, picked) } else { answer.clone() }; + let request = crate::picks::PickRequest::Save(pick.clone()); + if path != answer && crate::picks::ask_to_replace(app, request, &answer, file_type.as_deref(), &path) { + return Some(Err("cancelled".into())); + } + (Some(path), picked) + } + None => (None, shown), + } + } + }; + // Its save dialog is open: the file is made and written when it answers. + if path.is_none() && app.file_dialog_open() { + return Some(Err("cancelled".into())); + } + let bytes = match export_text_file(format, &app.ui.shortcut_set, &app.ui.shortcut_overrides, page) { + Ok(bytes) => bytes, + Err(e) => return Some(Err(e)), + }; + match path { Some(path) => match app.services.write.as_mut() { - Some(w) => w(&path, text.as_bytes()).map(|_| json!({"path": path})), + Some(w) => w(&path, &bytes).map(|_| json!({"path": path})), None => Err("no file writer".into()), }, - // Its save dialog is open: the file is written when it answers. - None if app.file_dialog_open() => Err("cancelled".into()), None => match app.services.download.as_mut() { - Some(dl) => dl("VectorCraft Shortcuts.txt", text.as_bytes()).map(|()| Value::Null), - None => Ok(json!({"text": text})), + Some(dl) => dl(&format.file_name(), &bytes).map(|()| Value::Null), + None if format == TextFormat::Sheet => Ok(json!({"pdf": vectorcraft_svg::base64_encode(&bytes)})), + None => Ok(json!({"text": String::from_utf8_lossy(&bytes)})), }, } } @@ -2171,6 +2354,133 @@ mod tests { assert_eq!(*text, expected); } + /// The sheet's sections: Tools first, then each top-level menu once, in the + /// order the dialog first lists a command of it, holding every row the dialog lists with its + /// shortcut, the command named without its top-level menu. + #[test] + fn export_sections_hold_every_listed_row_once_by_top_level_menu() { + let mut ov = Overrides::new(); + crate::keymap::set_override(&mut ov, "edit.preferences", "Ctrl+Alt+Shift+9"); + let (sections, listed_rows, tops) = with_steady_plugins(|| { + let km = keymap_with(&ov); + let listed: Vec = entries().iter().filter(|e| listed(km.overrides(), e)).cloned().collect(); + let mut tops: Vec = vec![]; + for e in listed.iter().filter(|e| !e.is_tool) { + let top = e.group.split(" › ").next().filter(|t| !t.is_empty()).unwrap_or(MENU_COMMANDS).to_string(); + if !tops.contains(&top) { + tops.push(top); + } + } + (export_sections(&ov), listed.len(), tops) + }); + let titles: Vec<&str> = sections.iter().map(|s| s.title.as_str()).collect(); + assert_eq!(titles[0], "Tools"); + assert_eq!(titles[1..], tops.iter().map(String::as_str).collect::>()[..], "one section per top-level menu"); + for menu in ["File", "Edit", "Object", "Type", "Select", "Effect", "View", "Window", "Help"] { + assert!(titles.contains(&menu), "no {menu} section: {titles:?}"); + } + assert_eq!(sections.iter().map(|s| s.rows.len()).sum::(), listed_rows, "every listed row once"); + let prefs = entry("edit.preferences").expect("the Preferences row"); + let top = prefs.group.split(" › ").next().unwrap_or_default().to_string(); + let name = shown_name(&prefs).strip_prefix(&format!("{top} › ")).map(str::to_string).expect("Preferences is in a menu"); + let section = sections.iter().find(|s| s.title == top).expect("its menu's section"); + assert!(section.rows.iter().any(|r| r.name == name && r.shortcut.ends_with('9')), "{name} in {:?}", section.rows); + let pen = sections[0].rows.iter().find(|r| r.shortcut == menus::pretty_shortcut(default_of("tool:pen").unwrap_or_default())); + assert!(pen.is_some(), "the Pen tool's row"); + } + + /// `format` picks the file: text (the default, the same bytes as before) or the PDF sheet. A + /// given path is written as text whatever its extension, and a bad `format` or `pageSize` is an + /// error that writes nothing. + #[test] + fn export_text_command_writes_text_or_a_sheet() { + type Files = std::rc::Rc)>>>; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let written: Files = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + w.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + let (files, text) = with_steady_plugins(|| { + written.borrow_mut().clear(); + app.run("shortcuts.exportText", json!({"path": "/a/plain.txt"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/named.txt", "format": "text"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/as-text.pdf"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/sheet.pdf", "format": "sheet", "pageSize": "a4"})).unwrap(); + app.run("shortcuts.exportText", json!({"path": "/a/sheet.txt", "format": "sheet"})).unwrap(); + (written.borrow().clone(), export_text(&app.ui.shortcut_set, &app.ui.shortcut_overrides)) + }); + let [plain, named, as_text, sheet, sheet_as_named] = files.as_slice() else { panic!("{} files", files.len()) }; + for f in [plain, named, as_text] { + assert_eq!(f.1, text.as_bytes(), "{}", f.0); + } + assert!(sheet.1.starts_with(b"%PDF-"), "{}", sheet.0); + assert_eq!(sheet_as_named.0, "/a/sheet.txt", "a path is written as given"); + assert!(sheet_as_named.1.starts_with(b"%PDF-")); + written.borrow_mut().clear(); + let mut err = |p: Value| app.run("shortcuts.exportText", p); + assert_eq!(err(json!({"path": "/a/x", "format": "xlsx"})), Err("`format` must be one of text, sheet".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": "Sheet"})), Err("`format` must be one of text, sheet".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": 3})), Err("`format` must be a string".to_string())); + assert_eq!(err(json!({"path": "/a/x", "pageSize": "legal"})), Err("`pageSize` must be one of letter, a4".to_string())); + assert_eq!(err(json!({"path": "/a/x", "pageSize": "A4"})), Err("`pageSize` must be one of letter, a4".to_string())); + assert!(written.borrow().is_empty()); + } + + /// With no `pageSize` the sheet is on A4 when the current document prints on A4: its print + /// settings say so, or, with none saved, its first artboard is A4 either way up; else Letter. + #[test] + fn the_sheet_is_on_a4_when_the_document_prints_on_a4() { + use crate::shortcut_sheet::PageSize; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "no document"); + app.session.add_document(vectorcraft_doc::Document::new(612.0, 792.0), None); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "a Letter artboard"); + app.session.add_document(vectorcraft_doc::Document::new(595.28, 841.89), None); + assert_eq!(default_sheet_page(&app), PageSize::A4, "an A4 artboard"); + let printing = |w, h, media| { + let mut doc = vectorcraft_doc::Document::new(w, h); + doc.print_setup = serde_json::to_value(vectorcraft_pdf::PrintSettings { media, ..Default::default() }).ok(); + doc + }; + app.session.add_document(printing(595.28, 841.89, vectorcraft_pdf::Media::Letter), None); + assert_eq!(default_sheet_page(&app), PageSize::Letter, "an A4 artboard printing on Letter"); + app.session.add_document(printing(612.0, 792.0, vectorcraft_pdf::Media::A4), None); + assert_eq!(default_sheet_page(&app), PageSize::A4, "printing on A4"); + } + + /// Without a path, a file writer or a download, `shortcuts.exportText` returns the file: the + /// text file under `text` and the sheet as base64 under `pdf`. + #[test] + fn export_text_without_a_file_returns_it() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let (text, sheet) = + with_steady_plugins(|| (app.run("shortcuts.exportText", json!({})), app.run("shortcuts.exportText", json!({"format": "sheet"})))); + let text = text.unwrap(); + assert!(text["text"].as_str().unwrap_or_default().starts_with("Keyboard Shortcuts\n"), "{text}"); + let sheet = sheet.unwrap(); + // "%PDF-" in base64. + assert!(sheet["pdf"].as_str().unwrap_or_default().starts_with("JVBERi0"), "{}", sheet.to_string().len()); + } + + /// The save dialog's answer picks the format: the file type it reports, else the extension + /// typed; text for any other. + #[test] + fn the_save_dialogs_answer_picks_the_export_text_format() { + assert_eq!(TextFormat::picked("/a/sheet.PDF", None), TextFormat::Sheet); + assert_eq!(TextFormat::picked("/a/list", Some("pdf")), TextFormat::Sheet); + assert_eq!(TextFormat::picked("/a/list.pdf", Some("txt")), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list.txt", None), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list", None), TextFormat::Text); + assert_eq!(TextFormat::picked("/a/list.json", None), TextFormat::Text); + assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Sheet), "/a/list.pdf"); + assert_eq!(TextFormat::with_extension("/a/list.txt", TextFormat::Sheet), "/a/list.pdf"); + assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Text), "/a/list.txt"); + assert_eq!(TextFormat::with_extension("/a/list.PDF", TextFormat::Sheet), "/a/list.PDF"); + assert_eq!(TextFormat::with_extension("/a/v1.2", TextFormat::Sheet), "/a/v1.2.pdf"); + } + /// The dialog's Import… leaves an action its function key when the imported set gives the key /// to a command, through both Cancel and OK. #[test] diff --git a/crates/ui-egui/src/shortcut_sheet.rs b/crates/ui-egui/src/shortcut_sheet.rs new file mode 100644 index 0000000000..6f99802830 --- /dev/null +++ b/crates/ui-egui/src/shortcut_sheet.rs @@ -0,0 +1,462 @@ +//! Keyboard Shortcuts › Export Text…'s printable shortcut sheet. +//! +//! The rows come from [`crate::shortcut_editor::export_sections`]: a Tools section and one section +//! per top-level menu. The sheet lists the rows that have a shortcut, each section under a colored +//! band with the shortcut on the left and the name on the right, flowed down columns of landscape +//! pages, and is written as a PDF by laying it out as a document. + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; + +/// One section of the list: Tools or a top-level menu, with its rows in the dialog's order. +#[derive(Clone, Debug, PartialEq)] +pub struct Section { + pub title: String, + pub rows: Vec, +} + +/// A row: the command's name within its section and its shortcuts as the dialog shows them (empty +/// when it has none). +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + pub name: String, + pub shortcut: String, +} + +/// The sheet's paper, used in landscape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PageSize { + Letter, + A4, +} + +impl PageSize { + pub const ALL: [Self; 2] = [Self::Letter, Self::A4]; + + /// The `pageSize` param's value. + pub fn name(self) -> &'static str { + match self { + Self::Letter => "letter", + Self::A4 => "a4", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|p| p.name() == s) + } + + /// Width and height of a landscape page in points. + pub fn landscape(self) -> (f64, f64) { + match self { + Self::Letter => (792.0, 612.0), + Self::A4 => (841.89, 595.28), + } + } +} + +/// Section band colors, in turn. +const BANDS: [(u8, u8, u8); 9] = [ + (0x2f, 0x6d, 0xb5), + (0xc0, 0x39, 0x2b), + (0x27, 0x86, 0x5f), + (0x8e, 0x44, 0xad), + (0xd3, 0x54, 0x00), + (0x16, 0x87, 0x9a), + (0x9a, 0x7d, 0x0a), + (0x5d, 0x6d, 0x7e), + (0xc2, 0x18, 0x5b), +]; + +const MARGIN: f64 = 30.0; +const TITLE_SIZE: f64 = 15.0; +/// From the top margin to the top of the first column. +const TITLE_SPACE: f64 = 28.0; +const COLUMNS: usize = 4; +const GUTTER: f64 = 12.0; +const BAND_HEIGHT: f64 = 13.0; +const BAND_SIZE: f64 = 8.0; +const ROW_HEIGHT: f64 = 9.5; +const ROW_SIZE: f64 = 7.0; +/// Space above a section that does not start a column. +const SECTION_SPACE: f64 = 6.0; +/// The least and the most of a column's width the shortcuts take. +const SHORTCUT_SHARE: f64 = 0.3; +const MAX_SHORTCUT_SHARE: f64 = 0.5; +/// Space between pages in the document. +const PAGE_GAP: f64 = 36.0; +const FONT: &str = "Source Sans 3"; + +/// The sheet's text style. +fn style(size: f64, bold: bool, fill: Color) -> CharStyle { + CharStyle { + font_family: FONT.into(), + font_style: if bold { "Bold" } else { "Regular" }.into(), + size, + fill: Paint::solid(fill), + ..CharStyle::default() + } +} + +/// The width `text` takes in `style`. +fn width(text: &str, style: &CharStyle) -> f64 { + let t = TextObject::point(Point::ZERO, text, style.clone()); + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds.width() +} + +/// The most characters of a name or title the sheet measures; no line on a page holds more. +const MAX_FIT_CHARS: usize = 400; + +/// `text`, shortened with an ellipsis to fit in `room`: the longest start of it that fits with the +/// ellipsis, found with a binary search, so a long imported name takes a few layouts. +fn fitted(text: &str, style: &CharStyle, room: f64) -> String { + let chars: Vec = text.chars().take(MAX_FIT_CHARS + 1).collect(); + if chars.len() <= MAX_FIT_CHARS && width(text, style) <= room { + return text.to_string(); + } + let cut = |n: usize| chars.iter().take(n).collect::().trim_end().to_string() + "…"; + let (mut lo, mut hi) = (0, chars.len().min(MAX_FIT_CHARS)); + while lo < hi { + let mid = (lo + hi).div_ceil(2); + if width(&cut(mid), style) <= room { lo = mid } else { hi = mid - 1 } + } + if lo == 0 && width("…", style) > room { String::new() } else { cut(lo) } +} + +/// Builds the sheet's document: one artboard per page. +struct Sheet { + doc: Document, + page: (f64, f64), + /// Pages so far. + pages: usize, + /// The column being filled, 0-based, and the top of its free space. + column: usize, + y: f64, + /// The shortcut column's width; the names start there. + split: f64, +} + +impl Sheet { + fn origin(&self) -> f64 { + (self.pages - 1) as f64 * (self.page.0 + PAGE_GAP) + } + + fn column_width(&self) -> f64 { + (self.page.0 - 2.0 * MARGIN - GUTTER * (COLUMNS - 1) as f64) / COLUMNS as f64 + } + + fn column_left(&self) -> f64 { + self.origin() + MARGIN + self.column as f64 * (self.column_width() + GUTTER) + } + + fn top(&self) -> f64 { + MARGIN + TITLE_SPACE + } + + fn bottom(&self) -> f64 { + self.page.1 - MARGIN + } + + fn add(&mut self, mut n: Node) { + n.id = self.doc.alloc_id(); + let Some(layer) = self.doc.default_layer() else { return }; + let len = self.doc.children(Some(layer)).map_or(0, |c| c.len()); + // Insertion into the document's own layer only fails for a node id already used, and + // every node gets a new id above. + let _ = self.doc.insert(Some(layer), len, n); + } + + fn rect(&mut self, r: Rect, fill: Color) { + self.add(Node::path(NodeId(0), shapes::rectangle(r), Appearance::basic(Paint::solid(fill), Paint::None, 0.0))); + } + + fn text(&mut self, at: Point, text: &str, style: CharStyle) { + if !text.is_empty() { + self.add(Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(at, text, style))))); + } + } + + /// Starts a page with `title` at its top. + fn new_page(&mut self, title: &str) { + self.pages += 1; + let rect = Rect::new(self.origin(), 0.0, self.origin() + self.page.0, self.page.1); + if self.pages == 1 { + if let Some(a) = self.doc.artboards.first_mut() { + a.rect = rect; + } + } else if let Some(mut a) = self.doc.artboards.first().cloned() { + a.id = self.pages as u32; + a.name = format!("Artboard {}", self.pages); + a.rect = rect; + self.doc.artboards.push(a); + } + let style = style(TITLE_SIZE, true, Color::BLACK); + let room = self.page.0 - 2.0 * MARGIN; + let shown = fitted(title, &style, room); + self.text(Point::new(self.origin() + MARGIN, MARGIN + TITLE_SIZE), &shown, style); + self.column = 0; + self.y = self.top(); + } + + /// Room for `height` more in the column, else the next column or page. + fn make_room(&mut self, height: f64, title: &str) -> bool { + if self.y + height <= self.bottom() { + return false; + } + if self.column + 1 < COLUMNS { + self.column += 1; + self.y = self.top(); + } else { + self.new_page(title); + } + true + } + + fn band(&mut self, title: &str, color: Color) { + let (x, w) = (self.column_left(), self.column_width()); + self.rect(Rect::new(x, self.y, x + w, self.y + BAND_HEIGHT), color); + let style = style(BAND_SIZE, true, Color::WHITE); + let shown = fitted(title, &style, w - 8.0); + self.text(Point::new(x + 4.0, self.y + BAND_HEIGHT - 3.6), &shown, style); + self.y += BAND_HEIGHT; + } + + /// Draws one line of a row: `key` on the left and, on the row's first line, `name` on the right. + fn line(&mut self, key: &str, name: Option<&str>, shaded: bool) { + let (x, w) = (self.column_left(), self.column_width()); + if shaded { + self.rect(Rect::new(x, self.y, x + w, self.y + ROW_HEIGHT), Color::rgb8(0xee, 0xf0, 0xf2)); + } + let baseline = self.y + ROW_HEIGHT - 2.6; + self.text(Point::new(x + 3.0, baseline), key, shortcut_style(key, self.split - 6.0)); + if let Some(name) = name { + let plain = style(ROW_SIZE, false, Color::BLACK); + let name = fitted(name, &plain, w - self.split - 3.0); + self.text(Point::new(x + self.split, baseline), &name, plain); + } + self.y += ROW_HEIGHT; + } +} + +/// The style of shortcut `key` in `room`: a shortcut is never cut short, and one too wide for +/// `room` is set smaller. +fn shortcut_style(key: &str, room: f64) -> CharStyle { + let bold = style(ROW_SIZE, true, Color::BLACK); + let wide = width(key, &bold); + if wide > room && wide > 0.0 && room > 0.0 { style(ROW_SIZE * room / wide, true, Color::BLACK) } else { bold } +} + +/// The separate shortcuts of a row's shortcut text, which the dialog joins with ` · `; a row has at +/// least one line. +fn shortcuts(text: &str) -> Vec<&str> { + let keys: Vec<&str> = text.split(" · ").filter(|s| !s.is_empty()).collect(); + if keys.is_empty() { vec![""] } else { keys } +} + +/// The sheet as a document on `page`-sized landscape artboards: `title` at the top of each page, +/// then each section that has a row with a shortcut under a colored band, its rows with a shortcut +/// below it (shortcut on the left, name on the right), flowed down the columns and onto further +/// pages. A section that continues in the next column repeats its band there. A row with several +/// shortcuts has a line for each, kept in one column unless the row is taller than a column, and a +/// shortcut is never shortened; a name too long for its column ends in an ellipsis. +pub fn sheet_document(title: &str, sections: &[Section], page: PageSize) -> Document { + let page = page.landscape(); + let mut s = Sheet { doc: Document::new(page.0, page.1), page, pages: 0, column: 0, y: 0.0, split: 0.0 }; + // The shortcut column is as wide as the widest shortcut, within limits. + let bold = style(ROW_SIZE, true, Color::BLACK); + let widest = sections.iter().flat_map(|sec| &sec.rows).flat_map(|r| shortcuts(&r.shortcut)).map(|k| width(k, &bold)).fold(0.0, f64::max); + let w = s.column_width(); + s.split = (widest + 6.0).clamp(w * SHORTCUT_SHARE, w * MAX_SHORTCUT_SHARE); + s.doc.title = title.to_string(); + s.new_page(title); + // The most a row takes in one piece: a column below its band. + let column = s.bottom() - s.top() - BAND_HEIGHT; + let whole = |row: &Row| shortcuts(&row.shortcut).len() as f64 * ROW_HEIGHT <= column; + let piece = |row: &Row| if whole(row) { shortcuts(&row.shortcut).len() as f64 * ROW_HEIGHT } else { ROW_HEIGHT }; + let listed = sections.iter().filter(|sec| sec.rows.iter().any(|r| !r.shortcut.is_empty())); + for (i, sec) in listed.enumerate() { + let (r, g, b) = BANDS[i % BANDS.len()]; + let color = Color::rgb8(r, g, b); + let space = if s.y > s.top() { SECTION_SPACE } else { 0.0 }; + let mut rows = sec.rows.iter().filter(|r| !r.shortcut.is_empty()).peekable(); + let first = rows.peek().map_or(ROW_HEIGHT, |r| piece(r)); + if !s.make_room(space + BAND_HEIGHT + first, title) { + s.y += space; + } + s.band(&sec.title, color); + for (n, row) in rows.enumerate() { + if s.make_room(piece(row), title) { + s.band(&sec.title, color); + } + let split = !whole(row); + for (k, key) in shortcuts(&row.shortcut).into_iter().enumerate() { + // A row taller than a column goes on in the next one, line by line. + if k > 0 && split && s.make_room(ROW_HEIGHT, title) { + s.band(&sec.title, color); + } + s.line(key, (k == 0).then_some(row.name.as_str()), n % 2 == 1); + } + } + } + s.doc +} + +/// The sheet as a PDF, one page per artboard of [`sheet_document`]. +pub fn sheet_pdf(title: &str, sections: &[Section], page: PageSize) -> Result, String> { + let doc = sheet_document(title, sections, page); + let opts = vectorcraft_pdf::PdfOptions { title: Some(title.to_string()), ..Default::default() }; + vectorcraft_pdf::export(&doc, &opts).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn row(name: &str, shortcut: &str) -> Row { + Row { name: name.into(), shortcut: shortcut.into() } + } + + /// Every type object in `doc`, in stacking order: its text, its style and its left edge. + fn text_objects(doc: &Document) -> Vec<(String, CharStyle, f64)> { + let mut out = vec![]; + let Some(layer) = doc.default_layer() else { return out }; + for n in doc.children(Some(layer)).into_iter().flatten() { + if let NodeKind::Text(t) = &n.kind { + out.push((t.plain_text(), t.first_style(), t.xf.translation().x)); + } + } + out + } + + /// The text of every type object in `doc`, in stacking order. + fn texts(doc: &Document) -> Vec { + text_objects(doc).into_iter().map(|(t, ..)| t).collect() + } + + /// Every node of `doc` lies on one of its pages. + fn assert_on_pages(doc: &Document) { + let l = doc.default_layer().unwrap_or(NodeId(0)); + for n in doc.children(Some(l)).into_iter().flatten() { + let Some(b) = n.geometric_bounds() else { continue }; + let on = |a: &vectorcraft_doc::Artboard| { + let r = a.rect.inflate(0.5, 0.5); + r.union(b) == r + }; + assert!(doc.artboards.iter().any(on), "{b:?} is off the pages"); + } + } + + /// The sheet lists the rows that have a shortcut and leaves out the others, and a section with + /// no shortcut at all has no band. + #[test] + fn sheet_leaves_out_rows_and_sections_without_a_shortcut() { + let sections = [ + Section { title: "Tools".into(), rows: vec![row("Pen", "P"), row("Unbound Tool", "")] }, + Section { title: "Empty Menu".into(), rows: vec![row("Nothing", "")] }, + Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C")] }, + ]; + let doc = sheet_document("Keyboard Shortcuts · Custom", §ions, PageSize::Letter); + let t = texts(&doc); + assert_eq!(t, ["Keyboard Shortcuts · Custom", "Tools", "P", "Pen", "Edit", "Ctrl+C", "Copy"]); + } + + /// Each page is a landscape artboard of the paper picked, and rows that do not fit on one page + /// go on to more pages of the same size, each with the title. + #[test] + fn sheet_pages_are_landscape_pages_of_the_paper_picked() { + let rows: Vec = (0..600).map(|i| row(&format!("Command {i}"), &format!("Ctrl+{i}"))).collect(); + let sections = [Section { title: "Edit".into(), rows }]; + for (page, (w, h)) in [(PageSize::Letter, (792.0, 612.0)), (PageSize::A4, (841.89, 595.28))] { + let doc = sheet_document("Sheet", §ions, page); + assert!(doc.artboards.len() >= 2, "{page:?}: {} pages", doc.artboards.len()); + for a in &doc.artboards { + assert!((a.rect.width() - w).abs() < 1e-9 && (a.rect.height() - h).abs() < 1e-9, "{page:?}: {:?}", a.rect); + } + let t = texts(&doc); + assert_eq!(t.iter().filter(|s| *s == "Sheet").count(), doc.artboards.len(), "a title on every page"); + assert_eq!(t.iter().filter(|s| s.starts_with("Command ")).count(), 600, "every row once"); + assert_on_pages(&doc); + // Each column the section takes starts with its band. + let mut columns: Vec = vec![]; + for (_, _, x) in text_objects(&doc).iter().filter(|(t, ..)| t.starts_with("Command ")) { + if !columns.iter().any(|c| (c - x).abs() < 1e-6) { + columns.push(*x); + } + } + assert!(columns.len() > COLUMNS, "{page:?}: {} columns", columns.len()); + assert_eq!(t.iter().filter(|s| *s == "Edit").count(), columns.len(), "{page:?}: a band in every column"); + } + let pdf = sheet_pdf("Sheet", &[Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C")] }], PageSize::A4).unwrap(); + assert!(pdf.starts_with(b"%PDF-")); + assert_eq!(PageSize::parse("a4"), Some(PageSize::A4)); + assert_eq!(PageSize::parse("A4"), None); + assert_eq!(PageSize::parse("legal"), None); + } + + /// A row with more shortcuts than a column holds goes on in the next column, under its band + /// again, and stays on the pages. + #[test] + fn a_row_taller_than_a_column_goes_on_in_the_next() { + let keys: Vec = (0..150).map(|i| format!("Ctrl+F{i}")).collect(); + let sections = [Section { title: "Edit".into(), rows: vec![row("Many", &keys.join(" · ")), row("After", "Ctrl+A")] }]; + let doc = sheet_document("Sheet", §ions, PageSize::Letter); + assert_on_pages(&doc); + let t = texts(&doc); + for k in &keys { + assert_eq!(t.iter().filter(|s| *s == k).count(), 1, "{k}"); + } + assert_eq!(t.iter().filter(|s| *s == "Many").count(), 1); + assert!(t.iter().filter(|s| *s == "Edit").count() >= 3, "{t:?}"); + assert!(t.contains(&"After".to_string())); + } + + /// The sheet's font has the macOS modifier symbols the key names use, and the ellipsis. + #[test] + fn the_sheets_font_has_the_key_name_characters() { + let db = vectorcraft_text::FontDb::global(); + for face in ["Regular", "Bold"] { + let f = db.face(FONT, face).expect("the bundled face"); + for c in "⌃⌥⇧⌘…".chars() { + assert!(f.covers(c), "{face} lacks {c} (U+{:04X})", c as u32); + } + } + } + + /// A row with several shortcuts lists each on a line of its own, and a shortcut too wide for + /// its column is kept whole and set smaller to fit. + #[test] + fn sheet_keeps_every_shortcut_of_a_row_whole() { + let long = "Ctrl+Alt+Shift+".repeat(6) + "PageDown"; + let sections = [Section { title: "Edit".into(), rows: vec![row("Copy", "Ctrl+C · Ctrl+Insert"), row("Long", &long)] }]; + let objects = text_objects(&sheet_document("Sheet", §ions, PageSize::Letter)); + let t: Vec<&str> = objects.iter().map(|(t, ..)| t.as_str()).collect(); + assert_eq!(t, ["Sheet", "Edit", "Ctrl+C", "Copy", "Ctrl+Insert", long.as_str(), "Long"]); + let (_, short, _) = &objects[2]; + assert_eq!(short.size, ROW_SIZE); + let (_, set, _) = &objects[5]; + let (w, _) = PageSize::Letter.landscape(); + let column = (w - 2.0 * MARGIN - GUTTER * (COLUMNS - 1) as f64) / COLUMNS as f64; + assert!(set.size < ROW_SIZE, "{}", set.size); + assert!(width(&long, set) <= column * MAX_SHORTCUT_SHARE - 6.0 + 0.01, "{} wide", width(&long, set)); + } + + /// A name too long for its column is cut short with an ellipsis. + #[test] + fn a_long_name_is_cut_short_to_fit_its_column() { + let long = "Command ".repeat(20); + let doc = sheet_document("Sheet", &[Section { title: "Edit".into(), rows: vec![row(&long, "Ctrl+L")] }], PageSize::Letter); + let shown = texts(&doc).into_iter().find(|t| t.starts_with("Command")).unwrap_or_default(); + assert!(shown.ends_with('…') && shown.len() < long.len(), "{shown}"); + let plain = style(ROW_SIZE, false, Color::BLACK); + let room = 100.0; + assert!(width(&shown, &plain) > 0.0); + let fit = fitted(&long, &plain, room); + assert!(width(&fit, &plain) <= room, "{fit}"); + let one_more = long.chars().take(fit.chars().count()).collect::().trim_end().to_string() + "…"; + assert!(width(&one_more, &plain) > room || one_more == fit, "{fit} is the longest start that fits"); + // A name far longer than any line is measured only in part. + let huge = "x".repeat(1_000_000); + let title = fitted(&huge, &style(TITLE_SIZE, true, Color::BLACK), 700.0); + assert!(title.ends_with('…') && title.chars().count() <= MAX_FIT_CHARS + 1, "{} chars", title.chars().count()); + } +} diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index d6a06960bb..df9662e570 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -456,7 +456,9 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { d.fields.insert("set".into(), json!("Custom")); click(&mut app, "Export Text…", dialogs); match shown.requests().as_slice() { - [PickRequest::Save(pick)] => assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..])])), + [PickRequest::Save(pick)] => { + assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..])])) + } other => panic!("{other:?}"), } shown.answer(&["/keys/list.txt"]); @@ -474,6 +476,74 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "the dialog stays open"); } +/// The file type picked in Export Text…'s save dialog picks the file: the PDF sheet for a name +/// typed with `.pdf`, and for a type the dialog reports with a name typed without an extension, +/// that type's file under the name with its extension. +#[test] +fn keyboard_shortcuts_export_text_writes_the_format_picked_in_its_save_dialog() { + for (answer, path, start) in [ + (&["/keys/list.pdf"][..], "/keys/list.pdf", &b"%PDF-"[..]), + (&["/keys/sheet", "pdf"][..], "/keys/sheet.pdf", &b"%PDF-"[..]), + (&["/keys/plain", "txt"][..], "/keys/plain.txt", &b"Keyboard Shortcuts\n"[..]), + ] { + let (mut app, shown, _) = app(); + type Files = Rc)>>>; + let files: Files = Default::default(); + let f = files.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + f.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + app.run("edit.keyboardShortcuts", json!({})).unwrap(); + click(&mut app, "Export Text…", dialogs); + shown.answer(answer); + poll(&mut app); + let files = files.borrow(); + let [(written, bytes)] = files.as_slice() else { panic!("{files:?}") }; + assert_eq!(written, path); + assert!(bytes.starts_with(start), "{path}: {:?}", String::from_utf8_lossy(&bytes[..bytes.len().min(40)])); + } +} + +/// `shortcuts.exportText` with a `format` and no `path` gives the name its save dialog answers +/// that format's extension, though the dialog reports no file type. +#[test] +fn export_text_with_a_format_gives_the_answered_name_its_extension() { + let (mut app, shown, _) = app(); + let written: Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })); + let _ = app.run("shortcuts.exportText", json!({"format": "sheet"})); + shown.answer(&["/keys/sheet"]); + poll(&mut app); + assert_eq!(*written.borrow(), ["/keys/sheet.pdf"]); +} + +/// A name that Export Text… gives the picked type's extension names a file the save dialog did +/// not check: when one is there, a question asks before replacing it and nothing is written +/// meanwhile. +#[test] +fn keyboard_shortcuts_export_text_asks_before_replacing_a_file_its_extension_names() { + let (mut app, shown, _) = app(); + let written: Rc>> = Default::default(); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })); + app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/keys/list.pdf")); + app.run("edit.keyboardShortcuts", json!({})).unwrap(); + click(&mut app, "Export Text…", dialogs); + shown.answer(&["/keys/list.txt", "pdf"]); + poll(&mut app); + assert!(written.borrow().is_empty(), "{:?}", written.borrow()); + let d = app.ui.dialog.as_ref().expect("a question"); + assert_eq!(d.str("path"), "/keys/list.pdf"); +} + /// Keyboard Shortcuts' Import… opens a shortcut set another app saved as text (`.kys`) in Import /// Shortcut Set over the dialog when its file dialog answers, and the dialog's working set stays in /// Keyboard Shortcuts, which Cancel shows again. diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index df003ddb01..b8bd53586e 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -89,7 +89,13 @@ fn save_panels_show_the_file_type_they_write() { app.run("shortcuts.export", json!({})).unwrap(); assert_eq!(last_shown(&shown), FilePick::filters([("Shortcut sets", &["json"][..])]), "Keyboard Shortcuts › Export…"); app.run("shortcuts.exportText", json!({})).unwrap(); - assert_eq!(last_shown(&shown), FilePick::filters([("Text", &["txt"][..])]), "Keyboard Shortcuts › Export Text…"); + assert_eq!( + last_shown(&shown), + FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..])]), + "Keyboard Shortcuts › Export Text…" + ); + app.run("shortcuts.exportText", json!({"format": "sheet"})).unwrap(); + assert_eq!(last_shown(&shown), FilePick::filters([("Shortcut sheet", &["pdf"][..])]), "shortcuts.exportText with a format"); let presets = [ ("pdf.preset.save", json!({"name": "Mine"}), "pdf.preset.export", "PDF presets", pdfcmds::PRESET_EXTS), ("print.presets.save", json!({"name": "Mine"}), "print.presets.export", "Print presets", printpresets::PRESET_EXTS), diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..510380a174 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6300,18 +6300,42 @@ path and label, with its id when the row shows it, and the key runs what a click {id}`. A removed plug-in's row goes away and its key runs nothing; its shortcut stays saved and applies again when a plug-in with the same id is installed. -`shortcuts.exportText {path?}` saves the current set's shortcut list as a UTF-8 text file, as Edit › Keyboard -Shortcuts › Export Text… does with the dialog's set as edited so far. The file starts with a "Keyboard Shortcuts" line -and a "Set:" line with the set's name, followed by a Tools section and a Menu Commands section. Each section lists the -rows Edit › Keyboard Shortcuts lists, in its order and with names as it shows them: one line per row, with the name, a -tab and the shortcuts as the dialog shows them on the current platform. A row with no shortcut ends after the tab. -Without `path` a save dialog asks for the file. A `path` that is not a string, or a file that cannot be written, -returns an error, and nothing is written. The layout is VectorCraft's own. The reference app's [Export keyboard -shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) +`shortcuts.exportText {path?, format?, pageSize?}` saves the current set's shortcut list as a UTF-8 text file, as +Edit › Keyboard Shortcuts › Export Text… does with the dialog's set as edited so far. The file starts with a "Keyboard +Shortcuts" line and a "Set:" line with the set's name, followed by a Tools section and a Menu Commands section. Each +section lists the rows Edit › Keyboard Shortcuts lists, in its order and with names as it shows them: one line per +row, with the name, a tab and the shortcuts as the dialog shows them on the current platform. A row with no shortcut +ends after the tab. Without `path` a save dialog asks for the file. A `path` that is not a string, or a file that +cannot be written, returns an error, and nothing is written. The layout is VectorCraft's own. The reference app's +[Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes saving the list from the Keyboard Shortcuts dialog as a text file, and does not describe its layout. +`format` picks the file: `"text"` (the default) writes the text file above and `"sheet"` a printable shortcut sheet +as a PDF. A `path` is written as given, in the format `format` names, or as text without `format`. In the desktop +app, without `path`, the save dialog offers both formats (Text and Shortcut sheet, Text first) unless `format` names +one, and the file type picked in it decides. When `format` names a format, or the dialog reports the type picked, the +name the dialog returns gets that format's extension (`.txt` or `.pdf`): one of these extensions is replaced, and the +extension is added to any other name. When that names a file that is already there, a question asks before replacing +it. The web app downloads the format `format` names, text without it. With no file dialog, file writer or download, +the command returns the file: the text file as `text`, the sheet in base64 as `pdf`. A `format` other than `"text"` +or `"sheet"`, or a `pageSize` other than `"letter"` or `"a4"` (lowercase), returns an error, and nothing is written. + +The shortcut sheet lists the rows that have a shortcut in groups: the Tools rows under the Tools group, then each +top-level menu as a group, in the order the dialog first lists a command of it, with the command named without its +top-level menu. The group names, command names and shortcuts are in the UI language, as the dialog shows them. Each +group has a colored band with its name, and below it the rows, the shortcut on the left and the name on the right. The +groups flow down four columns of landscape pages and onto more pages when they do not fit. `pageSize` is `"letter"` +(792 × 612 pt) or `"a4"` (841.89 × 595.28 pt). Without it the sheet is on A4 when the current document prints on A4 +(its print settings, or, with none saved, a first artboard of A4 size), and on Letter otherwise. Each page is titled +with "Keyboard Shortcuts" and the set's name. A group that continues in the next column repeats its band there. A row +with several shortcuts has a line for each, kept in one column unless the row is taller than a column. A shortcut is +never shortened: one too wide for its column is set smaller. A name too long for its column ends in "…". The type is +Source Sans 3, which VectorCraft bundles and which has the macOS modifier symbols (⌃ ⌥ ⇧ ⌘). Characters it does not +have are drawn in another font the app has loaded, when one has them. The layout is VectorCraft's own. + ```json {"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.txt"}}} +{"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.pdf","format":"sheet","pageSize":"a4"}}} ``` The desktop app adds its active artboard, the one the Artboards panel highlights, to the `object.align`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..f621ba0de4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1096,7 +1096,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+F6 (`window.nextDocument`) and Cmd/Ctrl+Shift+F6 (`window.previousDocument`) make the next and the previous open document the current one, in tab order and as a click on its tab does, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for navigating to the next and the previous document. After the last document comes the first, and before the first document comes the last. From the Home screen the keys go to the first and the last document. Keyboard Shortcuts lists both under Window. - Cmd/Ctrl+Alt+Shift+U (`document.switchUnits`) switches the document to the next unit of measurement, in one undo step, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for switching units of measurement. The page does not give an order. VectorCraft steps through the units in the order a right-click on a ruler lists them (Points, Picas, Inches, Millimeters, Centimeters, Pixels, Feet & Inches, Meters, Yards, Feet) and goes from Feet back to Points. - Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`). - - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. Tests `shortcut_editor::tests::export_text_*` and `tests::picks::keyboard_shortcuts_export_text_writes_the_working_set_as_text`. + - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?, format?, pageSize?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. In the desktop app its save dialog also offers a printable shortcut sheet as a PDF, which `format: "sheet"` also picks (`pageSize: "letter" | "a4"`, A4 when the current document prints on A4): the rows with a shortcut under a colored band per group, in columns on landscape pages, a layout of VectorCraft's own. Tests `shortcut_editor::tests::export_text_*`, `shortcut_editor::tests::export_sections_*`, `shortcut_editor::tests::the_save_dialogs_answer_picks_the_export_text_format`, `shortcut_editor::tests::the_sheet_is_on_a4_when_the_document_prints_on_a4`, `shortcut_sheet::tests::*`, `tests::picks::keyboard_shortcuts_export_text_*` and `tests::picks::export_text_with_a_format_gives_the_answered_name_its_extension`. - On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one. - On Linux and the BSDs, when the desktop leaves the window's frame to the app (a Wayland session without server-side decorations, such as GNOME) and the window is not opened through XWayland, the app bar's window buttons follow the `button-layout` key of `org.gnome.desktop.wm.preferences` ([schema](https://gitlab.gnome.org/GNOME/gsettings-desktop-schemas/-/blob/master/schemas/org.gnome.desktop.wm.preferences.gschema.xml.in)): Close alone at the right, all three at the left, or split between the ends, in the listed order with the first one leftmost. When the key cannot be read or names no window button, and for an app frame turned on by `VECTORCRAFT_TITLEBAR=app` or VectorCraft Title Bar on Every Desktop, all three stay at the right. Tests `titlebar::tests::caption_buttons_follow_the_caption_layout`, `tests::the_caption_buttons_follow_the_frame_layout` and `tests::the_start_frame_applies_the_app_title_bar_preference`. - On Linux and the BSDs, Preferences › User Interface › VectorCraft Title Bar on Every Desktop (off by default) uses the app bar as the title bar from the next start in the sessions where the desktop would draw the window's frame (X11, Wayland compositors with server-side decorations such as KDE Plasma, a window opened through XWayland). System Title Bar and `VECTORCRAFT_TITLEBAR` take precedence over it, and `VECTORCRAFT_TITLEBAR` also takes precedence over System Title Bar for the run it is set in. Only the values `app`, `system` and `desktop` take precedence (case-sensitive, surrounding spaces ignored); any other value, such as `unknown`, is ignored and does not override System Title Bar. From 08b3c0b00a56e6fd8785d529d4a048bc3744de15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:39:56 -0800 Subject: [PATCH 20/41] =?UTF-8?q?Keyboard=20Shortcuts:=20Export=20Text?= =?UTF-8?q?=E2=80=A6=20also=20saves=20the=20list=20as=20a=20CSV=20file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Export Text…'s save dialog in the desktop app adds a CSV type after Text and Shortcut sheet, and shortcuts.exportText takes `format: "csv"`. The CSV file is UTF-8 with a byte order mark, CRLF line ends and RFC 4180 quoting. Its header row is Group,Command,Shortcut in every UI language, then one record per row the dialog lists, in the sheet's groups (Tools, then a group per top-level menu) with names and shortcuts in the UI language. A row with no shortcut has an empty Shortcut field. A field that starts with =, +, - or @ and has more after it, or that starts with a tab or a carriage return, starts with an apostrophe. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/shortcut_editor.rs | 56 ++++++++++++++++--- crates/ui-egui/src/shortcut_sheet.rs | 72 ++++++++++++++++++++++++- crates/ui-egui/src/tests/picks.rs | 10 ++-- crates/ui-egui/src/tests/saveext.rs | 2 +- docs/mcp.md | 25 +++++---- docs/target-app-parity.md | 2 +- 8 files changed, 145 insertions(+), 26 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 25158eacca..58e08db941 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -182,7 +182,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?, format?: \"text\"|\"sheet\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. A `path` is written as given. Without it, pick a file: the desktop save dialog offers both formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", + "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 31abcabb3d..f3bb87206e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -183,7 +183,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?, format?: \"text\"|\"sheet\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. A `path` is written as given. Without it, pick a file: the desktop save dialog offers both formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", + "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 5a50525657..348aed01fa 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1209,16 +1209,19 @@ pub enum TextFormat { Text, /// The printable shortcut sheet as a PDF ([`crate::shortcut_sheet::sheet_pdf`]). Sheet, + /// A CSV file of [`export_sections`] ([`crate::shortcut_sheet::csv`]). + Csv, } impl TextFormat { - pub const ALL: [Self; 2] = [Self::Text, Self::Sheet]; + pub const ALL: [Self; 3] = [Self::Text, Self::Sheet, Self::Csv]; /// The `format` param's value. pub fn name(self) -> &'static str { match self { Self::Text => "text", Self::Sheet => "sheet", + Self::Csv => "csv", } } @@ -1226,6 +1229,7 @@ impl TextFormat { match self { Self::Text => "txt", Self::Sheet => "pdf", + Self::Csv => "csv", } } @@ -1234,6 +1238,7 @@ impl TextFormat { let label = match self { Self::Text => "Text", Self::Sheet => "Shortcut sheet", + Self::Csv => "CSV", }; crate::FilePick::filter(label, &[self.extension()]) } @@ -1266,10 +1271,10 @@ impl TextFormat { /// The section name for menu commands no menu holds, as Export Text's heading has it. const MENU_COMMANDS: &str = "Menu Commands"; -/// Export Text's rows in sections, for the shortcut sheet: Tools, then one section per top-level -/// menu in the order the dialog first lists a command of it, with the names and shortcuts as the -/// dialog shows them, each name without its top-level menu. Every row the dialog lists is there, -/// with an empty shortcut when it has none. +/// Export Text's rows in sections, for the shortcut sheet and the CSV file: Tools, then one section +/// per top-level menu in the order the dialog first lists a command of it, with the names and +/// shortcuts as the dialog shows them, each name without its top-level menu. Every row the dialog +/// lists is there, with an empty shortcut when it has none. pub fn export_sections(overrides: &Overrides) -> Vec { use crate::shortcut_sheet::{Row, Section}; let snapshot = snapshot(); @@ -1305,6 +1310,7 @@ fn export_text_file(format: TextFormat, set: &str, overrides: &Overrides, page: let title = format!("{} · {}", tl!("Keyboard Shortcuts"), shown_set_name(set)); crate::shortcut_sheet::sheet_pdf(&title, &export_sections(overrides), page) } + TextFormat::Csv => Ok(crate::shortcut_sheet::csv(&export_sections(overrides), ["Group", "Command", "Shortcut"]).into_bytes()), } } @@ -2420,14 +2426,47 @@ mod tests { assert!(sheet_as_named.1.starts_with(b"%PDF-")); written.borrow_mut().clear(); let mut err = |p: Value| app.run("shortcuts.exportText", p); - assert_eq!(err(json!({"path": "/a/x", "format": "xlsx"})), Err("`format` must be one of text, sheet".to_string())); - assert_eq!(err(json!({"path": "/a/x", "format": "Sheet"})), Err("`format` must be one of text, sheet".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": "xlsx"})), Err("`format` must be one of text, sheet, csv".to_string())); + assert_eq!(err(json!({"path": "/a/x", "format": "Sheet"})), Err("`format` must be one of text, sheet, csv".to_string())); assert_eq!(err(json!({"path": "/a/x", "format": 3})), Err("`format` must be a string".to_string())); assert_eq!(err(json!({"path": "/a/x", "pageSize": "legal"})), Err("`pageSize` must be one of letter, a4".to_string())); assert_eq!(err(json!({"path": "/a/x", "pageSize": "A4"})), Err("`pageSize` must be one of letter, a4".to_string())); assert!(written.borrow().is_empty()); } + /// `format: "csv"` writes the CSV file: the `Group,Command,Shortcut` header, then a record per + /// row the dialog lists, every group and row of [`export_sections`] once. Without a file it + /// comes back under `text`. + #[test] + fn export_text_command_writes_a_csv_file() { + type Files = std::rc::Rc)>>>; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let written: Files = Default::default(); + let (returned, files, sections) = with_steady_plugins(|| { + app.services.write = None; + written.borrow_mut().clear(); + let returned = app.run("shortcuts.exportText", json!({"format": "csv"})); + let w = written.clone(); + app.services.write = Some(Box::new(move |path: &str, b: &[u8]| { + w.borrow_mut().push((path.to_string(), b.to_vec())); + Ok(()) + })); + app.run("shortcuts.exportText", json!({"path": "/a/list.csv", "format": "csv"})).unwrap(); + (returned, written.borrow().clone(), export_sections(&app.ui.shortcut_overrides)) + }); + let [(path, bytes)] = files.as_slice() else { panic!("{} files", files.len()) }; + assert_eq!(path, "/a/list.csv"); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert_eq!(returned.unwrap()["text"].as_str(), Some(text.as_str()), "the same file without a writer"); + assert_eq!(text, crate::shortcut_sheet::csv(§ions, ["Group", "Command", "Shortcut"])); + assert!(text.starts_with("\u{feff}Group,Command,Shortcut\r\nTools,"), "{text}"); + let records = text.matches("\r\n").count(); + assert_eq!(records, 1 + sections.iter().map(|s| s.rows.len()).sum::(), "a header and a record per row"); + for s in §ions { + assert!(text.contains(&format!("\r\n{},", s.title)), "no {} group", s.title); + } + } + /// With no `pageSize` the sheet is on A4 when the current document prints on A4: its print /// settings say so, or, with none saved, its first artboard is A4 either way up; else Letter. #[test] @@ -2477,6 +2516,9 @@ mod tests { assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Sheet), "/a/list.pdf"); assert_eq!(TextFormat::with_extension("/a/list.txt", TextFormat::Sheet), "/a/list.pdf"); assert_eq!(TextFormat::with_extension("/a/list", TextFormat::Text), "/a/list.txt"); + assert_eq!(TextFormat::picked("/a/list.CSV", None), TextFormat::Csv); + assert_eq!(TextFormat::picked("/a/list", Some("csv")), TextFormat::Csv); + assert_eq!(TextFormat::with_extension("/a/list.pdf", TextFormat::Csv), "/a/list.csv"); assert_eq!(TextFormat::with_extension("/a/list.PDF", TextFormat::Sheet), "/a/list.PDF"); assert_eq!(TextFormat::with_extension("/a/v1.2", TextFormat::Sheet), "/a/v1.2.pdf"); } diff --git a/crates/ui-egui/src/shortcut_sheet.rs b/crates/ui-egui/src/shortcut_sheet.rs index 6f99802830..bcd9732381 100644 --- a/crates/ui-egui/src/shortcut_sheet.rs +++ b/crates/ui-egui/src/shortcut_sheet.rs @@ -1,9 +1,10 @@ -//! Keyboard Shortcuts › Export Text…'s printable shortcut sheet. +//! Keyboard Shortcuts › Export Text…'s printable shortcut sheet and CSV file. //! //! The rows come from [`crate::shortcut_editor::export_sections`]: a Tools section and one section //! per top-level menu. The sheet lists the rows that have a shortcut, each section under a colored //! band with the shortcut on the left and the name on the right, flowed down columns of landscape -//! pages, and is written as a PDF by laying it out as a document. +//! pages, and is written as a PDF by laying it out as a document. The CSV file lists every row +//! ([RFC 4180](https://www.rfc-editor.org/rfc/rfc4180.txt) quoting, CRLF line ends). use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; @@ -55,6 +56,41 @@ impl PageSize { } } +/// Whether a spreadsheet would read `s` as a formula: it starts with `=`, `+`, `-` or `@` and has +/// more after it, or starts with a tab or a carriage return. +fn reads_as_formula(s: &str) -> bool { + let mut chars = s.chars(); + match chars.next() { + Some('=' | '+' | '-' | '@') => chars.next().is_some(), + Some('\t' | '\r') => true, + _ => false, + } +} + +/// A CSV field: a field a spreadsheet would read as a formula starts with an apostrophe, and a +/// field with a comma, a double quote or a line break is quoted, with each double quote doubled. +fn csv_field(s: &str) -> String { + let s = if reads_as_formula(s) { format!("'{s}") } else { s.to_string() }; + if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s } +} + +/// The CSV file: a byte order mark, so spreadsheets read it as UTF-8, a header row of `headers`, +/// then one `section,name,shortcut` record per row, each ending in CRLF. +pub fn csv(sections: &[Section], headers: [&str; 3]) -> String { + let mut out = String::from("\u{feff}"); + let mut record = |fields: [&str; 3]| { + out += &fields.map(csv_field).join(","); + out += "\r\n"; + }; + record(headers); + for s in sections { + for r in &s.rows { + record([&s.title, &r.name, &r.shortcut]); + } + } + out +} + /// Section band colors, in turn. const BANDS: [(u8, u8, u8); 9] = [ (0x2f, 0x6d, 0xb5), @@ -346,6 +382,38 @@ mod tests { } } + /// A field with a comma, a double quote or a line break is quoted, with its double quotes + /// doubled; other fields are written as they are, and each record ends in CRLF. + #[test] + fn csv_quotes_fields_with_commas_quotes_and_line_breaks() { + let sections = [ + Section { title: "Edit".into(), rows: vec![row("Paste in Front, Place", "Ctrl+F"), row("Say \"Hi\"", "")] }, + Section { title: "Two\nLines".into(), rows: vec![row("Plain", "Ctrl+,")] }, + ]; + let text = csv(§ions, ["Group", "Command", "Shortcut"]); + assert_eq!( + text, + "\u{feff}Group,Command,Shortcut\r\nEdit,\"Paste in Front, Place\",Ctrl+F\r\nEdit,\"Say \"\"Hi\"\"\",\r\n\"Two\nLines\",Plain,\"Ctrl+,\"\r\n" + ); + } + + /// A field a spreadsheet would read as a formula starts with an apostrophe; a lone `+`, `-`, + /// `=` or `@` key and other fields are written as they are. + #[test] + fn csv_keeps_fields_from_reading_as_formulas() { + let sections = [Section { + title: "Plug-ins".into(), + rows: vec![row("=HYPERLINK(\"x\")", "+"), row("@Sum", "-"), row("-Minus", "- · Ctrl+-"), row("Tab\tName", "=")], + }]; + let text = csv(§ions, ["Group", "Command", "Shortcut"]); + assert_eq!( + text, + "\u{feff}Group,Command,Shortcut\r\nPlug-ins,\"'=HYPERLINK(\"\"x\"\")\",+\r\nPlug-ins,'@Sum,-\r\nPlug-ins,'-Minus,'- · Ctrl+-\r\nPlug-ins,Tab\tName,=\r\n" + ); + assert_eq!(csv_field("\tx"), "'\tx"); + assert_eq!(csv_field("\rx"), "\"'\rx\""); + } + /// The sheet lists the rows that have a shortcut and leaves out the others, and a section with /// no shortcut at all has no band. #[test] diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index df9662e570..9d4ae15493 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -457,7 +457,7 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { click(&mut app, "Export Text…", dialogs); match shown.requests().as_slice() { [PickRequest::Save(pick)] => { - assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..])])) + assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..]), ("CSV", &["csv"][..])])) } other => panic!("{other:?}"), } @@ -476,13 +476,15 @@ fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "the dialog stays open"); } -/// The file type picked in Export Text…'s save dialog picks the file: the PDF sheet for a name -/// typed with `.pdf`, and for a type the dialog reports with a name typed without an extension, -/// that type's file under the name with its extension. +/// The file type picked in Export Text…'s save dialog picks the file: the PDF sheet or the CSV file +/// for a name typed with `.pdf` or `.csv`, and for a type the dialog reports with a name typed +/// without an extension, that type's file under the name with its extension. #[test] fn keyboard_shortcuts_export_text_writes_the_format_picked_in_its_save_dialog() { for (answer, path, start) in [ (&["/keys/list.pdf"][..], "/keys/list.pdf", &b"%PDF-"[..]), + (&["/keys/list.csv"][..], "/keys/list.csv", &b"\xef\xbb\xbfGroup,Command,Shortcut\r\n"[..]), + (&["/keys/table", "csv"][..], "/keys/table.csv", &b"\xef\xbb\xbfGroup,Command,Shortcut\r\n"[..]), (&["/keys/sheet", "pdf"][..], "/keys/sheet.pdf", &b"%PDF-"[..]), (&["/keys/plain", "txt"][..], "/keys/plain.txt", &b"Keyboard Shortcuts\n"[..]), ] { diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index b8bd53586e..87bc207950 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -91,7 +91,7 @@ fn save_panels_show_the_file_type_they_write() { app.run("shortcuts.exportText", json!({})).unwrap(); assert_eq!( last_shown(&shown), - FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..])]), + FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..]), ("CSV", &["csv"][..])]), "Keyboard Shortcuts › Export Text…" ); app.run("shortcuts.exportText", json!({"format": "sheet"})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 510380a174..7783a0be49 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6310,15 +6310,16 @@ cannot be written, returns an error, and nothing is written. The layout is Vecto [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes saving the list from the Keyboard Shortcuts dialog as a text file, and does not describe its layout. -`format` picks the file: `"text"` (the default) writes the text file above and `"sheet"` a printable shortcut sheet -as a PDF. A `path` is written as given, in the format `format` names, or as text without `format`. In the desktop -app, without `path`, the save dialog offers both formats (Text and Shortcut sheet, Text first) unless `format` names -one, and the file type picked in it decides. When `format` names a format, or the dialog reports the type picked, the -name the dialog returns gets that format's extension (`.txt` or `.pdf`): one of these extensions is replaced, and the -extension is added to any other name. When that names a file that is already there, a question asks before replacing -it. The web app downloads the format `format` names, text without it. With no file dialog, file writer or download, -the command returns the file: the text file as `text`, the sheet in base64 as `pdf`. A `format` other than `"text"` -or `"sheet"`, or a `pageSize` other than `"letter"` or `"a4"` (lowercase), returns an error, and nothing is written. +`format` picks the file: `"text"` (the default) writes the text file above, `"sheet"` a printable shortcut sheet as a +PDF and `"csv"` a CSV file. A `path` is written as given, in the format `format` names, or as text without `format`. +In the desktop app, without `path`, the save dialog offers the three formats (Text, Shortcut sheet and CSV, Text first) +unless `format` names one, and the file type picked in it decides. When `format` names a format, or the dialog reports +the type picked, the name the dialog returns gets that format's extension (`.txt`, `.pdf` or `.csv`): one of these +extensions is replaced, and the extension is added to any other name. When that names a file that is already there, a +question asks before replacing it. The web app downloads the format `format` names, text without it. With no file +dialog, file writer or download, the command returns the file: the text file and the CSV file as `text`, the sheet in +base64 as `pdf`. A `format` other than `"text"`, `"sheet"` or `"csv"`, or a `pageSize` other than `"letter"` or +`"a4"` (lowercase), returns an error, and nothing is written. The shortcut sheet lists the rows that have a shortcut in groups: the Tools rows under the Tools group, then each top-level menu as a group, in the order the dialog first lists a command of it, with the command named without its @@ -6333,6 +6334,12 @@ never shortened: one too wide for its column is set smaller. A name too long for Source Sans 3, which VectorCraft bundles and which has the macOS modifier symbols (⌃ ⌥ ⇧ ⌘). Characters it does not have are drawn in another font the app has loaded, when one has them. The layout is VectorCraft's own. +The CSV file is UTF-8 with a byte order mark, with CRLF line ends and fields quoted as +[RFC 4180](https://www.rfc-editor.org/rfc/rfc4180.txt) describes. Its header row is `Group,Command,Shortcut` in every +UI language. Each row the dialog lists has one record, in the sheet's groups and with names and shortcuts in the UI +language, and a row with no shortcut has an empty Shortcut field. A field that starts with `=`, `+`, `-` or `@` and has +more after it, or that starts with a tab or a carriage return, starts with an apostrophe (`'`). + ```json {"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.txt"}}} {"name":"run_command","arguments":{"command":"shortcuts.exportText","params":{"path":"/Users/me/Shortcuts.pdf","format":"sheet","pageSize":"a4"}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f621ba0de4..8e53371d19 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1096,7 +1096,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+F6 (`window.nextDocument`) and Cmd/Ctrl+Shift+F6 (`window.previousDocument`) make the next and the previous open document the current one, in tab order and as a click on its tab does, on the keys the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for navigating to the next and the previous document. After the last document comes the first, and before the first document comes the last. From the Home screen the keys go to the first and the last document. Keyboard Shortcuts lists both under Window. - Cmd/Ctrl+Alt+Shift+U (`document.switchUnits`) switches the document to the next unit of measurement, in one undo step, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for switching units of measurement. The page does not give an order. VectorCraft steps through the units in the order a right-click on a ruler lists them (Points, Picas, Inches, Millimeters, Centimeters, Pixels, Feet & Inches, Meters, Yards, Feet) and goes from Feet back to Points. - Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`). - - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?, format?, pageSize?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. In the desktop app its save dialog also offers a printable shortcut sheet as a PDF, which `format: "sheet"` also picks (`pageSize: "letter" | "a4"`, A4 when the current document prints on A4): the rows with a shortcut under a colored band per group, in columns on landscape pages, a layout of VectorCraft's own. Tests `shortcut_editor::tests::export_text_*`, `shortcut_editor::tests::export_sections_*`, `shortcut_editor::tests::the_save_dialogs_answer_picks_the_export_text_format`, `shortcut_editor::tests::the_sheet_is_on_a4_when_the_document_prints_on_a4`, `shortcut_sheet::tests::*`, `tests::picks::keyboard_shortcuts_export_text_*` and `tests::picks::export_text_with_a_format_gives_the_answered_name_its_extension`. + - Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?, format?, pageSize?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. In the desktop app its save dialog also offers a printable shortcut sheet as a PDF, which `format: "sheet"` also picks (`pageSize: "letter" | "a4"`, A4 when the current document prints on A4): the rows with a shortcut under a colored band per group, in columns on landscape pages, a layout of VectorCraft's own. It also offers a CSV file of the same rows (`format: "csv"`; Group, Command and Shortcut columns). Tests `shortcut_editor::tests::export_text_*`, `shortcut_editor::tests::export_sections_*`, `shortcut_editor::tests::the_save_dialogs_answer_picks_the_export_text_format`, `shortcut_editor::tests::the_sheet_is_on_a4_when_the_document_prints_on_a4`, `shortcut_sheet::tests::*`, `tests::picks::keyboard_shortcuts_export_text_*` and `tests::picks::export_text_with_a_format_gives_the_answered_name_its_extension`. - On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one. - On Linux and the BSDs, when the desktop leaves the window's frame to the app (a Wayland session without server-side decorations, such as GNOME) and the window is not opened through XWayland, the app bar's window buttons follow the `button-layout` key of `org.gnome.desktop.wm.preferences` ([schema](https://gitlab.gnome.org/GNOME/gsettings-desktop-schemas/-/blob/master/schemas/org.gnome.desktop.wm.preferences.gschema.xml.in)): Close alone at the right, all three at the left, or split between the ends, in the listed order with the first one leftmost. When the key cannot be read or names no window button, and for an app frame turned on by `VECTORCRAFT_TITLEBAR=app` or VectorCraft Title Bar on Every Desktop, all three stay at the right. Tests `titlebar::tests::caption_buttons_follow_the_caption_layout`, `tests::the_caption_buttons_follow_the_frame_layout` and `tests::the_start_frame_applies_the_app_title_bar_preference`. - On Linux and the BSDs, Preferences › User Interface › VectorCraft Title Bar on Every Desktop (off by default) uses the app bar as the title bar from the next start in the sessions where the desktop would draw the window's frame (X11, Wayland compositors with server-side decorations such as KDE Plasma, a window opened through XWayland). System Title Bar and `VECTORCRAFT_TITLEBAR` take precedence over it, and `VECTORCRAFT_TITLEBAR` also takes precedence over System Title Bar for the run it is set in. Only the values `app`, `system` and `desktop` take precedence (case-sensitive, surrounding spaces ignored); any other value, such as `unknown`, is ignored and does not override System Title Bar. From cbe83c89a784a8e653cabcb58d895d67bcf54fba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:04:20 -0800 Subject: [PATCH 21/41] Links: relinking a clipped PSD follows the new file's clipping path links.relink and links.update kept a PSD or PSB file's clip group as it was, so an image relinked to a file with another clipping path, or with none, stayed clipped to the old file's path, and a plain image relinked to a clipped PSD came in unclipped. - The PNG a PSD or PSB file's merged image is kept as now carries the clipping path the file names in a text chunk, and RasterImage.clip holds it with its fill rule (even-odd), as it holds a DCS file's (nonzero). - links.relink and links.update read that path the way they read a DCS file's: the clip group's clipping path becomes the new file's, a file that names none leaves a plain group of the image, and a later file that names one clips it again. A clip group whose path or fill rule was changed in the document stays as a clipping mask around the file's clip group. - docs/mcp.md and the evidence line in docs/target-app-parity.md describe the new behavior. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 54 +++++- crates/engine/src/cmd/fileio/tests_psdread.rs | 92 ++++++++++ crates/engine/src/cmd/links.rs | 162 ++++++++++-------- crates/engine/src/cmd/place.rs | 2 +- crates/engine/src/cmd/place/dcs.rs | 1 + docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 8 files changed, 242 insertions(+), 78 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index fc5be365d5..d8c9074001 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note}; mod heifread; mod hpgl; mod jp2read; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 52ed7f0e7f..1d954ba7cb 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -73,8 +73,10 @@ pub struct RasterImage { pub height: u32, /// The resolution the file declares (see [`super::ppi::resolution`]). pub ppi: Option<(f64, f64)>, - /// A DCS file's clipping path, in the image's pixel space ([`crate::cmd::place::dcs`]). - pub clip: Option, + /// The clipping path its file draws it through, in the image's pixel space, with its fill rule: + /// a DCS file's (nonzero, [`crate::cmd::place::dcs`]), or a PSD or PSB file's (even-odd, + /// [`psdread::clipping_path`]). + pub clip: Option<(vectorcraft_geom::PathData, vectorcraft_geom::FillRule)>, } pub(super) fn err(e: impl std::fmt::Display) -> EngineError { @@ -942,7 +944,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; -/// other samples become 8-bit RGBA. +/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file +/// names ([`png_with_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -950,7 +953,8 @@ pub fn raster_image(bytes: &[u8]) -> Result { } if psdread::is_psd(bytes) { let cms = vectorcraft_color::cms::active(); - return as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi); + let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?; + return Ok(png_with_clip(img, psdread::clipping_path(bytes))); } if jxlread::is_jxl(bytes) { let (img, icc, orientation) = jxlread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?; @@ -1118,10 +1122,48 @@ fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) } +/// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from +/// ([`png_with_clip`]). +const CLIP_KEYWORD: &str = "VectorCraft clip"; + +/// Longest clipping path a PNG keeps (bytes of its JSON). +const MAX_PNG_CLIP: usize = 16 << 20; + +/// `img`, a PNG made from a PSD or PSB file, with `clip`, the clipping path that file names in the +/// image's pixel space (even-odd): the image keeps it, and its PNG keeps it in a text chunk, so the +/// Links commands know a clip group of that path as the file's ([`png_clip`]). A path whose JSON is +/// longer than [`MAX_PNG_CLIP`] is left out, and the image comes in unclipped. +fn png_with_clip(mut img: RasterImage, clip: Option) -> RasterImage { + let Some(clip) = clip else { return img }; + let Some(json) = serde_json::to_string(&clip).ok().filter(|j| j.len() <= MAX_PNG_CLIP) else { return img }; + let png = vectorcraft_render::encode::png::with_text(img.blob.bytes.to_vec(), &[(CLIP_KEYWORD, json.into())]); + img.blob = ImageBlob::new("image/png", png); + img.key = img.blob.content_key(); + img.clip = Some((clip, vectorcraft_geom::FillRule::EvenOdd)); + img +} + +/// The clipping path a PNG made from a PSD or PSB file keeps ([`png_with_clip`]), in its pixel +/// space; `None` for other images, and for a text chunk longer than [`MAX_PNG_CLIP`] or a path +/// past [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Reads only the chunks before the image data. +pub(crate) fn png_clip(png: &[u8]) -> Option { + if !png.starts_with(b"\x89PNG\r\n\x1a\n") { + return None; + } + let keyword = [CLIP_KEYWORD.as_bytes(), &[0]].concat(); + let json = super::ppi::png_chunks(png) + .take_while(|(ty, _)| *ty != b"IDAT") + .find_map(|(ty, data)| data.strip_prefix(keyword.as_slice()).filter(|_| ty == b"tEXt"))?; + if json.len() > MAX_PNG_CLIP { + return None; + } + vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { - let RasterImage { key, blob, width, height, ppi, .. } = raster_image(bytes)?; + let RasterImage { key, blob, width, height, ppi, clip } = raster_image(bytes)?; let (sx, sy) = crate::cmd::place::pt_per_px(ppi); let mut d = Document::new(width as f64 * sx, height as f64 * sy); let layer = d.layers[0].id; @@ -1131,7 +1173,7 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { id, NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })), ); - let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes)); + let mut n = file_clipped(&mut d, n, clip.map(|(path, _)| path)); n.name = Some(name.to_string()); d.images.insert(key, blob); d.insert(Some(layer), 0, n).map_err(err)?; diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 6d66b8da4e..2a7340a79e 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -414,6 +414,98 @@ fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() { assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}"); } +/// A square saved as "Square" and the clipping path naming it. +fn square_resources() -> Vec { + let square = saved_path(false, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); + [resource(2000, b"Square", &square), clipping_name(b"Square")].concat() +} + +/// `bytes` written as `name` in `dir`, by its path. +fn write_file(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String { + let p = dir.join(name); + std::fs::write(&p, bytes).unwrap(); + p.to_string_lossy().into_owned() +} + +/// links.relink and links.update put a linked PSD file's image in the clip group of the clipping +/// path its new file names, take that clip group's clipping path away when the new file names +/// none, and give it back when a later file names one again. +#[test] +fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-clip"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let square = write_file(&dir, "square.psd", &red_psd(&square_resources())); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]; + let squared = vec![[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), r["image"].as_u64().unwrap()); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image))); + s.execute("links.relink", &json!({"ids": [image], "path": square})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared.clone(), true, NodeId(image)), "the new file's clipping path"); + s.execute("links.relink", &json!({"ids": [image], "path": plain})).unwrap(); + let d = &s.doc().unwrap().doc; + match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id.0).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + s.execute("links.relink", &json!({"ids": [image], "path": cut})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (triangle.clone(), true, NodeId(image)), "clipped again"); + // The file is saved again with another clipping path. + std::fs::write(&cut, red_psd(&square_resources())).unwrap(); + s.execute("links.update", &json!({"ids": [image]})).unwrap(); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); +} + +/// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a +/// text chunk within the size limit that reads as a path gives one back. +#[test] +fn the_kept_png_holds_the_clipping_path_within_bounds() { + let img = raster_image(&red_psd(&triangle_resources())).unwrap(); + let (path, rule) = img.clip.clone().expect("the file's clipping path"); + assert_eq!(rule, vectorcraft_geom::FillRule::EvenOdd); + assert_eq!(super::load::png_clip(&img.blob.bytes), Some(path)); + let plain = raster_image(&red_psd(&[])).unwrap(); + assert!(plain.clip.is_none() && super::load::png_clip(&plain.blob.bytes).is_none()); + let with = |text: String| vectorcraft_render::encode::png::with_text(plain.blob.bytes.to_vec(), &[("VectorCraft clip", text.into())]); + assert_eq!(super::load::png_clip(&with("not a path".into())), None); + assert_eq!(super::load::png_clip(&with(" ".repeat((16 << 20) + 1))), None, "a chunk past the limit is not read"); +} + +/// A plain image relinked to a PSD file that names a clipping path goes into a clip group of that +/// path, under the even-odd rule; a clipping mask made in the document stays around it. +#[test] +fn a_plain_image_relinked_to_a_clipped_psd_is_clipped_by_its_path() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-plain"); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": plain, "at": [50, 25]})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let group = d.parent_of(image).expect("a clip group"); + assert_eq!(clip_group(d, group), (vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]], true, image)); + // The clipping path's fill rule changed in the document makes it the document's own mask: a + // relink keeps it and puts the file's clip group inside it. + let clip = match d.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, .. }) => children[0].id, + other => panic!("{other:?}"), + }; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(vectorcraft_doc::Node { kind: NodeKind::Path { rule, .. }, .. }) = doc.node_mut(clip) { + *rule = vectorcraft_geom::FillRule::NonZero; + } + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let inner = d.parent_of(image).unwrap(); + assert_eq!(d.parent_of(inner), Some(group), "the document's mask holds the file's clip group"); + assert!(clip_group(d, inner).1, "the file's clip group is even-odd"); +} + #[test] fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() { let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index b3fc65e8fc..9abccf1392 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -698,6 +698,20 @@ fn clip_shape((frame, room): Clip) -> PathData { shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame) } +/// The clipping path an image's file draws it through, with the fill rule its clip group takes: +/// a DCS file's (nonzero) or a PSD or PSB file's (even-odd). +type FileClip = (PathData, FillRule); + +/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it +/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB +/// file's ([`fileio::png_clip`]). +fn file_clip(blob: &ImageBlob) -> Option { + if let Some(path) = blob.separated_clip() { + return Some((path, FillRule::NonZero)); + } + (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) +} + /// What happens to the clip of an object a link update remakes. enum ClipTo { /// It stays as it is. @@ -705,25 +719,25 @@ enum ClipTo { /// It is clipped to this path (Placement Options' clip): the clipping path of the clip group /// holding just it changes, else it goes into a new clip group. Path(PathData), - /// It is clipped to this path, the clipping path its DCS file draws it through: as [`ClipTo::Path`], - /// except that a plain group holding just it (as [`ClipTo::Off`] leaves one) becomes a clip group - /// again. - File(PathData), + /// It is clipped to this path, the clipping path its file draws it through, under its fill + /// rule: as [`ClipTo::Path`], except that a plain group holding just it (as [`ClipTo::Off`] + /// leaves one) becomes a clip group again. + File(FileClip), /// It goes into a new clip group of this path, inside the clip group that holds it. - Nest(PathData), - /// Placement Options clip it to `placement` while its DCS file draws it through `file`: it is + Nest(FileClip), + /// Placement Options clip it to `placement` while its file draws it through `file`: it is /// clipped to `file` as [`ClipTo::File`] clips it, and the clip group holding it is clipped to /// `placement` as [`ClipTo::Path`] clips an object. With no `file` (the new file lacks the /// clipping path of the clip group holding it), that group stays as [`ClipTo::Off`] leaves it, /// clipped to `placement`. - Both { file: Option, placement: PathData }, - /// Placement Options clip it to `placement` while its DCS file draws it through `file`, and the + Both { file: Option, placement: PathData }, + /// Placement Options clip it to `placement` while its file draws it through `file`, and the /// clip group holding just it is not its old file's: that clip group's clipping path becomes /// `placement`, and it goes into a new clip group of `file` inside it. - BothInside { file: PathData, placement: PathData }, - /// The clipping path of the clip group holding just it goes (a DCS file's clipping path that - /// its new file lacks): the group stays as a plain group of it, with its id, name, visibility - /// and transparency. + BothInside { file: FileClip, placement: PathData }, + /// The clipping path of the clip group holding just it goes (its old file's clipping path, + /// which its new file lacks): the group stays as a plain group of it, with its id, name, + /// visibility and transparency. Off, } @@ -756,25 +770,25 @@ fn same_path(a: &PathData, b: &PathData) -> bool { } /// The clip an image placed with `old_xf` takes when it shows `img`, read from a file, placed with -/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path a DCS file -/// draws `img` through, the file's clip group inside the placement's. When neither clips it, a clip -/// group holding just it whose clipping path `held` is its old DCS file's (`old_clip`, in the old -/// pixels, under the nonzero rule its clip groups get) goes. +/// `new_xf`: Placement Options' clip `clip` when they clip it, and the clipping path the file +/// (DCS, PSD or PSB) draws `img` through, the file's clip group inside the placement's. When +/// neither clips it, a clip group holding just it whose clipping path `held` is its old file's +/// (`old_clip`, in the old pixels, under the fill rule its clip groups get) goes. fn clip_to( old_xf: Affine, - old_clip: Option<&PathData>, + old_clip: Option<&FileClip>, clip: Option, img: &RasterImage, new_xf: Affine, held: Option<(&PathData, FillRule)>, ) -> ClipTo { - // Whether the clip group holding just the image is the old DCS file's: a clipping path whose - // fill rule was changed in the document is not. + // Whether the clip group holding just the image is the old file's: a clipping path whose fill + // rule was changed in the document is not. let file_held = match (old_clip, held) { - (Some(old), Some((held, rule))) => rule == FillRule::NonZero && same_path(&old.transformed(old_xf), held), + (Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held), _ => false, }; - let file = img.clip.as_ref().map(|path| path.transformed(new_xf)); + let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule)); if let Some(clip) = clip { let placement = clip_shape(clip); return match file { @@ -831,7 +845,7 @@ impl Nested<'_> { fn root(&mut self, n: &mut Arc) { if !(self.pick)(n) { if let Some(placement) = self.update(n, true) { - *n = Arc::new(self.clip_group(Arc::clone(n), placement)); + *n = Arc::new(self.clip_group(Arc::clone(n), (placement, FillRule::NonZero))); } return; } @@ -839,7 +853,8 @@ impl Nested<'_> { let mut new = Arc::new(new); let _ = self.update(&mut new, true); *n = match clip { - ClipTo::Path(path) | ClipTo::File(path) | ClipTo::Nest(path) => Arc::new(self.clip_group(new, path)), + ClipTo::Path(path) => Arc::new(self.clip_group(new, (path, FillRule::NonZero))), + ClipTo::File(file) | ClipTo::Nest(file) => Arc::new(self.clip_group(new, file)), ClipTo::Both { file, placement } => self.clip_both(new, file, placement), ClipTo::BothInside { file, placement } => self.clip_both(new, Some(file), placement), ClipTo::Keep | ClipTo::Off => new, @@ -848,8 +863,8 @@ impl Nested<'_> { /// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays /// the same node when none is there, and only the nodes on the way to one are copied. The - /// result is Placement Options' clip that `n` itself, now the clip group of a DCS file's - /// clipping path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: + /// result is Placement Options' clip that `n` itself, now the clip group of a file's clipping + /// path holding a picked object (or the plain group [`ClipTo::Off`] leaves), takes: /// the clipping path of the clip group holding just `n` becomes it, else `n` goes into a new /// clip group of it. #[must_use] @@ -880,8 +895,8 @@ impl Nested<'_> { match (self.update(&mut new, nested), clip_path) { (None, _) if Arc::ptr_eq(&new, c) => {} (None, _) => slots.push((i, new)), - (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement)), (1, new)]), - (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, placement)))), + (Some(placement), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, placement, None)), (1, new)]), + (Some(placement), _) => slots.push((i, Arc::new(self.clip_group(new, (placement, FillRule::NonZero))))), } continue; } @@ -894,17 +909,22 @@ impl Nested<'_> { let _ = self.update(&mut new, true); match (clip, clip_path) { (ClipTo::Keep, _) => slots.push((i, new)), - (ClipTo::Path(clip) | ClipTo::File(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip)), (1, new)]), + (ClipTo::Path(clip), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, None)), (1, new)]), + (ClipTo::File((clip, rule)), Some(path)) if i == 1 => slots.extend([(0, with_clip(path, clip, Some(rule))), (1, new)]), (ClipTo::File(clip), None) if plain => reclipped = Some((clip, new)), - (ClipTo::Path(clip) | ClipTo::File(clip) | ClipTo::Nest(clip), _) => { + (ClipTo::Path(clip), _) => { + let group = self.clip_group(new, (clip, FillRule::NonZero)); + slots.push((i, Arc::new(group))); + } + (ClipTo::File(clip) | ClipTo::Nest(clip), _) => { let group = self.clip_group(new, clip); slots.push((i, Arc::new(group))); } (ClipTo::Off, Some(_)) if i == 1 => declipped = Some(new), (ClipTo::Off, _) => slots.push((i, new)), // The file's clip group stays `n`, and the placement's clip goes around it. - (ClipTo::Both { file: Some(file), placement }, Some(path)) if i == 1 => { - slots.extend([(0, with_clip(path, file)), (1, new)]); + (ClipTo::Both { file: Some((file, rule)), placement }, Some(path)) if i == 1 => { + slots.extend([(0, with_clip(path, file, Some(rule))), (1, new)]); around = Some(placement); } (ClipTo::Both { file: Some(file), placement }, None) if plain => { @@ -917,7 +937,7 @@ impl Nested<'_> { } (ClipTo::BothInside { file, placement }, Some(path)) if i == 1 => { let group = self.clip_group(new, file); - slots.extend([(0, with_clip(path, placement)), (1, Arc::new(group))]); + slots.extend([(0, with_clip(path, placement, None)), (1, Arc::new(group))]); } (ClipTo::Both { file, placement }, _) => slots.push((i, self.clip_both(new, file, placement))), (ClipTo::BothInside { file, placement }, _) => slots.push((i, self.clip_both(new, Some(file), placement))), @@ -958,27 +978,28 @@ impl Nested<'_> { /// A clip group of `placement` holding `object`, inside a clip group of `file` when there is a /// `file` ([`ClipTo::Both`] for an object no clip group holds yet). - fn clip_both(&mut self, object: Arc, file: Option, placement: PathData) -> Arc { + fn clip_both(&mut self, object: Arc, file: Option, placement: PathData) -> Arc { let object = match file { Some(file) => Arc::new(self.clip_group(object, file)), None => object, }; - Arc::new(self.clip_group(object, placement)) + Arc::new(self.clip_group(object, (placement, FillRule::NonZero))) } - /// A clip group of `object` clipped to `clip`, as [`clip_image_to`] makes one in the layers. - fn clip_group(&mut self, object: Arc, clip: PathData) -> Node { + /// A clip group of `object` clipped to `clip` under its fill rule, as [`new_clip_group`] makes + /// one in the layers. + fn clip_group(&mut self, object: Arc, clip: FileClip) -> Node { let path = self.clipping_path(clip); let group_id = NodeId(self.next); self.next += 1; Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true }) } - /// A clipping path of `clip`, with the next node id. - fn clipping_path(&mut self, clip: PathData) -> Node { + /// A clipping path of `clip` under its fill rule, with the next node id. + fn clipping_path(&mut self, (clip, rule): FileClip) -> Node { let id = NodeId(self.next); self.next += 1; - clipping_path(id, clip) + clipping_path(id, clip, rule) } } @@ -1082,9 +1103,9 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n (frame * at * Affine::scale_non_uniform(size.0 / nw, size.1 / nh), (o.clip && over).then_some((frame, room))) } -/// The clipping path of the clip group of `d` holding just object `id` becomes `path`; false when -/// no such clip group holds it. -fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { +/// The clipping path of the clip group of `d` holding just object `id` becomes `path`, under fill +/// rule `rule` when one is given; false when no such clip group holds it. +fn set_clip_path(d: &mut Document, id: NodeId, path: PathData, rule: Option) -> bool { let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind { NodeKind::Group { children, clip: true } => match &children[..] { [c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id), @@ -1093,8 +1114,9 @@ fn set_clip_path(d: &mut Document, id: NodeId, path: PathData) -> bool { _ => None, }); let Some(c) = clip_path else { return false }; - if let Some(Node { kind: NodeKind::Path { path: p, .. }, .. }) = d.node_mut(c) { + if let Some(Node { kind: NodeKind::Path { path: p, rule: r, .. }, .. }) = d.node_mut(c) { *p = path; + *r = rule.unwrap_or(*r); } true } @@ -1108,25 +1130,25 @@ fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> { /// Clip object `id` of `d` to `path`: the clipping path of the clip group holding just it changes, /// else it goes into a new clip group. fn clip_image_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { + if set_clip_path(d, id, path.clone(), None) { return Ok(()); } - new_clip_group(d, id, path) + new_clip_group(d, id, (path, FillRule::NonZero)) } -/// Clip object `id` of `d` to `path`, the clipping path its DCS file draws it through: the clipping -/// path of the clip group holding just it changes, a plain group holding just it (as [`unclip`] -/// leaves one) becomes a clip group again, else it goes into a new clip group. -fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { - if set_clip_path(d, id, path.clone()) { +/// Clip object `id` of `d` to `path`, the clipping path its file draws it through, under its fill +/// rule: the clipping path of the clip group holding just it changes, a plain group holding just it +/// (as [`unclip`] leaves one) becomes a clip group again, else it goes into a new clip group. +fn clip_file_to(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { + if set_clip_path(d, id, path.clone(), Some(rule)) { return Ok(()); } let plain = d.parent_of(id).filter(|g| match d.node(*g).map(|n| &n.kind) { Some(NodeKind::Group { children, clip: false }) => matches!(&children[..], [o] if o.id == id), _ => false, }); - let Some(g) = plain else { return new_clip_group(d, id, path) }; - let clip = clipping_path(d.alloc_id(), path); + let Some(g) = plain else { return new_clip_group(d, id, (path, rule)) }; + let clip = clipping_path(d.alloc_id(), path, rule); d.insert(Some(g), 0, clip)?; if let Some(Node { kind: NodeKind::Group { clip, .. }, .. }) = d.node_mut(g) { *clip = true; @@ -1134,30 +1156,33 @@ fn clip_file_to(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { Ok(()) } -/// Clipping path `path` (a node) with its path changed to `clip`. -fn with_clip(path: &Node, clip: PathData) -> Arc { +/// Clipping path `path` (a node) with its path changed to `clip`, and its fill rule to `rule` when +/// one is given. +fn with_clip(path: &Node, clip: PathData, rule: Option) -> Arc { let mut path = Node::clone(path); - if let NodeKind::Path { path: p, .. } = &mut path.kind { + if let NodeKind::Path { path: p, rule: r, .. } = &mut path.kind { *p = clip; + *r = rule.unwrap_or(*r); } Arc::new(path) } -/// A clipping path `id` of `path`, unpainted. -fn clipping_path(id: NodeId, path: PathData) -> Node { +/// A clipping path `id` of `path` under fill rule `rule`, unpainted. +fn clipping_path(id: NodeId, path: PathData, rule: FillRule) -> Node { let none = vectorcraft_color::Paint::None; let mut clip = Node::path(id, path, Appearance::basic(none.clone(), none, 0.0)); - if let NodeKind::Path { clipping, .. } = &mut clip.kind { + if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind { *clipping = true; + *r = rule; } clip } -/// Put object `id` of `d` into a new clip group of `path`, where it is. -fn new_clip_group(d: &mut Document, id: NodeId, path: PathData) -> Result<()> { +/// Put object `id` of `d` into a new clip group of `path`, under its fill rule, where it is. +fn new_clip_group(d: &mut Document, id: NodeId, (path, rule): FileClip) -> Result<()> { let (par, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?; let image = d.remove(id)?; - let clip = clipping_path(d.alloc_id(), path); + let clip = clipping_path(d.alloc_id(), path, rule); let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), image], clip: true }); d.insert(par, index, group)?; Ok(()) @@ -1186,15 +1211,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let nested = nested_ids(d, ids); if also.is_some() || !nested.is_empty() { let pick = |n: &Node| matches!(n.kind, NodeKind::Image(_)) && (nested.contains(&n.id) || also.is_some_and(|also| shows(n, also, false))); - // The resolution of each content the images picked show, and the clipping path its DCS file + // The resolution of each content the images picked show, and the clipping path its file // drew it through, looked up once each. - let mut old: BTreeMap)> = BTreeMap::new(); + let mut old: BTreeMap)> = BTreeMap::new(); d.visit_stored(|n, _| { if let NodeKind::Image(im) = &n.kind && pick(n) && !old.contains_key(&im.key) { - old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(ImageBlob::separated_clip))); + old.insert(im.key.clone(), (file_pt(d, &im.key), d.images.get(&im.key).and_then(file_clip))); } }); let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { @@ -1220,8 +1245,9 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (xf, clip) = placed_xf(im.xf, size(im.width, im.height), file_pt(d, &im.key), size(img.width, img.height), new_pt, o); - // Placement Options' clip, else a DCS file's clipping path, read again with its plates. - let old_clip = d.images.get(&im.key).and_then(ImageBlob::separated_clip); + // Placement Options' clip, else the clipping path of a DCS file (read again with its + // plates) or of a PSD or PSB file. + let old_clip = d.images.get(&im.key).and_then(file_clip); clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind @@ -1235,8 +1261,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio clips.into_iter().try_for_each(|(id, clip)| match clip { ClipTo::Keep => Ok(()), ClipTo::Path(path) => clip_image_to(d, id, path), - ClipTo::File(path) => clip_file_to(d, id, path), - ClipTo::Nest(path) => new_clip_group(d, id, path), + ClipTo::File(file) => clip_file_to(d, id, file), + ClipTo::Nest(file) => new_clip_group(d, id, file), ClipTo::Off => unclip(d, id), ClipTo::Both { file, placement } => { match file { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 83216b2f43..1b0ec6b888 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -304,7 +304,7 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes)); let mut warnings: Vec = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect(); *slices_out = psd_slices(slices_from, natural, &mut warnings); - let clip = fileio::psdread::clipping_path(&src.bytes); + let clip = img.clip.clone().map(|(path, _)| path); return Ok(Loaded { name, format, art: Art::Image(img, clip), natural, warnings, link, board: None }); } if pdf { diff --git a/crates/engine/src/cmd/place/dcs.rs b/crates/engine/src/cmd/place/dcs.rs index 69a397c5d1..efa02e06a8 100644 --- a/crates/engine/src/cmd/place/dcs.rs +++ b/crates/engine/src/cmd/place/dcs.rs @@ -104,6 +104,7 @@ pub(crate) fn read(bytes: &[u8], path: Option<&str>) -> Result { }; let blob = ImageBlob::separated_tiff_clipped(&p.separated, p.ppi, &files, clip.as_ref()) .ok_or_else(|| EngineError::Other("the plates can't be kept".into()))?; + let clip = clip.map(|path| (path, vectorcraft_geom::FillRule::NonZero)); let img = RasterImage { key: blob.content_key(), blob, width: p.separated.width, height: p.separated.height, ppi: p.ppi, clip }; let spots = p.separated.spots().map(|s| (s.name.clone(), s.cmyk)).collect(); Ok(DcsArt { img, xf: p.xf, page: p.page, clip: p.clip, spots, warnings: p.warnings }) diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..cb6bdad68c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8691,7 +8691,10 @@ path is that path, under the even-odd rule, so the image shows only inside it. T that can be edited or released. `file.place` answers `image`, the id of the image in the clip group. The [import options help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) says that a file imported as one flattened image keeps the document's clipping path when it has one. `links.update` -and `links.relink` read the file's pixels again and leave the clip group and its clipping path as they are. Files that name no clipping path, or name a path +and `links.relink` read the file again: the clip group's clipping path becomes the one the new file names, under the +even-odd rule, and the clip group stays as a plain group of the image when the new file names none. A plain image relinked to such a +file goes into a clip group of its path. A clip group whose clipping path was changed in the document, or whose fill rule was, is kept as a +clipping mask, with the file's clip group inside it. Files that name no clipping path, or name a path they don't have, come in as a plain image. `file.place` with `replace` on such a clip group puts a new image, clipped or not, at the scale and rotation of the image in the group. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..6fade6b57b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1879,7 +1879,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` keep the clip group, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`). - Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`). From a670cd11023a46aee950964591ab723f8a8f9570 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:05:55 -0800 Subject: [PATCH 22/41] File Info: metadata templates save, import and list from the File Info menu File Info's menu saves the fields as an XMP metadata template (into the Metadata Templates folder next to the preferences, or any file), imports one with a choice of three merges, lists the saved templates and opens the folder. The import is one undo step and records nothing when no field changes. - file.info.saveTemplate writes the title (when it is not the document's name), author, author title, description, keywords, rating, copyright status, notice and URL that have a value. - file.info.applyTemplate reads a file, a saved template or XMP text (at most 8 MB) and merges it: replace clears the fields first, keep takes each field the template has, append adds keywords and fills only empty fields. apply: false returns the merged fields without changing the document. - file.info.templates lists the folder's .xmp files. - A PDF or .ai also opens with the rating and author title its XMP packet gives. Docs: docs/mcp.md, docs/target-app-parity.md. --- apps/vectorcraft-cli/src/main.rs | 3 +- apps/vectorcraft/src/main.rs | 2 + apps/vectorcraft/src/prefs_dir.rs | 8 + crates/engine/src/cmd/docmenu.rs | 27 ++ crates/engine/src/cmd/fileinfo.rs | 331 +++++++++++++++++++++++- crates/engine/src/lib.rs | 3 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/fileinfo.rs | 221 ++++++++++++++++ crates/pdf/src/file_info.rs | 86 ++++++ crates/pdf/src/lib.rs | 2 +- crates/pdf/src/post.rs | 2 +- crates/pdf/src/tests/file_info.rs | 47 ++++ crates/ui-egui/src/dialogs/file_info.rs | 220 +++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 12 + crates/ui-egui/src/i18n/cs.tsv | 12 + crates/ui-egui/src/i18n/da.tsv | 12 + crates/ui-egui/src/i18n/de.tsv | 12 + crates/ui-egui/src/i18n/el.tsv | 12 + crates/ui-egui/src/i18n/es.tsv | 12 + crates/ui-egui/src/i18n/fi.tsv | 12 + crates/ui-egui/src/i18n/fr.tsv | 12 + crates/ui-egui/src/i18n/gu.tsv | 6 + crates/ui-egui/src/i18n/hi.tsv | 12 + crates/ui-egui/src/i18n/hu.tsv | 12 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 12 + crates/ui-egui/src/i18n/ja.tsv | 12 + crates/ui-egui/src/i18n/ka.tsv | 12 + crates/ui-egui/src/i18n/ko.tsv | 12 + crates/ui-egui/src/i18n/nl.tsv | 12 + crates/ui-egui/src/i18n/pl.tsv | 12 + crates/ui-egui/src/i18n/pt-br.tsv | 12 + crates/ui-egui/src/i18n/ru.tsv | 12 + crates/ui-egui/src/i18n/sv.tsv | 12 + crates/ui-egui/src/i18n/tr.tsv | 12 + crates/ui-egui/src/i18n/uk.tsv | 12 + crates/ui-egui/src/i18n/vi.tsv | 12 + crates/ui-egui/src/i18n/zh-hans.tsv | 12 + crates/ui-egui/src/i18n/zh-hant.tsv | 12 + docs/mcp.md | 28 ++ docs/target-app-parity.md | 1 + 43 files changed, 1273 insertions(+), 18 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index b66c15070f..4711232643 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,11 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// (`script.listInstalled`), keeps File Info's metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and /// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c55785cfdf..19bef080c7 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -498,6 +498,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + // File Info's metadata templates live in their own folder next to the preferences. + prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..1a33352ffc 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template +/// makes. +pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Metadata Templates") { + session.attach_metadata_templates_dir(dir); + } +} + /// Have File › New start each category's documents from its profile in the `New Document /// Profiles` folder, which `file.newProfiles.edit` makes. pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index ae48ba02e6..ee6e3c2834 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -269,6 +269,33 @@ pub fn specs() -> Vec { has_doc, super::fileinfo::file_info ), + cmd!( + "file.info.saveTemplate", + "Save Metadata Template…", + [], + None, + "{name?: save into the metadata templates folder as .xmp (a name with characters file systems reject, a dot at either end, or a device name is an error (spaces at either end are dropped); the same name replaces that template), path?: save to this file instead (not both), fields?: {File Info fields as file.info takes them} save these instead of the document's (default: the document's File Info)} write the File Info as an XMP metadata template: title (only one of its own, not Untitled-N), author, authorTitle, description, keywords, rating (1–5), copyrightStatus, copyrightNotice and copyrightUrl, each where it has a value; the dates are left out → {name, path} (with name), {path} (with path), or {data: the XMP text} with neither", + has_doc, + super::fileinfo::save_template + ), + cmd!( + "file.info.applyTemplate", + "Import Metadata Template…", + [], + None, + "{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)", + has_doc, + super::fileinfo::apply_template + ), + cmd!( + query "file.info.templates", + "Metadata Templates", + [], + None, + "{create?: false (true: make the folder when it is missing)} the metadata templates in the metadata templates folder next to the preferences, sorted by name, at most 1,000 → {templates: [{name, file: the file name, path}], folder?: the folder (left out for a request that may not read it, in runs without preferences and on the web, where the list is empty)}", + super::always, + super::fileinfo::templates + ), ] } diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index 9a59d0f2f8..b94fa1fe81 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -3,14 +3,28 @@ //! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]), //! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or //! `.ai` opens with the File Info it gives ([`read_pdf`]). +//! +//! Metadata templates: `file.info.saveTemplate` writes the File Info as an XMP file +//! ([`vectorcraft_pdf::metadata_template`]), `file.info.applyTemplate` merges one into the File +//! Info, and `file.info.templates` lists those in the metadata templates folder. use serde_json::{Map, Value, json}; use vectorcraft_doc::metadata::{MAX_RATING, iso8601}; use vectorcraft_doc::{ColorMode, CopyrightStatus, DocMetadata, Document}; -use super::{Result, Session, bad}; +use super::{Result, Session, bad, switch_or, text_param}; const C: &str = "file.info"; +const SAVE: &str = "file.info.saveTemplate"; +const APPLY: &str = "file.info.applyTemplate"; +const LIST: &str = "file.info.templates"; +/// The extension of a metadata template file. +const TEMPLATE_EXT: &str = "xmp"; +/// The most templates `file.info.templates` lists. +const MAX_LISTED: usize = 1000; +/// The largest metadata template `file.info.saveTemplate` writes and `file.info.applyTemplate` +/// reads, in bytes (8 MB). The largest template File Info's fields can give is under 4 MB. +const MAX_TEMPLATE_FILE: usize = vectorcraft_pdf::MAX_TEMPLATE_BYTES; /// Longest text field, in characters. const MAX_TEXT: usize = 65_536; /// Longest keyword, in characters. @@ -21,9 +35,13 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb /// What `file.info` reports (and takes back). pub(crate) fn info_json(d: &Document) -> Value { - let m = &d.metadata; + info_json_with(d, d.info_title(), &d.metadata) +} + +/// [`info_json`] with the title `title` and the metadata `m` in place of the document's. +fn info_json_with(d: &Document, title: &str, m: &DocMetadata) -> Value { json!({ - "title": d.info_title(), + "title": title, "author": m.author, "authorTitle": m.author_title, "description": m.description, @@ -48,11 +66,25 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result { Value::Object(o) => o, _ => return Err(bad(C, "params must be an object")), }; + let (title, m) = edited(s, Some(o))?; + commit(s, title, m)?; + Ok(info_json(&s.doc()?.doc)) +} + +/// The active document's File Info title and metadata with `fields` (as `file.info` takes them) +/// applied. +fn edited(s: &Session, fields: Option<&Map>) -> Result<(String, DocMetadata)> { let d = &s.doc()?.doc; let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone()); - for (k, v) in o { + for (k, v) in fields.into_iter().flatten() { apply(&mut title, &mut m, k, v)?; } + Ok((title, m)) +} + +/// Make `title` and `m` the active document's File Info in one undo step; nothing is recorded when +/// they are what it has. Whether anything changed. +fn commit(s: &mut Session, title: String, mut m: DocMetadata) -> Result { let d = &s.doc()?.doc; // A title File Info changes becomes the document's own, as it always has (the tab and Save As // offer it where the document has no file), and replaces the one its file gave. @@ -60,16 +92,287 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result { if retitled { m.title = None; } - if retitled || m != d.metadata { - s.edit("File Info", |d, _| { - if retitled { - d.title = title; - } - d.metadata = m; - Ok(()) - })?; + if !retitled && m == d.metadata { + return Ok(false); } - Ok(info_json(&s.doc()?.doc)) + s.edit("File Info", |d, _| { + if retitled { + d.title = title; + } + d.metadata = m; + Ok(()) + })?; + Ok(true) +} + +/// The optional object `p` gives for `key`. +fn fields_param<'a>(p: &'a Value, key: &str, c: &str) -> Result>> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Object(o)) => Ok(Some(o)), + Some(_) => Err(bad(c, format!("`{key}` must be an object"))), + } +} + +impl Session { + /// Have `file.info.saveTemplate`, `file.info.applyTemplate` and `file.info.templates` keep the + /// metadata templates in the folder `dir`, which a save makes when it is missing. + pub fn attach_metadata_templates_dir(&mut self, dir: std::path::PathBuf) { + self.metadata_templates_dir = Some(dir); + } + + /// The metadata templates folder ([`Session::attach_metadata_templates_dir`]); none on the web, + /// which has no folders. + pub fn metadata_templates_dir(&self) -> Option<&std::path::Path> { + self.metadata_templates_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } +} + +/// The metadata template of the File Info `title` and `m`: each field that has a value, the title +/// only where it is one of its own ([`super::fileio::is_own_title`]), the rating only from 1 up. +fn template_of(title: &str, m: &DocMetadata) -> vectorcraft_pdf::FileInfo { + let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string()); + vectorcraft_pdf::FileInfo { + title: super::fileio::is_own_title(title).then(|| title.to_string()), + author: text(&m.author), + author_title: text(&m.author_title), + description: text(&m.description), + keywords: (!m.keywords.is_empty()).then(|| m.keywords.clone()), + rating: (m.rating > 0).then_some(m.rating), + copyright_notice: text(&m.copyright_notice), + copyright_url: text(&m.copyright_url), + copyrighted: match m.copyright_status { + CopyrightStatus::Copyrighted => Some(true), + CopyrightStatus::PublicDomain => Some(false), + CopyrightStatus::Unknown => None, + }, + ..Default::default() + } +} + +/// The path of the template `name` in the folder `dir`: `name` made a safe file name, with +/// [`TEMPLATE_EXT`]. +fn template_path(dir: &std::path::Path, name: &str, c: &str) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(bad(c, "the template name can't be empty")); + } + Ok(dir.join(super::swatchlib::library_file_name(name, TEMPLATE_EXT)).to_string_lossy().into_owned()) +} + +/// The error for a template over [`MAX_TEMPLATE_FILE`]. +fn too_big(c: &str) -> crate::EngineError { + bad(c, format!("the file is larger than {} MB", MAX_TEMPLATE_FILE >> 20)) +} + +/// File Info › Save Metadata Template: `file.info.saveTemplate {name?, path?, fields?}`. +pub(crate) fn save_template(s: &mut Session, p: &Value) -> Result { + let name = text_param(p, "name", SAVE)?; + let path = text_param(p, "path", SAVE)?; + let (title, m) = edited(s, fields_param(p, "fields", SAVE)?)?; + let xmp = vectorcraft_pdf::metadata_template(&template_of(&title, &m)); + if xmp.len() > MAX_TEMPLATE_FILE { + return Err(too_big(SAVE)); + } + match (name, path) { + (Some(_), Some(_)) => Err(bad(SAVE, "give `name` or `path`, not both")), + (Some(name), None) => { + let dir = s.metadata_templates_dir().ok_or_else(|| bad(SAVE, "no metadata templates folder here"))?.to_path_buf(); + let path = template_path(&dir, name, SAVE)?; + // The name is the file name as it is, so two names never share a file. + let listed = std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().into_owned()); + if listed.as_deref() != Some(name.trim()) { + return Err(bad(SAVE, "the template name isn't usable as a file name")); + } + // Only a file in the folder itself is replaced: a link there is not followed. + if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) { + return Err(crate::EngineError::Other(format!("{path}: not a file"))); + } + let dir = dir.to_string_lossy().into_owned(); + // The app's own folder, under a name checked above: no root applies. + crate::file_access::unconfined(|| super::fileio::create_dir(&dir).and_then(|()| super::fileio::write_file(&path, xmp.as_bytes())))?; + Ok(json!({ "name": listed, "path": super::fileio::shown_path(&path) })) + } + (None, Some(path)) => { + super::fileio::write_file(path, xmp.as_bytes())?; + Ok(json!({ "path": path })) + } + (None, None) => Ok(json!({ "data": xmp })), + } +} + +/// How `file.info.applyTemplate` merges a template's fields into the File Info. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Merge { + /// Clear the fields a template can hold, then take the template's. + Replace, + /// Keep the fields, and take each one the template gives. + Keep, + /// Keep the fields: add the template's keywords, and take its other fields only where the File + /// Info has none. + Append, +} + +/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`. +pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result { + let mode = match text_param(p, "mode", APPLY)? { + Some("replace") => Merge::Replace, + Some("keep") => Merge::Keep, + Some("append") => Merge::Append, + _ => return Err(bad(APPLY, "mode must be replace, keep or append")), + }; + let apply = switch_or(p, "apply", true, APPLY)?; + let base = fields_param(p, "base", APPLY)?; + let bytes = template_bytes(s, p)?; + let t = vectorcraft_pdf::read_template(&bytes).ok_or_else(|| bad(APPLY, "the file is not an XMP metadata template"))?; + let (mut title, mut m) = edited(s, base)?; + merge(&mut title, &mut m, t, mode); + if !apply { + return Ok(info_json_with(&s.doc()?.doc, &title, &m)); + } + let changed = commit(s, title, m)?; + let mut out = info_json(&s.doc()?.doc); + out["changed"] = json!(changed); + Ok(out) +} + +/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or +/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long. +fn template_bytes(s: &Session, p: &Value) -> Result> { + let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?]; + // At most one byte past the limit is read, so a huge file is never read whole. + let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1); + let bytes = match given { + [Some(path), None, None] => read(path)?, + [None, Some(name), None] => { + let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?; + let mut path = template_path(dir, name, APPLY)?; + // A template `file.info.templates` lists: by its `file` first, then by its `name` with + // the extension in lowercase, then in other letter case. Only files in the folder itself + // are listed: a link there is not followed. + let name = name.trim(); + let own = format!("{name}.{TEMPLATE_EXT}"); + let listed = template_files(dir) + .filter(|f| f == name || f.rsplit_once('.').is_some_and(|(stem, _)| stem == name)) + .min_by_key(|f| (f != name, *f != own)); + if let Some(file) = listed { + path = dir.join(file).to_string_lossy().into_owned(); + } + let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()); + if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) { + return Err(crate::EngineError::Other(format!("{path}: not a file"))); + } + // The app's own folder: no root applies. + crate::file_access::unconfined(|| read(&path))? + } + [None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)), + [None, None, Some(data)] => data.as_bytes().to_vec(), + _ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")), + }; + if bytes.len() > MAX_TEMPLATE_FILE { + return Err(too_big(APPLY)); + } + Ok(bytes) +} + +/// Merge the template `t` into the File Info `title` and `m` as `mode` says. Each field goes in as +/// `file.info` would take it; a value it would refuse is left out. +fn merge(title: &mut String, m: &mut DocMetadata, t: vectorcraft_pdf::FileInfo, mode: Merge) { + if mode == Merge::Replace { + // The title is never cleared: a document always has one. + m.author.clear(); + m.author_title.clear(); + m.description.clear(); + m.keywords.clear(); + m.rating = 0; + m.copyright_status = CopyrightStatus::Unknown; + m.copyright_notice.clear(); + m.copyright_url.clear(); + } + let status = t.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); + let fields = [ + ("title", t.title.map(Value::from)), + ("author", t.author.map(Value::from)), + ("authorTitle", t.author_title.map(Value::from)), + ("description", t.description.map(Value::from)), + ("keywords", t.keywords.map(Value::from)), + ("rating", t.rating.map(Value::from)), + ("copyrightStatus", status.map(|s| Value::from(s.id()))), + ("copyrightNotice", t.copyright_notice.map(Value::from)), + ("copyrightUrl", t.copyright_url.map(Value::from)), + ]; + for (k, v) in fields { + let Some(mut v) = v else { continue }; + if mode == Merge::Append { + let empty = match k { + "title" => !super::fileio::is_own_title(title), + "author" => m.author.is_empty(), + "authorTitle" => m.author_title.is_empty(), + "description" => m.description.is_empty(), + "rating" => m.rating == 0, + "copyrightStatus" => m.copyright_status == CopyrightStatus::Unknown, + "copyrightNotice" => m.copyright_notice.is_empty(), + "copyrightUrl" => m.copyright_url.is_empty(), + _ => true, + }; + if !empty { + continue; + } + if k == "keywords" { + let mut all: Vec = m.keywords.iter().cloned().map(Value::from).collect(); + all.extend(v.as_array().cloned().unwrap_or_default()); + v = Value::from(all); + } + } + // `apply` changes the field only when it takes the value. + let _ = apply(title, m, k, &v); + } +} + +/// The file names of the templates in the folder `dir`: its files with a name before the +/// [`TEMPLATE_EXT`] extension, in any case. The app's own folder, read directly; a folder not made +/// yet holds none. +fn template_files(dir: &std::path::Path) -> impl Iterator { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|file| file.rsplit_once('.').is_some_and(|(stem, ext)| ext.eq_ignore_ascii_case(TEMPLATE_EXT) && !stem.is_empty())) +} + +/// `file.info.templates {create?}`: the metadata templates in the folder, by name. +pub(crate) fn templates(s: &mut Session, p: &Value) -> Result { + let create = switch_or(p, "create", false, LIST)?; + let Some(dir) = s.metadata_templates_dir().map(|d| d.to_string_lossy().into_owned()) else { + return Ok(json!({ "templates": [] })); + }; + if create { + // The app's own folder: no root applies. + crate::file_access::unconfined(|| super::fileio::create_dir(&dir))?; + } + // The first [`MAX_LISTED`] by name, with no more than that many held at once. + let mut files = std::collections::BTreeSet::new(); + for file in template_files(std::path::Path::new(&dir)) { + files.insert(file); + if files.len() > MAX_LISTED { + files.pop_last(); + } + } + let list: Vec = files + .iter() + .filter_map(|file| { + let (stem, _) = file.rsplit_once('.')?; + let path = std::path::Path::new(&dir).join(file).to_string_lossy().into_owned(); + Some(json!({ "name": stem, "file": file, "path": super::fileio::shown_path(&path) })) + }) + .collect(); + let mut out = json!({ "templates": list }); + if super::fileio::shown_path(&dir) == dir.as_str() { + out["folder"] = json!(dir); + } + Ok(out) } /// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each @@ -79,8 +382,10 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) { let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain }); let fields = [ ("author", f.author.map(Value::from)), + ("authorTitle", f.author_title.map(Value::from)), ("description", f.description.map(Value::from)), ("keywords", f.keywords.map(Value::from)), + ("rating", f.rating.map(Value::from)), ("copyrightStatus", status.map(|s| Value::from(s.id()))), ("copyrightNotice", f.copyright_notice.map(Value::from)), ("copyrightUrl", f.copyright_url.map(Value::from)), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4b47966463..9bad697683 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -178,6 +178,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The folder of File Info's metadata templates; `None`: no folder + /// ([`Session::attach_metadata_templates_dir`]). + metadata_templates_dir: Option, /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1244b77432..243092e1f5 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -93,6 +93,7 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, + metadata_templates_dir: None, new_doc_profile_dir: None, plugin_output: None, plugin_install_approval: None, diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index 4d86a84b3c..f04a9208a3 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -559,3 +559,224 @@ fn an_untitled_document_saved_to_a_file_exports_titled_after_it() { } let _ = std::fs::remove_dir_all(dir); } + +/// A session whose metadata templates folder is `dir/Metadata Templates`, with a document titled +/// Poster. +fn template_session(dir: &std::path::Path) -> Session { + let mut s = session(); + s.attach_metadata_templates_dir(dir.join("Metadata Templates")); + s +} + +#[test] +fn a_saved_metadata_template_is_listed_and_applies_to_another_document() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template"); + let mut s = template_session(&dir); + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([]), "no folder yet"); + s.execute("file.info", &info()).unwrap(); + let r = s.execute("file.info.saveTemplate", &json!({"name": " Studio "})).unwrap(); + assert_eq!(r["name"], "Studio"); + let path = dir.join("Metadata Templates").join("Studio.xmp"); + assert!(path.is_file(), "saved into the folder: {r}"); + let listed = s.execute("file.info.templates", &json!({})).unwrap(); + assert_eq!(listed["templates"][0]["name"], "Studio"); + assert_eq!(listed["templates"].as_array().map(Vec::len), Some(1)); + // A name that isn't a usable file name as it is is refused, so `a/b` and `a?b` never share a file. + for name in ["a/b", "a?b", "CON", "Studio.", "x\u{1}"] { + assert!(s.execute("file.info.saveTemplate", &json!({"name": name})).is_err(), "{name}"); + } + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"].as_array().map(Vec::len), Some(1)); + // Saving is not an edit of the document. + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + // Into a new document, by name, in one undo step. + s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "Studio", "mode": "keep"})).unwrap(); + assert_eq!(r["changed"], true); + let m = &s.doc().unwrap().doc.metadata; + assert_eq!((m.author.as_str(), m.author_title.as_str(), m.rating), ("Ada Lovelace", "Designer", 4)); + assert_eq!(m.keywords, ["fair", "Poster", "print"]); + assert_eq!((m.copyright_status, m.copyright_notice.as_str()), (CopyrightStatus::Copyrighted, "(c) 2026 Ada")); + assert_eq!(m.description, "A poster\nfor the fair"); + assert_eq!(r["title"], "Poster", "the template carries the title of its own"); + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + // Applied again, nothing changes and nothing is recorded. + let r = s.execute("file.info.applyTemplate", &json!({"path": path.to_str().unwrap(), "mode": "keep"})).unwrap(); + assert_eq!(r["changed"], false); + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.metadata.author, ""); + // The same name replaces the template. + s.execute("file.info.saveTemplate", &json!({"name": "Studio", "fields": {"author": "Grace"}})).unwrap(); + let back = vectorcraft_pdf::read_template(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(back.author.as_deref(), Some("Grace")); + assert_eq!(back.title, None, "an Untitled-N title is not written"); +} + +#[test] +fn a_metadata_template_merges_in_three_modes() { + let mut s = session(); + s.execute("file.info", &json!({"author": "Ada", "keywords": ["fair"], "rating": 2, "copyrightUrl": "https://example.com/a"})).unwrap(); + let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { + author: Some("Grace".into()), + description: Some("From the template".into()), + keywords: Some(vec!["print".into(), "Fair".into()]), + rating: Some(5), + copyrighted: Some(false), + ..Default::default() + }); + let merged = + |s: &mut Session, mode: &str| s.execute("file.info.applyTemplate", &json!({"data": template, "mode": mode, "apply": false})).unwrap(); + // Clear and replace: the fields the template lacks are cleared; the title stays. + let r = merged(&mut s, "replace"); + assert_eq!((r["author"].as_str(), r["description"].as_str(), r["rating"].as_u64()), (Some("Grace"), Some("From the template"), Some(5))); + assert_eq!( + (r["keywords"].clone(), r["copyrightUrl"].as_str(), r["copyrightStatus"].as_str()), + (json!(["print", "Fair"]), Some(""), Some("publicDomain")) + ); + assert_eq!(r["title"], "Poster"); + // Keep and replace: the template's fields replace those it has; the others stay. + let r = merged(&mut s, "keep"); + assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["copyrightUrl"].as_str()), (Some("Grace"), Some(5), Some("https://example.com/a"))); + assert_eq!(r["keywords"], json!(["print", "Fair"])); + // Keep and append: keywords are added (each once), and only empty fields are filled. + let r = merged(&mut s, "append"); + assert_eq!((r["author"].as_str(), r["rating"].as_u64(), r["description"].as_str()), (Some("Ada"), Some(2), Some("From the template"))); + assert_eq!((r["keywords"].clone(), r["copyrightStatus"].as_str()), (json!(["fair", "print"]), Some("publicDomain"))); + // `apply: false` changed nothing; `base` merges into the given fields instead. + assert_eq!(s.doc().unwrap().history.undo.len(), 1); + assert_eq!(s.doc().unwrap().doc.metadata.author, "Ada"); + let r = s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "append", "apply": false, "base": {"author": ""}})).unwrap(); + assert_eq!(r["author"], "Grace"); + // Applied: one undo step. + s.execute("file.info.applyTemplate", &json!({"data": template, "mode": "replace"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), 2); + assert_eq!(s.doc().unwrap().doc.metadata.copyright_url, ""); +} + +#[test] +fn metadata_template_errors() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-errors"); + let mut s = template_session(&dir); + let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() }); + let not_xmp = dir.join("note.xmp"); + std::fs::write(¬_xmp, "not metadata").unwrap(); + let big = dir.join("big.xmp"); + std::fs::write(&big, vec![b' '; vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1]).unwrap(); + let e = s.execute("file.info.applyTemplate", &json!({"path": big.to_str().unwrap(), "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + let e = s.execute("file.info.applyTemplate", &json!({"data": " ".repeat(vectorcraft_pdf::MAX_TEMPLATE_BYTES + 1), "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("larger than 8 MB"), "{e}"); + for bad in [ + json!({"data": xmp, "mode": "merge"}), + json!({"data": xmp}), + json!({"data": xmp, "mode": 3}), + json!({"mode": "keep"}), + json!({"data": xmp, "path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"path": dir.join("missing.xmp").to_str().unwrap(), "mode": "keep"}), + json!({"path": not_xmp.to_str().unwrap(), "mode": "keep"}), + json!({"path": big.to_str().unwrap(), "mode": "keep"}), + json!({"name": "missing", "mode": "keep"}), + json!({"data": "Ada Lovelace", "mode": "keep"}), + json!({"data": xmp, "mode": "keep", "apply": "yes"}), + json!({"data": xmp, "mode": "keep", "base": [1]}), + json!({"data": xmp, "mode": "keep", "base": {"rating": 9}}), + ] { + assert!(s.execute("file.info.applyTemplate", &bad).is_err(), "{bad}"); + } + for bad in [json!({"name": "a", "path": "b.xmp"}), json!({"name": " "}), json!({"fields": {"rating": 9}}), json!({"fields": "x"})] { + assert!(s.execute("file.info.saveTemplate", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), 0); + assert!(!dir.join("Metadata Templates").exists(), "no failed save made the folder"); + // A link in the folder is not followed, by its name or its file name. + #[cfg(unix)] + { + let outside = dir.join("outside.xmp"); + std::fs::write(&outside, &xmp).unwrap(); + std::fs::create_dir_all(dir.join("Metadata Templates")).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Metadata Templates").join("Linked.xmp")).unwrap(); + for name in ["Linked", "Linked.xmp"] { + assert!(s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "keep"})).is_err(), "{name}"); + } + let e = s.execute("file.info.applyTemplate", &json!({"name": "Linked", "mode": "keep"})).unwrap_err(); + assert!(e.to_string().contains("not a file"), "{e}"); + assert_eq!(s.execute("file.info.templates", &json!({})).unwrap()["templates"], json!([])); + // A save by that name leaves the linked file as it was. + let e = s.execute("file.info.saveTemplate", &json!({"name": "Linked", "fields": {"author": "Grace"}})).unwrap_err(); + assert!(e.to_string().contains("not a file"), "{e}"); + assert_eq!(std::fs::read_to_string(&outside).unwrap(), xmp); + std::fs::remove_dir_all(dir.join("Metadata Templates")).unwrap(); + } + // Without a folder (runs without preferences), a name is an error, the data comes back, and + // the list is empty. + let mut s = session(); + assert!(s.execute("file.info.saveTemplate", &json!({"name": "Studio"})).is_err()); + let data = s.execute("file.info.saveTemplate", &json!({"fields": {"author": "Ada"}})).unwrap()["data"].as_str().unwrap().to_string(); + assert_eq!(vectorcraft_pdf::read_template(data.as_bytes()).unwrap().author.as_deref(), Some("Ada")); + assert_eq!(s.execute("file.info.templates", &json!({"create": true})).unwrap(), json!({"templates": []})); +} + +#[test] +fn the_templates_folder_lists_only_xmp_files_and_can_be_made() { + let dir = vectorcraft_testkit::TempDir::new("fileinfo-template-list"); + let mut s = template_session(&dir); + let r = s.execute("file.info.templates", &json!({"create": true})).unwrap(); + let folder = dir.join("Metadata Templates"); + assert!(folder.is_dir()); + assert_eq!(r["folder"], folder.to_str().unwrap()); + for f in ["b.XMP", "a.xmp", "notes.txt", ".xmp"] { + std::fs::write(folder.join(f), "x").unwrap(); + } + std::fs::create_dir(folder.join("c.xmp")).unwrap(); + // Other files, however many, leave the templates listed. + for i in 0..1000 { + std::fs::write(folder.join(format!("{i:04}.txt")), "").unwrap(); + } + let names: Vec = s.execute("file.info.templates", &json!({})).unwrap()["templates"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(names, ["a", "b"]); + // A listed name opens whatever the case of its extension. + let xmp = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() }); + std::fs::write(folder.join("b.XMP"), xmp).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b", "mode": "keep"})).unwrap(); + assert_eq!(r["author"], "Grace"); + // Its listed file name opens it too. + let listed = s.execute("file.info.templates", &json!({})).unwrap(); + assert_eq!(listed["templates"][1]["file"], "b.XMP"); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + // A listed file name is taken before the name with `.xmp` added. + let ada = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Ada".into()), ..Default::default() }); + std::fs::write(folder.join("b.XMP.xmp"), ada).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Ada"); +} + +#[test] +fn the_largest_file_info_saves_a_template_that_imports() { + let mut s = session(); + let text = "\"&".repeat(32_768); + let keywords: Vec = (0..1000).map(|i| format!("{i:04}{}", "\"".repeat(252))).collect(); + let fields = json!({ + "author": text, "authorTitle": text, "description": text, "copyrightNotice": text, + "copyrightUrl": format!("https://example.com/{}", "&".repeat(2000)), "keywords": keywords, "rating": 5, "copyrightStatus": "copyrighted", + }); + let data = s.execute("file.info.saveTemplate", &json!({"fields": fields})).unwrap()["data"].as_str().unwrap().to_string(); + assert!(data.len() > 1 << 20, "{} bytes", data.len()); + let r = s.execute("file.info.applyTemplate", &json!({"data": data, "mode": "replace"})).unwrap(); + assert_eq!((r["author"].as_str(), r["keywords"].as_array().map(Vec::len)), (Some(text.as_str()), Some(1000))); +} + +#[test] +fn a_pdf_opens_with_the_rating_and_author_title_its_packet_gives() { + let mut m = DocMetadata::default(); + let f = vectorcraft_pdf::FileInfo { author_title: Some("Editor".into()), rating: Some(3), ..Default::default() }; + crate::cmd::fileinfo::read_pdf(&mut m, f); + assert_eq!((m.author_title.as_str(), m.rating), ("Editor", 3)); +} diff --git a/crates/pdf/src/file_info.rs b/crates/pdf/src/file_info.rs index 1cb0a45273..d238f75105 100644 --- a/crates/pdf/src/file_info.rs +++ b/crates/pdf/src/file_info.rs @@ -2,6 +2,9 @@ //! dictionary (ISO 32000-1 §14.3.3) and the XMP packet of the catalog's metadata stream (§14.3.2, //! ISO 16684-1). Where both give a field, the XMP packet's value is taken; a packet that can't be //! read leaves the information dictionary's values. +//! +//! File › File Info's metadata templates are XMP packets of the same properties: [`metadata_template`] +//! writes one and [`read_template`] reads one back. use craft_pdf::syntax::Pdf; use craft_pdf::syntax::object::{DateTime, Dict, Stream}; @@ -20,6 +23,11 @@ pub(crate) const DC: &str = "http://purl.org/dc/elements/1.1/"; const XMP: &str = "http://ns.adobe.com/xap/1.0/"; // brand-ok: the XMP namespace the files use pub(crate) const XMP_RIGHTS: &str = "http://ns.adobe.com/xap/1.0/rights/"; // brand-ok: the XMP namespace the files use const PDF: &str = "http://ns.adobe.com/pdf/1.3/"; // brand-ok: the XMP namespace the files use +const PHOTOSHOP: &str = "http://ns.adobe.com/photoshop/1.0/"; // brand-ok: the XMP namespace the files use +const X: &str = "adobe:ns:meta/"; // brand-ok: the XMP namespace the files use + +/// The longest metadata template [`read_template`] reads, in bytes. +pub const MAX_TEMPLATE_BYTES: usize = MAX_XMP; /// The File Info fields a PDF gives, each `None` when the file gives none (or only blank text). #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -28,10 +36,15 @@ pub struct FileInfo { pub title: Option, /// XMP `dc:creator` (its names joined with ", "), else Info `Author`. pub author: Option, + /// XMP `photoshop:AuthorsPosition`. + pub author_title: Option, /// XMP `dc:description` (its `x-default` item, else its first), else Info `Subject`. pub description: Option, /// XMP `dc:subject`, else XMP `pdf:Keywords` or Info `Keywords` split at commas and semicolons. pub keywords: Option>, + /// XMP `xmp:Rating`, a whole number from 0 to 5 (a rejected file's -1 and other values are + /// left out). + pub rating: Option, /// XMP `dc:rights` (its `x-default` item, else its first). pub copyright_notice: Option, /// XMP `xmpRights:WebStatement`. @@ -75,12 +88,30 @@ fn packet(pdf: &Pdf) -> Option> { /// The File Info fields of an XMP packet; `None` when it isn't XML in UTF-8 or UTF-16, or when its /// elements nest more than [`MAX_NESTING`] deep. fn xmp(packet: &[u8]) -> Option { + read_xmp(packet, false) +} + +/// The File Info fields of the metadata template `bytes`, an XMP packet as [`metadata_template`] +/// writes one (or any XMP file); `None` when it is longer than [`MAX_TEMPLATE_BYTES`], isn't XML in +/// UTF-8 or UTF-16, has no `rdf:RDF` element, or nests more than [`MAX_NESTING`] deep. +pub fn read_template(bytes: &[u8]) -> Option { + if bytes.len() > MAX_TEMPLATE_BYTES { + return None; + } + read_xmp(bytes, true) +} + +/// [`xmp`]; with `need_rdf`, `None` for XML that has no `rdf:RDF` element. +fn read_xmp(packet: &[u8], need_rdf: bool) -> Option { let text = xml_text(packet)?; // roxmltree parses nested elements recursively. if nesting(&text) > MAX_NESTING { return None; } let xml = roxmltree::Document::parse(&text).ok()?; + if need_rdf && !xml.descendants().any(|n| n.has_tag_name((RDF, "RDF"))) { + return None; + } // The resource's own descriptions: those right under `rdf:RDF`, not the ones inside a value. let descriptions: Vec> = xml .descendants() @@ -95,8 +126,10 @@ fn xmp(packet: &[u8]) -> Option { Some(FileInfo { title: first(DC, "title"), author: (!creators.is_empty()).then(|| creators.join(", ")), + author_title: first(PHOTOSHOP, "AuthorsPosition"), description: first(DC, "description"), keywords: if subjects.is_empty() { first(PDF, "Keywords").map(|k| split(&k)).filter(|k| !k.is_empty()) } else { Some(subjects) }, + rating: first(XMP, "Rating").and_then(|r| rating(&r)), copyright_notice: first(DC, "rights"), copyright_url: first(XMP_RIGHTS, "WebStatement"), copyrighted: first(XMP_RIGHTS, "Marked").and_then(|m| match m.to_ascii_lowercase().as_str() { @@ -109,6 +142,59 @@ fn xmp(packet: &[u8]) -> Option { }) } +/// An `xmp:Rating` value as File Info takes one: a whole number from 0 to 5, written as an integer +/// or as a real with no fraction (`3`, `3.0`). The rejected rating -1, fractions and other values +/// give `None`. +fn rating(s: &str) -> Option { + let r: f64 = s.trim().parse().ok()?; + (r.fract() == 0.0 && (0.0..=5.0).contains(&r)).then_some(r as u8) +} + +/// The metadata template of `f`: an XMP packet (ISO 16684-1) holding its title (`dc:title`), author +/// (`dc:creator`), author title (`photoshop:AuthorsPosition`), description (`dc:description`), +/// keywords (`dc:subject`), rating (`xmp:Rating`), copyright status (`xmpRights:Marked`), notice +/// (`dc:rights`) and URL (`xmpRights:WebStatement`), each where `f` gives it, which +/// [`read_template`] reads back. The dates are left out. +pub fn metadata_template(f: &FileInfo) -> String { + use crate::post::xml_text as esc; + let alt = |name: &str, v: &str| format!(" <{name}>{}\n", esc(v)); + let simple = |name: &str, v: &str| format!(" <{name}>{}\n", esc(v)); + let blank = |v: &Option| v.as_deref().map(str::trim).filter(|v| !v.is_empty()).map(str::to_string); + let mut props = String::new(); + if let Some(v) = blank(&f.title) { + props.push_str(&alt("dc:title", &v)); + } + if let Some(v) = blank(&f.author) { + props.push_str(&format!(" {}\n", esc(&v))); + } + if let Some(v) = blank(&f.author_title) { + props.push_str(&simple("photoshop:AuthorsPosition", &v)); // brand-ok: the XMP property name the files use + } + if let Some(v) = blank(&f.description) { + props.push_str(&alt("dc:description", &v)); + } + let keywords: Vec<&str> = f.keywords.iter().flatten().map(|k| k.trim()).filter(|k| !k.is_empty()).collect(); + if !keywords.is_empty() { + let items: String = keywords.iter().map(|k| format!("{}", esc(k))).collect(); + props.push_str(&format!(" {items}\n")); + } + if let Some(r) = f.rating { + props.push_str(&simple("xmp:Rating", &r.to_string())); + } + if let Some(c) = f.copyrighted { + props.push_str(&simple("xmpRights:Marked", if c { "True" } else { "False" })); + } + if let Some(v) = blank(&f.copyright_notice) { + props.push_str(&alt("dc:rights", &v)); + } + if let Some(v) = blank(&f.copyright_url) { + props.push_str(&simple("xmpRights:WebStatement", &v)); + } + format!( + "\n\n \n \n{props} \n \n\n\n" // brand-ok: the XMP namespace prefix the files use + ) +} + /// A packet's text: UTF-8 (with or without a byte order mark), or UTF-16 told by its byte order /// mark or by a zero byte beside the `<` it starts with. fn xml_text(b: &[u8]) -> Option { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 8f9959c77f..ff1b147c91 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,7 +76,7 @@ mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use encrypt::Encryption; pub use export::{check_page_sizes, export, export_with_report, page_areas}; -pub use file_info::{FileInfo, file_info}; +pub use file_info::{FileInfo, MAX_TEMPLATE_BYTES, file_info, metadata_template, read_template}; #[cfg(any(test, feature = "read-count"))] pub use import::imports_of; pub use import::{ diff --git a/crates/pdf/src/post.rs b/crates/pdf/src/post.rs index c6fdd8048d..79e872e59b 100644 --- a/crates/pdf/src/post.rs +++ b/crates/pdf/src/post.rs @@ -180,7 +180,7 @@ fn rights_properties(info: &DocMetadata) -> String { /// `s` as XML character data: `&`, `<`, `>` and `"` escaped, a carriage return written as the /// character reference ` `, and the characters XML 1.0 doesn't allow left out. -fn xml_text(s: &str) -> String { +pub(crate) fn xml_text(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { match c { diff --git a/crates/pdf/src/tests/file_info.rs b/crates/pdf/src/tests/file_info.rs index 4c837ba67f..57bbdcd58c 100644 --- a/crates/pdf/src/tests/file_info.rs +++ b/crates/pdf/src/tests/file_info.rs @@ -94,8 +94,10 @@ fn the_xmp_packet_gives_file_info() { FileInfo { title: Some("Poster".into()), author: Some("Ada Lovelace, Charles Babbage".into()), + author_title: None, description: Some("A poster\nfor the fair".into()), keywords: Some(vec!["fair".into(), "print".into()]), + rating: None, copyright_notice: Some("(c) 2026 Ada".into()), copyright_url: Some("https://example.com/rights".into()), copyrighted: Some(false), @@ -270,3 +272,48 @@ fn a_written_pdf_gives_its_copyright_back() { let f = file_info(&export(&d, &PdfOptions::uncompressed()).unwrap(), None).unwrap(); assert_eq!((f.author.as_deref(), f.copyright_notice.as_deref()), (Some("Ada"), Some("(c) Ada"))); } + +#[test] +fn a_metadata_template_gives_its_file_info_back() { + let f = FileInfo { + title: Some("Fair poster".into()), + author: Some("Ada & ".into()), + author_title: Some("Designer, \"lead\"".into()), + description: Some("A poster\r\nfor the fair".into()), + keywords: Some(vec!["fair".into(), "print, large".into()]), + rating: Some(4), + copyright_notice: Some("(c) 2026 Ada".into()), + copyright_url: Some("https://example.com/rights?a=1&b=2".into()), + copyrighted: Some(true), + ..Default::default() + }; + let xmp = metadata_template(&f); + assert!(xmp.starts_with(""), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(f)); + // A public-domain status writes Marked False; fields without a value and the dates are left out. + let f = FileInfo { copyrighted: Some(false), author: Some(" ".into()), created: Some(CREATED), ..Default::default() }; + let xmp = metadata_template(&f); + assert!(!xmp.contains("dc:creator") && !xmp.contains("CreateDate") && xmp.contains("False"), "{xmp}"); + assert_eq!(read_template(xmp.as_bytes()), Some(FileInfo { copyrighted: Some(false), ..Default::default() })); + // The template is the PDF packet's format: a PDF whose metadata stream holds one reads the same. + let f = FileInfo { author: Some("Ada".into()), author_title: Some("Editor".into()), rating: Some(2), ..Default::default() }; + let read = file_info(&pdf(None, Some(&metadata_template(&f))), None).unwrap(); + assert_eq!((read.author, read.author_title, read.rating), (f.author, f.author_title, f.rating)); +} + +#[test] +fn a_metadata_template_reads_ratings_and_refuses_what_is_not_xmp() { + let rated = |r: &str| read_template(packet(&description(&format!("xmp:Rating=\"{r}\""), "")).as_bytes()).unwrap().rating; + assert_eq!([rated("0"), rated("5"), rated("3.0"), rated(" 2 ")], [Some(0), Some(5), Some(3), Some(2)]); + // A rejected file's -1, fractions, ratings past 5 and words are left out. + assert_eq!([rated("-1"), rated("2.5"), rated("6"), rated("high")], [None; 4]); + // XML without `rdf:RDF`, text and a packet that isn't well-formed are not templates. + assert_eq!(read_template(b"Poster"), None); + assert_eq!(read_template(b"Ada Lovelace"), None); + assert_eq!(read_template(packet("").as_bytes()), None); + // An XMP packet with no File Info is a template with no fields. + assert_eq!(read_template(packet("").as_bytes()), Some(FileInfo::default())); + // Longer than the longest template read, it is refused without being parsed. + let long = packet(&description("", &" ".repeat(MAX_TEMPLATE_BYTES))); + assert_eq!(read_template(long.as_bytes()), None); +} diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 3f3cbae3f2..b9c12777a9 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -4,6 +4,10 @@ //! Fields: what `file.info` reports (and takes back) plus `__keyword`, the keyword being typed //! (Enter or Add turns it into chips; OK keeps it too). OK runs `file.info` with them: one undo //! step. On an error the dialog stays open. +//! +//! The ≡ menu at the top saves the fields as a metadata template (`file.info.saveTemplate`), imports +//! one (`file.info.applyTemplate`, after a choice of how to merge it into the fields), lists the +//! templates of the metadata templates folder and shows that folder. use serde_json::{Value, json}; use vectorcraft_doc::CopyrightStatus; @@ -11,13 +15,25 @@ use vectorcraft_doc::metadata::MAX_RATING; use super::document_setup::{LABEL, choice}; use super::{DialogSpec, form}; +use crate::picks::PickRequest; use crate::state::Dialog; use crate::theme::Tokens; -use crate::{VectorcraftApp, icons, widgets}; +use crate::{FilePick, VectorcraftApp, icons, widgets}; pub(super) const KIND: &str = "fileInfo"; /// The keyword being typed. const PENDING: &str = "__keyword"; +/// The template waiting for a merge choice: `{path}` or `{name}`. +const IMPORT: &str = "__import"; +/// The merge choice for [`IMPORT`]: `file.info.applyTemplate`'s `mode`. +const IMPORT_MODE: &str = "__importMode"; +/// The templates in the metadata templates folder, listed when the menu opens: `[label, file]` +/// pairs, the label being the name, or the file name where two templates share a name. +const TEMPLATES: &str = "__templates"; +/// The merge choices, as `file.info.applyTemplate` names them. +const MODES: [&str; 3] = ["replace", "keep", "append"]; +/// The extension of a metadata template file. +const XMP_EXT: &str = "xmp"; /// Width of the text fields. const FIELD: f32 = 320.0; @@ -60,8 +76,177 @@ fn add_keywords(d: &mut Dialog) { d.fields.insert(PENDING.into(), json!("")); } -fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// What the templates menu asked for, done once the menu is drawn. +enum Act { + Save, + Import, + Template(String), + Folder, +} + +/// A file dialog for metadata templates. +fn xmp_pick() -> FilePick { + FilePick { filters: vec![FilePick::filter("XMP metadata templates", &[XMP_EXT])], ..Default::default() } +} + +/// The ≡ templates menu at the top right, and the merge choice for a template it picked. +fn templates_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); + let can_save = crate::picks::can(app, &PickRequest::Save(xmp_pick())); + let can_open = crate::picks::can(app, &PickRequest::Open(xmp_pick())); + let mut act = None; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (rect, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); + let resp = ui.interact(rect, ui.scope_id().with("file-info-templates"), egui::Sense::click()); + icons::paint(ui, "menu", rect.shrink(1.0), if resp.hovered() { t.text_strong } else { t.text_dim }); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Templates"))); + let resp = resp.on_hover_text(tl!("Templates")); + if resp.clicked() { + // Listed once as the menu opens, not on every frame it shows. + let listed = app.session.execute("file.info.templates", &json!({})).map(|r| r["templates"].clone()).unwrap_or_default(); + let listed: Vec<(&str, &str)> = + listed.as_array().into_iter().flatten().filter_map(|t| Some((t.get("name")?.as_str()?, t.get("file")?.as_str()?))).collect(); + let entries: Vec = listed + .iter() + .map(|&(name, file)| { + let shared = listed.iter().filter(|(n, _)| *n == name).count() > 1; + json!([if shared { file } else { name }, file]) + }) + .collect(); + d.fields.insert(TEMPLATES.into(), json!(entries)); + } + egui::Popup::menu(&resp).show(|ui| { + ui.set_min_width(220.0); + if can_save && widgets::menu_item(ui, tl!("Save Metadata Template…"), true, false) { + act = Some(Act::Save); + } + if can_open && widgets::menu_item(ui, tl!("Import…"), true, false) { + act = Some(Act::Import); + } + let entries: Vec<(String, String)> = d + .fields + .get(TEMPLATES) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|e| Some((e.get(0)?.as_str()?.to_string(), e.get(1)?.as_str()?.to_string()))) + .collect(); + if !entries.is_empty() { + ui.separator(); + widgets::menu_scroll(ui, |ui| { + for (label, file) in entries { + if widgets::menu_item_name(ui, &label, true, false) { + act = Some(Act::Template(file)); + } + } + }); + } + ui.separator(); + if widgets::menu_item(ui, tl!("Templates Folder"), true, false) { + act = Some(Act::Folder); + } + }); + }) + }); + let r = match act { + None => Ok(()), + // The file dialogs, shown off the UI thread, act on the dialog as it is then. + Some(Act::Save) => crate::picks::in_dialog(app, d, save_template), + Some(Act::Import) => crate::picks::in_dialog(app, d, pick_template), + // `file.info.applyTemplate` takes a listed template's file name as its `name`. + Some(Act::Template(file)) => { + d.fields.insert(IMPORT.into(), json!({ "name": file })); + Ok(()) + } + Some(Act::Folder) => show_folder(app), + }; + if let Err(e) = r { + app.status(e); + } + import_options(app, ui, d); +} + +/// Save Metadata Template…: the fields as they are in the dialog, to a file picked in a save +/// dialog that starts in the metadata templates folder. +fn save_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let mut d2 = d.clone(); + add_keywords(&mut d2); + let folder = app.session.execute("file.info.templates", &json!({ "create": true })).ok().and_then(|r| r["folder"].as_str().map(str::to_string)); + let name = format!("{}.{XMP_EXT}", d2.str("title").trim()); + let pick = FilePick { name, folder, ..xmp_pick() }; + // None: canceled, or the dialog is still open off the UI thread and runs this again. + let Some(path) = crate::picks::save(app, &pick) else { return Ok(()) }; + app.run("file.info.saveTemplate", json!({ "path": path, "fields": form::params(&d2) })).map(|_| ()) +} + +/// Import…: a template picked in an open dialog waits for its merge choice. +fn pick_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + // None: canceled, or the dialog is still open off the UI thread and runs this again. + let Some(path) = crate::picks::open(app, &xmp_pick()) else { return Ok(()) }; + d.fields.insert(IMPORT.into(), json!({ "path": path })); + Ok(()) +} + +/// Templates Folder: the metadata templates folder (made when it is missing) in the file manager. +fn show_folder(app: &mut VectorcraftApp) -> Result<(), String> { + let r = app.session.execute("file.info.templates", &json!({ "create": true })).map_err(|e| e.to_string())?; + let folder = r["folder"].as_str().ok_or("no metadata templates folder here")?.to_string(); + crate::io::open_in_app(app, &folder) +} + +/// The merge choice for the template [`IMPORT`] names: OK merges it into the dialog's fields +/// (nothing changes in the document until the dialog's own OK), Cancel drops it. +fn import_options(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { + let Some(source) = d.fields.get(IMPORT).and_then(Value::as_object).cloned() else { return }; + widgets::subheader(ui, tl!("Import Options")); + let mode = d.fields.get(IMPORT_MODE).and_then(Value::as_str).filter(|m| MODES.contains(m)).unwrap_or("keep").to_string(); + let labels = [ + tl!("Clear existing fields and use the template's"), + tl!("Keep existing fields, but replace those the template has"), + tl!("Keep existing fields, but append those the template has"), + ]; + for (value, label) in MODES.into_iter().zip(labels) { + if widgets::radio(ui, label, mode == value, true) { + d.fields.insert(IMPORT_MODE.into(), json!(value)); + } + } + let mut ok = false; + let mut cancel = false; + ui.horizontal(|ui| { + ok = widgets::flat_button(ui, tl!("OK"), 64.0).clicked(); + cancel = widgets::flat_button(ui, tl!("Cancel"), 64.0).clicked(); + }); + ui.add_space(10.0); + if ok { + if let Err(e) = import(app, d, source, &mode) { + app.status(e); + } + } else if cancel { + d.fields.remove(IMPORT); + } +} + +/// Merge the template `source` names into the dialog's fields as `mode` says. +fn import(app: &mut VectorcraftApp, d: &mut Dialog, source: serde_json::Map, mode: &str) -> Result<(), String> { + let mut p = Value::Object(source); + p["mode"] = json!(mode); + p["apply"] = json!(false); + let mut d2 = d.clone(); + add_keywords(&mut d2); + p["base"] = form::params(&d2); + let merged = app.session.execute("file.info.applyTemplate", &p).map_err(|e| e.to_string())?; + for (k, v) in merged.as_object().into_iter().flatten() { + d.fields.insert(k.clone(), v.clone()); + } + d.fields.insert(PENDING.into(), json!("")); + d.fields.remove(IMPORT); + Ok(()) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + templates_menu(app, ui, d); for (key, label) in [("title", tl!("Document Title:")), ("author", tl!("Author:")), ("authorTitle", tl!("Author Title:"))] { widgets::label_row(ui, label, LABEL, |ui| { form::text(ui, d, key, FIELD); @@ -233,4 +418,35 @@ mod tests { assert!(crate::dialogs::confirm(&mut app).is_err()); assert!(app.ui.dialog.is_some()); } + + #[test] + fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info.saveTemplate", json!({"name": "Studio", "fields": {"author": "Grace", "keywords": ["print"], "rating": 3}})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("author".into(), json!("Ada")); + d.fields.insert(super::PENDING.into(), json!("fair")); + // A listed template waits for its merge choice; the choice draws. + d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"})); + d.fields.insert(super::IMPORT_MODE.into(), json!("append")); + frame(&mut app); + let mut d = app.ui.dialog.clone().unwrap(); + super::import(&mut app, &mut d, json!({"name": "Studio"}).as_object().unwrap().clone(), "append").unwrap(); + assert!(!d.fields.contains_key(super::IMPORT)); + // Appended: the typed author stays, the typed keyword is kept and the template's added. + assert_eq!( + (d.fields["author"].clone(), d.fields["keywords"].clone(), d.fields["rating"].clone()), + (json!("Ada"), json!(["fair", "print"]), json!(3)) + ); + assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "nothing changes before OK"); + app.ui.dialog = Some(d); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.metadata.author.as_str(), st.doc.metadata.rating), ("Ada", 3)); + assert_eq!(st.history.undo.len(), 1); + } } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 948b295e17..ca90b18905 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -638,6 +638,11 @@ font-technology Variable Променливи Copy Width Point Копиране на точка на ширина Copyright Авторско право Copyright Info URL: URL адрес с информация за авторското право: + Save Metadata Template… Запази шаблон за метаданни… + Import Options Опции за импортиране + Clear existing fields and use the template's Изчисти съществуващите полета и използвай тези от шаблона + Keep existing fields, but replace those the template has Запази съществуващите полета, но замени съдържащите се в шаблона + Keep existing fields, but append those the template has Запази съществуващите полета, но добави съдържащите се в шаблона Copyright Notice: Бележка за авторското право: Copyright Status: Статус на авторското право: Copyright Symbol Символ за авторско право diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f8d6fa263b..2fae16d0e4 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2545,6 +2545,11 @@ digits Malayalam Malajalam Author Title: Titula autora: Author: Autor: Copyright Info URL: URL informacija o autorskim pravima: + Save Metadata Template… Sačuvaj predložak metapodataka… + Import Options Opcije uvoza + Clear existing fields and use the template's Obriši postojeća polja i koristi polja iz predloška + Keep existing fields, but replace those the template has Zadrži postojeća polja, ali zamijeni ona koja predložak sadrži + Keep existing fields, but append those the template has Zadrži postojeća polja, ali dodaj ona koja predložak sadrži Copyright Notice: Obavještenje o autorskim pravima: Copyright Status: Status autorskih prava: Created: Kreirano: diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3ed3ca8331..2102e1976c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -940,6 +940,18 @@ antiAlias Sharp Nítid Copyright Copyright Copyright and Contact Info Informació de copyright i de contacte Copyright Info URL: URL de la informació de copyright: + Save Metadata Template… Desa la plantilla de metadades… + Import Options Opcions d’importació + Clear existing fields and use the template's Esborra els camps existents i fes servir els de la plantilla + Keep existing fields, but replace those the template has Conserva els camps existents, però substitueix els que tingui la plantilla + Keep existing fields, but append those the template has Conserva els camps existents, però afegeix els que tingui la plantilla +@msg the template name can't be empty el nom de la plantilla no pot estar buit +@msg the template name isn't usable as a file name el nom de la plantilla no es pot fer servir com a nom de fitxer +@msg no metadata templates folder here aquí no hi ha cap carpeta de plantilles de metadades +@msg give `name` or `path`, not both indiqueu `name` o `path`, no tots dos +@msg give one of `path`, `name` and `data` indiqueu un de `path`, `name` i `data` +@msg mode must be replace, keep or append el mode ha de ser replace, keep o append +@msg the file is not an XMP metadata template el fitxer no és una plantilla de metadades XMP Copyright Notice: Avís de copyright: Copyright Status: Estat del copyright: Copyright Symbol Símbol de copyright diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 161e235c56..0edf8255a0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2578,6 +2578,18 @@ digits Malayalam Malajálamské Author Title: Funkce autora: Author: Autor: Copyright Info URL: URL informací o autorských právech: + Save Metadata Template… Uložit šablonu metadat… + Import Options Možnosti importu + Clear existing fields and use the template's Vymazat stávající pole a použít pole ze šablony + Keep existing fields, but replace those the template has Zachovat stávající pole, ale nahradit ta, která šablona obsahuje + Keep existing fields, but append those the template has Zachovat stávající pole, ale připojit ta, která šablona obsahuje +@msg the template name can't be empty název šablony nesmí být prázdný +@msg the template name isn't usable as a file name název šablony nelze použít jako název souboru +@msg no metadata templates folder here zde není žádná složka šablon metadat +@msg give `name` or `path`, not both zadejte `name` nebo `path`, ne obojí +@msg give one of `path`, `name` and `data` zadejte jeden z parametrů `path`, `name` a `data` +@msg mode must be replace, keep or append režim musí být replace, keep nebo append +@msg the file is not an XMP metadata template soubor není šablona metadat XMP Copyright Notice: Upozornění o autorských právech: Copyright Status: Stav autorských práv: Created: Vytvořeno: diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fd0b7c042e..25c6eb9e14 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2980,6 +2980,18 @@ digits Malayalam Malayalam Author Title: Forfattertitel: Author: Forfatter: Copyright Info URL: URL til ophavsretinfo: + Save Metadata Template… Gem metadataskabelon… + Import Options Importindstillinger + Clear existing fields and use the template's Ryd eksisterende felter, og brug skabelonens + Keep existing fields, but replace those the template has Behold eksisterende felter, men erstat dem, skabelonen har + Keep existing fields, but append those the template has Behold eksisterende felter, men tilføj dem, skabelonen har +@msg the template name can't be empty skabelonnavnet må ikke være tomt +@msg the template name isn't usable as a file name skabelonnavnet kan ikke bruges som filnavn +@msg no metadata templates folder here der er ingen mappe til metadataskabeloner her +@msg give `name` or `path`, not both angiv `name` eller `path`, ikke begge +@msg give one of `path`, `name` and `data` angiv én af `path`, `name` og `data` +@msg mode must be replace, keep or append tilstanden skal være replace, keep eller append +@msg the file is not an XMP metadata template filen er ikke en XMP-metadataskabelon Copyright Notice: Ophavsretserklæring: Copyright Status: Ophavsretstatus: Created: Oprettet: diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a5f32a5d9..5e7442760e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -631,6 +631,18 @@ font-technology Variable Variabel Copy Width Point Breitenpunkt kopieren Copyright Copyright Copyright Info URL: URL für Copyright-Informationen: + Save Metadata Template… Metadatenvorlage speichern… + Import Options Importoptionen + Clear existing fields and use the template's Vorhandene Felder löschen und die der Vorlage verwenden + Keep existing fields, but replace those the template has Vorhandene Felder beibehalten, aber die in der Vorlage enthaltenen ersetzen + Keep existing fields, but append those the template has Vorhandene Felder beibehalten, aber die in der Vorlage enthaltenen anfügen +@msg the template name can't be empty der Vorlagenname darf nicht leer sein +@msg the template name isn't usable as a file name der Vorlagenname ist als Dateiname nicht verwendbar +@msg no metadata templates folder here hier gibt es keinen Ordner für Metadatenvorlagen +@msg give `name` or `path`, not both geben Sie `name` oder `path` an, nicht beides +@msg give one of `path`, `name` and `data` geben Sie einen der Parameter `path`, `name` und `data` an +@msg mode must be replace, keep or append der Modus muss replace, keep oder append sein +@msg the file is not an XMP metadata template die Datei ist keine XMP-Metadatenvorlage Copyright Notice: Copyright-Vermerk: Copyright Status: Copyright-Status: Copyright Symbol Copyright-Symbol diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b1b7b4d039..4363a45256 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -612,6 +612,18 @@ font-technology Variable Μεταβλητές Copy Width Point Αντιγραφή σημείου πλάτους Copyright Πνευματικά δικαιώματα Copyright Info URL: URL πληροφοριών πνευματικών δικαιωμάτων: + Save Metadata Template… Αποθήκευση προτύπου μεταδεδομένων… + Import Options Επιλογές εισαγωγής + Clear existing fields and use the template's Απαλοιφή των υπαρχόντων πεδίων και χρήση εκείνων του προτύπου + Keep existing fields, but replace those the template has Διατήρηση των υπαρχόντων πεδίων, αλλά αντικατάσταση όσων έχει το πρότυπο + Keep existing fields, but append those the template has Διατήρηση των υπαρχόντων πεδίων, αλλά προσθήκη όσων έχει το πρότυπο +@msg the template name can't be empty το όνομα του προτύπου δεν μπορεί να είναι κενό +@msg the template name isn't usable as a file name το όνομα του προτύπου δεν μπορεί να χρησιμοποιηθεί ως όνομα αρχείου +@msg no metadata templates folder here δεν υπάρχει φάκελος προτύπων μεταδεδομένων εδώ +@msg give `name` or `path`, not both δώστε `name` ή `path`, όχι και τα δύο +@msg give one of `path`, `name` and `data` δώστε ένα από τα `path`, `name` και `data` +@msg mode must be replace, keep or append η λειτουργία πρέπει να είναι replace, keep ή append +@msg the file is not an XMP metadata template το αρχείο δεν είναι πρότυπο μεταδεδομένων XMP Copyright Notice: Σημείωση πνευματικών δικαιωμάτων: Copyright Status: Κατάσταση πνευματικών δικαιωμάτων: Copyright Symbol Σύμβολο πνευματικών δικαιωμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b3c675f7b..80635429ce 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -653,6 +653,18 @@ font-technology Variable Variables Copy Width Point Copiar punto de anchura Copyright Copyright Copyright Info URL: URL de información de copyright: + Save Metadata Template… Guardar plantilla de metadatos… + Import Options Opciones de importación + Clear existing fields and use the template's Borrar los campos existentes y usar los de la plantilla + Keep existing fields, but replace those the template has Conservar los campos existentes, pero reemplazar los que tenga la plantilla + Keep existing fields, but append those the template has Conservar los campos existentes, pero añadir los que tenga la plantilla +@msg the template name can't be empty el nombre de la plantilla no puede estar vacío +@msg the template name isn't usable as a file name el nombre de la plantilla no se puede usar como nombre de archivo +@msg no metadata templates folder here aquí no hay ninguna carpeta de plantillas de metadatos +@msg give `name` or `path`, not both indique `name` o `path`, no ambos +@msg give one of `path`, `name` and `data` indique uno de `path`, `name` y `data` +@msg mode must be replace, keep or append el modo debe ser replace, keep o append +@msg the file is not an XMP metadata template el archivo no es una plantilla de metadatos XMP Copyright Notice: Aviso de copyright: Copyright Status: Estado de copyright: Copyright Symbol Símbolo de copyright diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e77a617c52..774450ba6a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2533,6 +2533,18 @@ digits Malayalam Malajalam Author Title: Tekijän titteli: Author: Tekijä: Copyright Info URL: Tekijänoikeustietojen URL: + Save Metadata Template… Tallenna metatietomallipohja… + Import Options Tuontiasetukset + Clear existing fields and use the template's Tyhjennä nykyiset kentät ja käytä mallipohjan kenttiä + Keep existing fields, but replace those the template has Säilytä nykyiset kentät, mutta korvaa mallipohjassa olevat + Keep existing fields, but append those the template has Säilytä nykyiset kentät, mutta lisää mallipohjassa olevat +@msg the template name can't be empty mallipohjan nimi ei voi olla tyhjä +@msg the template name isn't usable as a file name mallipohjan nimeä ei voi käyttää tiedostonimenä +@msg no metadata templates folder here täällä ei ole metatietomallipohjien kansiota +@msg give `name` or `path`, not both anna `name` tai `path`, ei molempia +@msg give one of `path`, `name` and `data` anna yksi seuraavista: `path`, `name` ja `data` +@msg mode must be replace, keep or append tilan on oltava replace, keep tai append +@msg the file is not an XMP metadata template tiedosto ei ole XMP-metatietomallipohja Copyright Notice: Tekijänoikeusilmoitus: Copyright Status: Tekijänoikeuden tila: Created: Luotu: diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2762d2a954..d7d7e545e6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -653,6 +653,18 @@ font-technology Variable Variables Copy to User Defined Copier dans Défini par l’utilisateur Copy Width Point Copier le point de largeur Copyright Copyright + Save Metadata Template… Enregistrer le modèle de métadonnées… + Import Options Options d’importation + Clear existing fields and use the template's Effacer les champs existants et utiliser ceux du modèle + Keep existing fields, but replace those the template has Conserver les champs existants, mais remplacer ceux que contient le modèle + Keep existing fields, but append those the template has Conserver les champs existants, mais ajouter ceux que contient le modèle +@msg the template name can't be empty le nom du modèle ne peut pas être vide +@msg the template name isn't usable as a file name le nom du modèle n'est pas utilisable comme nom de fichier +@msg no metadata templates folder here aucun dossier de modèles de métadonnées ici +@msg give `name` or `path`, not both indiquez `name` ou `path`, pas les deux +@msg give one of `path`, `name` and `data` indiquez un seul des paramètres `path`, `name` et `data` +@msg mode must be replace, keep or append le mode doit être replace, keep ou append +@msg the file is not an XMP metadata template le fichier n’est pas un modèle de métadonnées XMP Copyright Info URL: URL des informations de copyright : Copyright Notice: Mention de copyright : Copyright Status: État du copyright : diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c96900b2b..c3355206fa 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -755,6 +755,12 @@ Copy to User Defined વપરાશકર્તા-વ્યાખ્યાયિતમાં નકલ કરો Copyright કૉપીરાઇટ Copyright Info URL: કૉપીરાઇટ માહિતી URL: + Templates ટેમ્પલેટ + Save Metadata Template… મેટાડેટા ટેમ્પલેટ સાચવો… + Import Options આયાત વિકલ્પો + Clear existing fields and use the template's હાલના ફીલ્ડ સાફ કરો અને ટેમ્પલેટના ફીલ્ડ વાપરો + Keep existing fields, but replace those the template has હાલના ફીલ્ડ રાખો, પણ ટેમ્પલેટમાં હોય તે બદલો + Keep existing fields, but append those the template has હાલના ફીલ્ડ રાખો, પણ ટેમ્પલેટમાં હોય તે ઉમેરો Copyright Notice: કૉપીરાઇટ સૂચના: Copyright Status: કૉપીરાઇટ સ્થિતિ: Copyright Symbol કૉપીરાઇટ ચિહ્ન diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 548f961f51..d80993bad8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1078,6 +1078,18 @@ antiAlias Sharp शार्प Copyright कॉपीराइट Copyright and Contact Info कॉपीराइट और संपर्क जानकारी Copyright Info URL: कॉपीराइट जानकारी URL: + Save Metadata Template… मेटाडेटा टेम्पलेट सेव करें… + Import Options इम्पोर्ट विकल्प + Clear existing fields and use the template's मौजूदा फ़ील्ड साफ़ करें और टेम्पलेट के फ़ील्ड उपयोग करें + Keep existing fields, but replace those the template has मौजूदा फ़ील्ड रखें, लेकिन टेम्पलेट में मौजूद फ़ील्ड बदलें + Keep existing fields, but append those the template has मौजूदा फ़ील्ड रखें, लेकिन टेम्पलेट में मौजूद फ़ील्ड जोड़ें +@msg the template name can't be empty टेम्पलेट का नाम खाली नहीं हो सकता +@msg the template name isn't usable as a file name टेम्पलेट का नाम फ़ाइल नाम के रूप में उपयोग नहीं किया जा सकता +@msg no metadata templates folder here यहाँ कोई मेटाडेटा टेम्पलेट फ़ोल्डर नहीं है +@msg give `name` or `path`, not both `name` या `path` दें, दोनों नहीं +@msg give one of `path`, `name` and `data` `path`, `name` और `data` में से एक दें +@msg mode must be replace, keep or append मोड replace, keep या append होना चाहिए +@msg the file is not an XMP metadata template फ़ाइल XMP मेटाडेटा टेम्पलेट नहीं है Copyright Notice: कॉपीराइट सूचना: Copyright Status: कॉपीराइट स्थिति: Copyright Symbol कॉपीराइट सिंबल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 200b45d1b1..f1cd6bd499 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -847,6 +847,18 @@ font-technology Variable Változó Copyright Szerzői jog Copyright and Contact Info Szerzői jogi és kapcsolati adatok Copyright Info URL: Szerzői jogi információ URL-je: + Save Metadata Template… Metaadatsablon mentése… + Import Options Importálási beállítások + Clear existing fields and use the template's Meglévő mezők törlése és a sablon mezőinek használata + Keep existing fields, but replace those the template has Meglévő mezők megtartása, de a sablonban szereplők cseréje + Keep existing fields, but append those the template has Meglévő mezők megtartása, de a sablonban szereplők hozzáfűzése +@msg the template name can't be empty a sablon neve nem lehet üres +@msg the template name isn't usable as a file name a sablon neve nem használható fájlnévként +@msg no metadata templates folder here itt nincs metaadatsablon-mappa +@msg give `name` or `path`, not both adja meg a `name` vagy a `path` paramétert, de ne mindkettőt +@msg give one of `path`, `name` and `data` adja meg a `path`, a `name` és a `data` paraméterek egyikét +@msg mode must be replace, keep or append a mód értéke replace, keep vagy append lehet +@msg the file is not an XMP metadata template a fájl nem XMP-metaadatsablon Copyright Notice: Szerzői jogi közlemény: Copyright Status: Szerzői jogi állapot: Copyright Symbol Szerzői jogi jel diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f3dcca3874..1ed935c31d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2371,6 +2371,11 @@ digits Malayalam Malayalam Author Title: Judul penulis: Author: Penulis: Copyright Info URL: URL info hak cipta: + Save Metadata Template… Simpan templat metadata… + Import Options Opsi impor + Clear existing fields and use the template's Hapus bidang yang ada dan gunakan bidang templat + Keep existing fields, but replace those the template has Pertahankan bidang yang ada, tetapi ganti bidang yang dimiliki templat + Keep existing fields, but append those the template has Pertahankan bidang yang ada, tetapi tambahkan bidang yang dimiliki templat Copyright Notice: Pemberitahuan hak cipta: Copyright Status: Status hak cipta: Created: Dibuat: diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 90ec79404c..a020d1635d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -653,6 +653,18 @@ font-technology Variable Variabili Copy Width Point Copia punto di larghezza Copyright Copyright Copyright Info URL: URL informazioni copyright: + Save Metadata Template… Salva modello di metadati… + Import Options Opzioni di importazione + Clear existing fields and use the template's Cancella i campi esistenti e usa quelli del modello + Keep existing fields, but replace those the template has Mantieni i campi esistenti, ma sostituisci quelli presenti nel modello + Keep existing fields, but append those the template has Mantieni i campi esistenti, ma aggiungi quelli presenti nel modello +@msg the template name can't be empty il nome del modello non può essere vuoto +@msg the template name isn't usable as a file name il nome del modello non è utilizzabile come nome di file +@msg no metadata templates folder here qui non c'è una cartella dei modelli di metadati +@msg give `name` or `path`, not both indica `name` o `path`, non entrambi +@msg give one of `path`, `name` and `data` indica uno tra `path`, `name` e `data` +@msg mode must be replace, keep or append la modalità deve essere replace, keep o append +@msg the file is not an XMP metadata template il file non è un modello di metadati XMP Copyright Notice: Nota sul copyright: Copyright Status: Stato copyright: Copyright Symbol Simbolo di copyright diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d98acfa22d..cf4297434f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1382,6 +1382,18 @@ antiAlias Sharp シャープ Copy Width Point 幅ポイントをコピー Copyright 著作権 Copyright Info URL: 著作権情報の URL: + Save Metadata Template… メタデータテンプレートを保存… + Import Options 読み込みオプション + Clear existing fields and use the template's 既存のフィールドを消去してテンプレートのフィールドを使用 + Keep existing fields, but replace those the template has 既存のフィールドを保持し、テンプレートにあるフィールドを置換 + Keep existing fields, but append those the template has 既存のフィールドを保持し、テンプレートにあるフィールドを追加 +@msg the template name can't be empty テンプレート名は空にできません +@msg the template name isn't usable as a file name テンプレート名はファイル名として使用できません +@msg no metadata templates folder here ここにはメタデータテンプレートのフォルダーがありません +@msg give `name` or `path`, not both `name` と `path` のどちらか一方を指定してください +@msg give one of `path`, `name` and `data` `path`、`name`、`data` のいずれか 1 つを指定してください +@msg mode must be replace, keep or append モードは replace、keep、append のいずれかにしてください +@msg the file is not an XMP metadata template このファイルは XMP メタデータテンプレートではありません Copyright Notice: 著作権表示: Copyright Status: 著作権の状態: Corner Point Angle Threshold: コーナーポイントの角度のしきい値: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 794e5454a9..9d7e57b789 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2297,6 +2297,18 @@ digits Malayalam მალაიალამური Author Title: ავტორის თანამდებობა: Author: ავტორი: Copyright Info URL: საავტორო უფლების ინფორმაციის URL: + Save Metadata Template… მეტამონაცემების შაბლონის შენახვა… + Import Options იმპორტის პარამეტრები + Clear existing fields and use the template's არსებული ველების გასუფთავება და შაბლონის ველების გამოყენება + Keep existing fields, but replace those the template has არსებული ველების შენარჩუნება, მაგრამ შაბლონში არსებულების ჩანაცვლება + Keep existing fields, but append those the template has არსებული ველების შენარჩუნება, მაგრამ შაბლონში არსებულების დამატება +@msg the template name can't be empty შაბლონის სახელი ცარიელი ვერ იქნება +@msg the template name isn't usable as a file name შაბლონის სახელი ფაილის სახელად ვერ გამოდგება +@msg no metadata templates folder here აქ მეტამონაცემების შაბლონების საქაღალდე არ არის +@msg give `name` or `path`, not both მიუთითეთ `name` ან `path`, არა ორივე +@msg give one of `path`, `name` and `data` მიუთითეთ ერთ-ერთი: `path`, `name` და `data` +@msg mode must be replace, keep or append რეჟიმი უნდა იყოს replace, keep ან append +@msg the file is not an XMP metadata template ფაილი არ არის XMP მეტამონაცემების შაბლონი Copyright Notice: საავტორო უფლების შენიშვნა: Copyright Status: საავტორო უფლების სტატუსი: Created: შექმნილია: diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bb8676df71..01e2d89618 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1372,6 +1372,18 @@ antiAlias Sharp 날카롭게 Copy Width Point 너비 점 복사 Copyright 저작권 Copyright Info URL: 저작권 정보 URL: + Save Metadata Template… 메타데이터 템플릿 저장… + Import Options 가져오기 옵션 + Clear existing fields and use the template's 기존 필드를 지우고 템플릿의 필드 사용 + Keep existing fields, but replace those the template has 기존 필드를 유지하되 템플릿에 있는 필드 바꾸기 + Keep existing fields, but append those the template has 기존 필드를 유지하되 템플릿에 있는 필드 추가 +@msg the template name can't be empty 템플릿 이름은 비워 둘 수 없습니다 +@msg the template name isn't usable as a file name 템플릿 이름은 파일 이름으로 사용할 수 없습니다 +@msg no metadata templates folder here 여기에는 메타데이터 템플릿 폴더가 없습니다 +@msg give `name` or `path`, not both `name` 또는 `path` 중 하나만 지정하세요 +@msg give one of `path`, `name` and `data` `path`, `name`, `data` 중 하나를 지정하세요 +@msg mode must be replace, keep or append 모드는 replace, keep 또는 append여야 합니다 +@msg the file is not an XMP metadata template 파일이 XMP 메타데이터 템플릿이 아닙니다 Copyright Notice: 저작권 고지: Copyright Status: 저작권 상태: Corner Point Angle Threshold: 모퉁이 포인트 각도 임계값: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a597a03fd0..4ca2b8445d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2889,6 +2889,18 @@ digits Malayalam Malayalam Author Title: Auteurstitel: Author: Auteur: Copyright Info URL: URL voor copyrightinfo: + Save Metadata Template… Metagegevenssjabloon opslaan… + Import Options Importopties + Clear existing fields and use the template's Bestaande velden wissen en die van het sjabloon gebruiken + Keep existing fields, but replace those the template has Bestaande velden behouden, maar die in het sjabloon vervangen + Keep existing fields, but append those the template has Bestaande velden behouden, maar die in het sjabloon toevoegen +@msg the template name can't be empty de sjabloonnaam mag niet leeg zijn +@msg the template name isn't usable as a file name de sjabloonnaam is niet bruikbaar als bestandsnaam +@msg no metadata templates folder here hier is geen map voor metagegevenssjablonen +@msg give `name` or `path`, not both geef `name` of `path` op, niet allebei +@msg give one of `path`, `name` and `data` geef één van `path`, `name` en `data` op +@msg mode must be replace, keep or append de modus moet replace, keep of append zijn +@msg the file is not an XMP metadata template het bestand is geen XMP-metagegevenssjabloon Copyright Notice: Copyrightvermelding: Copyright Status: Copyrightstatus: Created: Aangemaakt: diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 99ee2080b8..1633bb57a0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2493,6 +2493,18 @@ digits Malayalam Malajalam Author Title: Stanowisko autora: Author: Autor: Copyright Info URL: URL informacji o prawach autorskich: + Save Metadata Template… Zapisz szablon metadanych… + Import Options Opcje importu + Clear existing fields and use the template's Wyczyść istniejące pola i użyj pól z szablonu + Keep existing fields, but replace those the template has Zachowaj istniejące pola, ale zastąp te, które zawiera szablon + Keep existing fields, but append those the template has Zachowaj istniejące pola, ale dołącz te, które zawiera szablon +@msg the template name can't be empty nazwa szablonu nie może być pusta +@msg the template name isn't usable as a file name nazwy szablonu nie można użyć jako nazwy pliku +@msg no metadata templates folder here brak tu folderu szablonów metadanych +@msg give `name` or `path`, not both podaj `name` albo `path`, nie oba +@msg give one of `path`, `name` and `data` podaj jeden z parametrów `path`, `name` i `data` +@msg mode must be replace, keep or append tryb musi mieć wartość replace, keep lub append +@msg the file is not an XMP metadata template plik nie jest szablonem metadanych XMP Copyright Notice: Informacja o prawach autorskich: Copyright Status: Status praw autorskich: Created: Utworzono: diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 677c8e460f..3996e74b18 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -589,6 +589,18 @@ antiAlias Sharp Nítido Copy to User Defined Copiar para Definido pelo Usuário Copyright Direitos Autorais Copyright Info URL: URL de Informações de Direitos Autorais: + Save Metadata Template… Salvar Modelo de Metadados… + Import Options Opções de Importação + Clear existing fields and use the template's Limpar os campos existentes e usar os do modelo + Keep existing fields, but replace those the template has Manter os campos existentes, mas substituir os que o modelo tiver + Keep existing fields, but append those the template has Manter os campos existentes, mas acrescentar os que o modelo tiver +@msg the template name can't be empty o nome do modelo não pode ficar vazio +@msg the template name isn't usable as a file name o nome do modelo não pode ser usado como nome de arquivo +@msg no metadata templates folder here não há pasta de modelos de metadados aqui +@msg give `name` or `path`, not both informe `name` ou `path`, não ambos +@msg give one of `path`, `name` and `data` informe um de `path`, `name` e `data` +@msg mode must be replace, keep or append o modo deve ser replace, keep ou append +@msg the file is not an XMP metadata template o arquivo não é um modelo de metadados XMP Copyright Notice: Aviso de Direitos Autorais: Copyright Status: Status de Direitos Autorais: Copyright Symbol Símbolo de Direitos Autorais diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 106343cddd..df6d68fc11 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -651,6 +651,18 @@ font-technology Variable Вариативные Copy Width Point Копировать точку ширины Copyright Copyright Copyright Info URL: URL информации об авторских правах: + Save Metadata Template… Сохранить шаблон метаданных… + Import Options Параметры импорта + Clear existing fields and use the template's Очистить существующие поля и использовать поля шаблона + Keep existing fields, but replace those the template has Сохранить существующие поля, но заменить те, что есть в шаблоне + Keep existing fields, but append those the template has Сохранить существующие поля, но добавить те, что есть в шаблоне +@msg the template name can't be empty имя шаблона не может быть пустым +@msg the template name isn't usable as a file name имя шаблона нельзя использовать как имя файла +@msg no metadata templates folder here здесь нет папки шаблонов метаданных +@msg give `name` or `path`, not both укажите `name` или `path`, но не оба +@msg give one of `path`, `name` and `data` укажите один из параметров `path`, `name` и `data` +@msg mode must be replace, keep or append режим должен быть replace, keep или append +@msg the file is not an XMP metadata template файл не является шаблоном метаданных XMP Copyright Notice: Уведомление об авторских правах: Copyright Status: Статус авторских прав: Copyright Symbol Символ авторского права diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cc854aa362..339256c74d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -640,6 +640,18 @@ font-technology Variable Variabla Copy Width Point Kopiera breddpunkt Copyright Upphovsrätt Copyright Info URL: URL för upphovsrättsinformation: + Save Metadata Template… Spara metadatamall… + Import Options Importalternativ + Clear existing fields and use the template's Rensa befintliga fält och använd mallens + Keep existing fields, but replace those the template has Behåll befintliga fält, men ersätt dem som mallen har + Keep existing fields, but append those the template has Behåll befintliga fält, men lägg till dem som mallen har +@msg the template name can't be empty mallnamnet får inte vara tomt +@msg the template name isn't usable as a file name mallnamnet kan inte användas som filnamn +@msg no metadata templates folder here det finns ingen mapp för metadatamallar här +@msg give `name` or `path`, not both ange `name` eller `path`, inte båda +@msg give one of `path`, `name` and `data` ange en av `path`, `name` och `data` +@msg mode must be replace, keep or append läget måste vara replace, keep eller append +@msg the file is not an XMP metadata template filen är inte en XMP-metadatamall Copyright Notice: Upphovsrättsmeddelande: Copyright Status: Upphovsrättsstatus: Copyright Symbol Upphovsrättssymbol diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2888a30f0..c8cdf2ff58 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -632,6 +632,18 @@ font-technology Variable Değişken Copy Width Point Genişlik Noktasını Kopyala Copyright Telif hakkı Copyright Info URL: Telif Hakkı Bilgisi URL'si: + Save Metadata Template… Meta Veri Şablonunu Kaydet… + Import Options İçe Aktarma Seçenekleri + Clear existing fields and use the template's Mevcut alanları temizle ve şablonunkileri kullan + Keep existing fields, but replace those the template has Mevcut alanları koru, ancak şablonda olanları değiştir + Keep existing fields, but append those the template has Mevcut alanları koru, ancak şablonda olanları ekle +@msg the template name can't be empty şablon adı boş olamaz +@msg the template name isn't usable as a file name şablon adı dosya adı olarak kullanılamaz +@msg no metadata templates folder here burada meta veri şablonları klasörü yok +@msg give `name` or `path`, not both `name` veya `path` verin, ikisini birden değil +@msg give one of `path`, `name` and `data` `path`, `name` ve `data` değerlerinden birini verin +@msg mode must be replace, keep or append mod replace, keep veya append olmalıdır +@msg the file is not an XMP metadata template dosya bir XMP meta veri şablonu değil Copyright Notice: Telif Hakkı Bildirimi: Copyright Status: Telif Hakkı Durumu: Copyright Symbol Telif Hakkı Sembolü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 411b2c3baf..3f1f07cce3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -647,6 +647,18 @@ font-technology Variable Варіативні Copy Width Point Копіювати точку ширини Copyright Авторські права Copyright Info URL: URL інформації про авторські права: + Save Metadata Template… Зберегти шаблон метаданих… + Import Options Параметри імпорту + Clear existing fields and use the template's Очистити наявні поля й використати поля шаблону + Keep existing fields, but replace those the template has Зберегти наявні поля, але замінити ті, що є в шаблоні + Keep existing fields, but append those the template has Зберегти наявні поля, але додати ті, що є в шаблоні +@msg the template name can't be empty назва шаблону не може бути порожньою +@msg the template name isn't usable as a file name назву шаблону не можна використати як назву файлу +@msg no metadata templates folder here тут немає папки шаблонів метаданих +@msg give `name` or `path`, not both укажіть `name` або `path`, але не обидва +@msg give one of `path`, `name` and `data` укажіть один із параметрів `path`, `name` і `data` +@msg mode must be replace, keep or append режим має бути replace, keep або append +@msg the file is not an XMP metadata template файл не є шаблоном метаданих XMP Copyright Notice: Повідомлення про авторські права: Copyright Status: Статус авторських прав: Copyright Symbol Символ авторського права diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1460910197..0e5060caf2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -747,6 +747,18 @@ font-technology Variable Biến thiên Copy Width Point Sao chép điểm chiều rộng Copyright Bản quyền Copyright Info URL: URL thông tin bản quyền: + Save Metadata Template… Lưu mẫu siêu dữ liệu… + Import Options Tùy chọn nhập + Clear existing fields and use the template's Xóa các trường hiện có và dùng các trường của mẫu + Keep existing fields, but replace those the template has Giữ các trường hiện có, nhưng thay thế các trường mà mẫu có + Keep existing fields, but append those the template has Giữ các trường hiện có, nhưng nối thêm các trường mà mẫu có +@msg the template name can't be empty tên mẫu không được để trống +@msg the template name isn't usable as a file name không thể dùng tên mẫu làm tên tệp +@msg no metadata templates folder here không có thư mục mẫu siêu dữ liệu ở đây +@msg give `name` or `path`, not both hãy chỉ định `name` hoặc `path`, không phải cả hai +@msg give one of `path`, `name` and `data` hãy chỉ định một trong `path`, `name` và `data` +@msg mode must be replace, keep or append chế độ phải là replace, keep hoặc append +@msg the file is not an XMP metadata template tệp không phải là mẫu siêu dữ liệu XMP Copyright Notice: Thông báo bản quyền: Copyright Status: Trạng thái bản quyền: Copyright Symbol Ký hiệu bản quyền diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3fe2f9e009..71697093ac 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -598,6 +598,18 @@ antiAlias Sharp 锐利 Copy Width Point 复制宽度点 Copyright 版权 Copyright Info URL: 版权信息 URL: + Save Metadata Template… 存储元数据模板… + Import Options 导入选项 + Clear existing fields and use the template's 清除现有字段并使用模板中的字段 + Keep existing fields, but replace those the template has 保留现有字段,但替换模板中包含的字段 + Keep existing fields, but append those the template has 保留现有字段,但追加模板中包含的字段 +@msg the template name can't be empty 模板名称不能为空 +@msg the template name isn't usable as a file name 模板名称不能用作文件名 +@msg no metadata templates folder here 此处没有元数据模板文件夹 +@msg give `name` or `path`, not both 请提供 `name` 或 `path`,不能同时提供 +@msg give one of `path`, `name` and `data` 请提供 `path`、`name` 和 `data` 中的一个 +@msg mode must be replace, keep or append 模式必须为 replace、keep 或 append +@msg the file is not an XMP metadata template 该文件不是 XMP 元数据模板 Copyright Notice: 版权声明: Copyright Status: 版权状态: Copyright Symbol 著作权符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab7f9d9dd2..36d2d63b0b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -615,6 +615,18 @@ font-technology Variable 可變 Copy Width Point 複製寬度點 Copyright 版權 Copyright Info URL: 著作權資訊網址: + Save Metadata Template… 儲存中繼資料範本… + Import Options 匯入選項 + Clear existing fields and use the template's 清除現有欄位並使用範本的欄位 + Keep existing fields, but replace those the template has 保留現有欄位,但取代範本中包含的欄位 + Keep existing fields, but append those the template has 保留現有欄位,但附加範本中包含的欄位 +@msg the template name can't be empty 範本名稱不能空白 +@msg the template name isn't usable as a file name 範本名稱無法用作檔案名稱 +@msg no metadata templates folder here 這裡沒有中繼資料範本資料夾 +@msg give `name` or `path`, not both 請提供 `name` 或 `path`,不可同時提供 +@msg give one of `path`, `name` and `data` 請提供 `path`、`name` 和 `data` 其中之一 +@msg mode must be replace, keep or append 模式必須是 replace、keep 或 append +@msg the file is not an XMP metadata template 這個檔案不是 XMP 中繼資料範本 Copyright Notice: 著作權聲明: Copyright Status: 著作權狀態: Copyright Symbol 著作權符號 diff --git a/docs/mcp.md b/docs/mcp.md index 8ca4121032..e154d6e21a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7312,6 +7312,34 @@ written unless the whole batch succeeds puts the saves and exports last, or runs {"name":"run_command","arguments":{"command":"file.info","params":{"author":"Ada","keywords":"poster, fair","rating":4,"copyrightStatus":"copyrighted","copyrightNotice":"© 2026 Ada"}}} ``` +A PDF, `.ai` or `.ait` also opens with the `authorTitle` and `rating` its XMP packet gives (`photoshop:AuthorsPosition`, +`xmp:Rating`, a whole number from 0 to 5). + +Metadata templates (the menu at the top of File Info: Save Metadata Template…, Import…, the saved templates and +Templates Folder; https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260) keep File +Info fields in an XMP file. `file.info.saveTemplate {name?, path?, fields?}` writes the `title` (when it is not the +document's name), `author`, `authorTitle`, `description`, `keywords`, `rating` (from 1), `copyrightStatus`, +`copyrightNotice` and `copyrightUrl` that have a value as an XMP packet, using the properties listed above; the dates +are left out. `fields` takes `file.info`'s editable keys in place of the document's values. `name` saves into the +metadata templates folder as `.xmp` (the folder is made when it is missing; a name with characters file systems reject, a dot at either end, or a +device name such as `CON` is refused, and a template of the same name is replaced), `path` writes that file, and with +neither the reply's `data` is the packet; `name` and `path` together are refused. In the app the folder is +`Metadata Templates` in VectorCraft's settings folder; the web build has none. +`file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}` reads one template (a file, a template in the +folder, or the packet as text; at most 8 MB, more than any saved template holds) and merges it in one undo step, recording nothing when no field changes. +`mode` is VectorCraft's own name for the three ways: `replace` clears the fields a template can hold (not the title) +and takes the template's, `keep` keeps the fields and takes each one the template gives, and `append` keeps the fields, +adds the template's keywords and takes its other fields only where the field is empty. A value `file.info` would +refuse is left out. With `apply: false` nothing changes and the reply is the merged File Info, merged into `base` (the +fields as `file.info` takes them) when given; the File Info dialog uses this for Import. A missing or bad `mode`, a +file that is not XMP and a file over 8 MB are refused. `file.info.templates {create?}` lists the folder's `.xmp` files +(the first 1,000 by name) as `{name, file, path}`, with the `folder` where the caller's file access shows full +paths; `create: true` makes the folder first. `applyTemplate`'s `name` takes either a listed `name` or its `file`. + +```json +{"name":"run_command","arguments":{"command":"file.info.applyTemplate","params":{"name":"Studio","mode":"append"}}} +``` + ## Document Raster Effects Settings `document.rasterEffectsSettings` holds how raster effects (shadows, glows, blurs, feathers) become images when PDF diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4424700be..1e146a4ae5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1859,6 +1859,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). - PDF export and PDF-compatible `.ai` and `.ait` saves write File Info's copyright notice, URL and status to the XMP packet (`dc:rights`, `xmpRights:WebStatement`, `xmpRights:Marked`), so a PDF or `.ai` opened from its pages keeps them (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). - Opening a PDF or PDF-compatible `.ai` whose XMP packet nests elements more than 256 deep no longer overflows the stack: File Info leaves the packet out and takes the document information dictionary's values (`crates/pdf/src/tests/file_info.rs`). + - File Info has metadata templates: its menu saves the fields as an XMP file (Save Metadata Template…, into the Metadata Templates folder in the settings folder or anywhere), imports one with a choice of clearing the fields first, replacing the ones the template has, or appending to them (VectorCraft's own names for the three ways), lists the saved templates and opens Templates Folder; the import is one undo step (`file.info.saveTemplate`, `file.info.applyTemplate`, `file.info.templates`; `crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests/file_info.rs`, `crates/ui-egui/src/dialogs/file_info.rs`). A PDF or `.ai` also opens with the rating and author title its XMP packet gives. - `file.print`, `print.preview` and `print.setup` take a print preset by name (`preset`: `[Default]` or a saved preset, in any case): its settings are used instead of the document's, with `settings` over them, `print.setup` saves them with the document, and an unknown name is refused with the list of presets. - Print's Copies per Sheet (`copiesPerSheet`, `gutter`; off by default) prints as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, as one grid placed like a single copy; the preview shows them, and an artboard that does not fit prints one copy per sheet with a warning (#1283). - Place and the Links panel, Package (placed `.vectorcraft` documents packaged with their own linked files and fonts, relinked to the copies: #777), File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457). From c1defd081c06b04b23515cc8c6bb8213710bd427 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:40:47 -0800 Subject: [PATCH 23/41] Variables: the open Data Set list marks the current data set again Since the Data Set box took over renaming (#7860), the list button next to it passed an empty name to dropdown_names_named, so the open list marked no row. The button now keeps its empty closed field and marks the current data set's row in the open list. The rename test opens the list, checks that only the renamed data set is marked and clicks the other row to choose it, instead of running dataset.select. The no-data-set test checks that the box is disabled. --- crates/ui-egui/src/panels/variables.rs | 60 ++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index aab1892ea2..4005c7f48f 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -263,7 +263,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(to) = typed { rename_active_dataset(app, current, &to); } - let picked = widgets::dropdown_names_named(ui, "variables-active", Some(tl!("Data Sets")), "", &names, 26.0); + // The closed list button is too narrow for a name and shows none; the open list marks the + // current data set. + let picked = widgets::combo_named(ui, "variables-active", Some(tl!("Data Sets")), "", 26.0, |ui| { + let mut chosen = None; + for (i, name) in names.iter().enumerate() { + if ui.add(egui::Button::selectable(*name == current, *name)).clicked() { + chosen = Some(i); + } + } + chosen + }); if let Some(name) = picked.and_then(|i| names.get(i)) && *name != current { @@ -562,6 +572,37 @@ mod tests { self.frame(app, vec![Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: none }]); self.frame(app, vec![]); } + + /// The panel's accessibility nodes after two frames without input. + fn nodes(&mut self, app: &mut VectorcraftApp) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { + self.frame(app, vec![]); + let out = self.frame(app, vec![]); + out.platform_output.accesskit_update.expect("an accessibility tree").nodes + } + + /// Clicks the center of `node`. + fn click(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node) { + use egui::{Event, Modifiers, PointerButton}; + let b = node.bounds().expect("bounds"); + let pos = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let (button, none) = (PointerButton::Primary, Modifiers::default()); + self.frame(app, vec![Event::PointerMoved(pos), Event::PointerButton { pos, button, pressed: true, modifiers: none }]); + self.frame(app, vec![Event::PointerButton { pos, button, pressed: false, modifiers: none }]); + self.frame(app, vec![]); + } + + /// Clicks the Data Set list button and returns the rows of the open list: the buttons that + /// were not in the panel before it opened. + fn open_data_set_list(&mut self, app: &mut VectorcraftApp) -> Vec { + use egui::accesskit::Role; + let before = self.nodes(app); + let (_, list) = + before.iter().find(|(_, n)| n.role() == Role::ComboBox && n.label() == Some("Data Sets")).expect("the Data Set list button"); + let list = list.clone(); + self.click(app, &list); + let after = self.nodes(app); + after.into_iter().filter(|(id, n)| n.role() == Role::Button && !before.iter().any(|(b, _)| b == id)).map(|(_, n)| n).collect() + } } fn set_names(app: &mut VectorcraftApp) -> Vec { @@ -574,7 +615,8 @@ mod tests { } /// A name typed in the Data Set box and entered renames the current data set in one undo step; - /// the list still chooses another data set afterward. + /// the open list then marks the renamed data set as the current one, and a click on another + /// row chooses that data set. #[test] fn the_data_set_box_renames_the_current_data_set() { let mut app = app_with_data(); @@ -587,10 +629,14 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Spring")); assert_eq!(undo_steps(&app), before + 1); assert_eq!(app.session.active().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Rename Data Set")); - // The new name is what the box shows, and what the list offers with the other row. + // The new name is what the box shows, and what the list offers, marked, with the other row. let text = crate::tests_labels::painted_text(&mut app, show); assert!(text.contains("Spring"), "{text}"); - app.run("dataset.select", json!({"name": "Data Set 2"})).unwrap(); + let rows = d.open_data_set_list(&mut app); + let marked: Vec<(Option<&str>, bool)> = rows.iter().map(|n| (n.label(), n.toggled() == Some(egui::accesskit::Toggled::True))).collect(); + assert_eq!(marked, [(Some("Spring"), true), (Some("Data Set 2"), false)]); + let other = rows.iter().find(|n| n.label() == Some("Data Set 2")).expect("the Data Set 2 row").clone(); + d.click(&mut app, &other); assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Data Set 2")); } @@ -626,6 +672,12 @@ mod tests { app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); let before = undo_steps(&app); let mut d = Driver::new(); + let nodes = d.nodes(&mut app); + let (_, field) = nodes + .iter() + .find(|(_, n)| matches!(n.role(), egui::accesskit::Role::TextInput | egui::accesskit::Role::MultilineTextInput)) + .expect("the Data Set box"); + assert!(field.is_disabled(), "the Data Set box is enabled without a data set"); d.type_name(&mut app, "Spring"); assert!(set_names(&mut app).is_empty()); assert_eq!(undo_steps(&app), before); From 04b312312087ed79213ef8f40abcc44eee97af29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:41:45 -0800 Subject: [PATCH 24/41] Clipboard: paste checks the size of another app's data before copying it Paste takes at most 64 MiB of a format another app copied, VectorCraft's existing limit for copied files, and reads the size before the copy: - On Windows, each registered format, the CF_DIBV5 and CF_DIB bitmaps (together), CF_UNICODETEXT and the CF_HDROP file list. A larger format is skipped and the next one is tried. - On macOS, each pasteboard type's data length is checked before it is copied. - A copied file list of more than 1,024 files pastes no file, and no file in it is opened, on every platform, as the Linux text/uri-list reader already does. On Windows the CF_HDROP names are counted before they are read. --- apps/vectorcraft/src/clipboard.rs | 281 ++++++++++++++++++++++++++---- docs/target-app-parity.md | 1 + 2 files changed, 244 insertions(+), 38 deletions(-) diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index ec6256a114..4ed77b2e05 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -157,6 +157,10 @@ fn copied_file(paths: Vec, mimes: &[&'static str]) -> Option { /// [`copied_file`] with a file of more than `limit` bytes skipped. fn copied_file_within(paths: Vec, mimes: &[&'static str], limit: usize) -> Option { + // A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at. + if paths.len() > MAX_URIS { + return None; + } paths.into_iter().find_map(|path| { // text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only. let path = match path.to_str() { @@ -197,6 +201,65 @@ fn read_rest(file: impl Read, mut data: Vec, limit: usize) -> Option (data.len() <= limit).then_some(data) } +/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports +/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and +/// when the copy comes to more than `limit` bytes. +#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))] +fn copy_within(size: Option, limit: usize, copy: impl FnOnce() -> Option>) -> Option> { + size.filter(|&n| n > 0 && n <= limit)?; + copy().filter(|data| data.len() <= limit) +} + +/// The copies of `ids`' data, in order, [`copy_within`] what is left of `limit` bytes once the +/// copies before them are taken: an id whose data doesn't fit is skipped and the next one is tried. +#[cfg_attr(not(windows), allow(dead_code))] +fn copies_within( + ids: impl IntoIterator, + limit: usize, + mut size: impl FnMut(T) -> Option, + mut copy: impl FnMut(T) -> Option>, +) -> Vec> { + let mut left = limit; + ids.into_iter() + .filter_map(|id| { + let data = copy_within(size(id), left, || copy(id))?; + left = left.saturating_sub(data.len()); + Some(data) + }) + .collect() +} + +/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a +/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit` +/// files. Counting stops at the first name past `limit`. A block too short for its header, or +/// whose names would start past its end, is not within. +#[cfg_attr(not(windows), allow(dead_code))] +fn drop_files_within(block: &[u8], limit: usize) -> bool { + let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?)); + let (Some(start), Some(wide)) = (field(0), field(16)) else { + return false; + }; + let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else { + return false; + }; + let (mut count, mut in_name) = (0usize, false); + for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) { + if unit.iter().all(|&b| b == 0) { + if !in_name { + break; + } + in_name = false; + } else if !in_name { + in_name = true; + count += 1; + if count > limit { + return false; + } + } + } + true +} + /// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted /// data) names no files. const MAX_URIS: usize = 1024; @@ -278,12 +341,13 @@ fn file_uri_path(uri: &str) -> Option { #[cfg(windows)] mod win { - use std::num::NonZeroU32; + use std::num::{NonZeroU32, NonZeroUsize}; use clipboard_win::{formats, options::NoClear, raw}; use super::{ - BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats, + BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copies_within, copy_within, + decode_png, dib_image, drop_files_within, png_flavour, windows_formats, }; /// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the @@ -370,8 +434,11 @@ mod win { let mut files = vec![]; { let _open = clipboard_win::Clipboard::new_attempts(10).ok()?; - // None copied when the clipboard holds no file list. - let _ = raw::get_file_list_path(&mut files); + // None copied when the clipboard holds no file list, or one of more than MAX_BYTES + // or MAX_URIS files: the list is counted before its names are copied. + if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) { + let _ = raw::get_file_list_path(&mut files); + } } // The files are read with the clipboard closed again, not keeping other apps waiting. copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| { @@ -390,44 +457,64 @@ mod win { } } - /// Read the first registered format of `mime` the clipboard holds into `data`. - fn read_registered(mime: &str, data: &mut Vec) -> bool { - formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| { - data.clear(); - raw::get_vec(id, data).is_ok() && !data.is_empty() + /// The size the clipboard reports for format `id`, while it is open. + fn size_of(id: u32) -> Option { + raw::size(id).map(NonZeroUsize::get) + } + + /// The data of format `id`, while the clipboard is open, copied only when its size is at most + /// `limit` bytes ([`copy_within`]). + fn copy_registered(id: u32, limit: usize) -> Option> { + copy_within(size_of(id), limit, || { + let mut data = vec![]; + raw::get_vec(id, &mut data).ok()?; + Some(data) }) } + /// The first registered format of `mime` the clipboard holds that is not empty and at most + /// [`MAX_BYTES`]; a larger one is skipped and the next tried. + fn read_registered(mime: &str) -> Option> { + formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty())) + } + /// A device-independent bitmap as a PNG flavour. fn dib_png(dib: &[u8]) -> Option { png_flavour(&dib_image(dib)?) } /// Copy both bitmap formats while the clipboard is open, then decode them in preference order. - pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option>) -> Option { - let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect(); + /// `size` gives each format's size before `get` copies it, and the two copies come to at most + /// [`MAX_BYTES`] together ([`copies_within`]). + pub(super) fn read_dibs(size: impl FnMut(u32) -> Option, get: impl FnMut(u32) -> Option>) -> Option { + let dibs = copies_within(DIBS, MAX_BYTES, size, get); (!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib))))) } /// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and - /// the work that comes back decodes each captured format in preference order. + /// the work that comes back decodes each captured format in preference order. Text whose + /// UTF-16 block is larger than [`MAX_BYTES`], or comes to more as UTF-8, is not read. fn read_one(mime: &'static str) -> Option { - let mut data = vec![]; - let mime = match mime { - BITMAP if read_registered(PNG, &mut data) => PNG, - BITMAP => { - return read_dibs(|id| { - let mut dib = vec![]; - raw::get_vec(id, &mut dib).ok()?; - Some(dib) - }); - } + let (mime, mut data) = match mime { + BITMAP => match read_registered(PNG) { + Some(png) => (PNG, png), + None => { + return read_dibs(size_of, |id| { + let mut dib = vec![]; + raw::get_vec(id, &mut dib).ok()?; + Some(dib) + }); + } + }, TEXT => { - raw::get_string(&mut data).ok()?; - TEXT + let text = copy_within(size_of(formats::CF_UNICODETEXT), MAX_BYTES, || { + let mut text = vec![]; + raw::get_string(&mut text).ok()?; + Some(text) + })?; + (TEXT, text) } - m if read_registered(m, &mut data) => m, - _ => return None, + m => (m, read_registered(m)?), }; // Memory blocks can be longer than the data: SVG text ends at its first NUL. if mime == SVG @@ -3092,7 +3179,7 @@ mod mac { use objc2_app_kit::NSPasteboard; use objc2_foundation::{NSArray, NSString}; - use super::{Flavour, pasteboard_types}; + use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types}; /// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only. pub fn has(mimes: &[&'static str]) -> bool { @@ -3103,13 +3190,16 @@ mod mac { }) } - /// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]). + /// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is + /// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger + /// type is skipped and the next tried. pub fn read(mime: &str) -> Option { autoreleasepool(|_| { let pasteboard = NSPasteboard::generalPasteboard(); pasteboard_types(mime).iter().find_map(|&(t, mime)| { - let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec(); - (!data.is_empty()).then_some(Flavour { mime, data }) + let held = pasteboard.dataForType(&NSString::from_str(t))?; + let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?; + Some(Flavour { mime, data }) }) }) } @@ -3296,6 +3386,105 @@ mod tests { assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty()); } + /// A copied file list of more than 1,024 files pastes none, before any file is looked at, + /// wherever the list came from; 1,024 files paste the first that is art. + #[test] + fn a_copied_file_list_longer_than_the_limit_pastes_no_file() { + let d = dir("many"); + let art = d.path().join("art.svg"); + std::fs::write(&art, "").unwrap(); + let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::>(); + let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat(); + assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG)); + // The art first: no file is opened past the count. + let first = [vec![art.clone()], missing(MAX_URIS)].concat(); + assert!(copied_file(first, &PASTE_ORDER).is_none()); + assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none()); + } + + /// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit, + /// and the copy is not asked for otherwise. + #[test] + fn clipboard_data_is_copied_only_when_its_size_fits() { + let copy = |size: Option, got: usize| { + let mut asked = false; + let data = copy_within(size, 8, || { + asked = true; + Some(vec![1; got]) + }); + (data.map(|d| d.len()), asked) + }; + assert_eq!(copy(Some(8), 8), (Some(8), true)); + assert_eq!(copy(Some(1), 1), (Some(1), true)); + for size in [None, Some(0), Some(9), Some(usize::MAX)] { + assert_eq!(copy(size, 1), (None, false), "{size:?}"); + } + // Data that comes to more than the limit after all is refused. + assert_eq!(copy(Some(8), 9), (None, true)); + assert_eq!(MAX_BYTES, 64 << 20); + } + + /// Formats copied together come to the limit at most: one that doesn't fit what is left is + /// skipped without a copy and the next one is tried. + #[test] + fn formats_copied_together_share_the_limit() { + let sizes = [5, 4, 2, 0]; + let mut asked = vec![]; + let copies = copies_within( + 0..sizes.len(), + 8, + |i| sizes.get(i).copied(), + |i| { + asked.push(i); + Some(vec![0; sizes[i]]) + }, + ); + assert_eq!(copies.iter().map(Vec::len).collect::>(), [5, 2]); + assert_eq!(asked, [0, 2]); + assert!(copies_within([0], 8, |_| None, |_| Some(vec![0])).is_empty()); + } + + /// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one + /// byte a character, each ended by a NUL, and one more NUL. + fn drop_files(names: &[&str], wide: bool) -> Vec { + let mut block = vec![]; + block.extend(20u32.to_le_bytes()); + block.extend([0u8; 12]); + block.extend(u32::from(wide).to_le_bytes()); + for name in names.iter().copied().chain([""]) { + for unit in name.encode_utf16().chain([0]) { + if wide { + block.extend(unit.to_le_bytes()); + } else { + block.push(unit as u8); + } + } + } + block + } + + #[test] + fn a_windows_file_list_is_counted_before_its_names_are_read() { + let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::>(); + for wide in [true, false] { + let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::>(), wide); + assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}"); + assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}"); + assert!(drop_files_within(&list(0), MAX_URIS), "{wide}"); + // Names past the list's closing NUL are not counted. + let mut ended = list(2); + ended.extend(list(MAX_URIS + 1).get(20..).unwrap()); + assert!(drop_files_within(&ended, 2), "{wide}"); + // A list cut short counts the names it holds. + assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}"); + } + // A header cut short, or names that would start past the block's end. + assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS)); + let mut past = drop_files(&["a"], true); + past[0..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(!drop_files_within(&past, MAX_URIS)); + } + #[test] fn gnome_files_list_names_its_files_after_copy_or_cut() { let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::>(); @@ -3349,19 +3538,35 @@ mod tests { let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED])); let mut captured = Vec::new(); - let read = win::read_dibs(|id| { - captured.push(id); - match id { - CF_DIBV5 => Some(vec![40, 0, 0]), - CF_DIB => Some(valid.clone()), - _ => None, - } - }) + let get = |id: u32| match id { + CF_DIBV5 => Some(vec![40, 0, 0]), + CF_DIB => Some(valid.clone()), + _ => None, + }; + let read = win::read_dibs( + |id| get(id).map(|d| d.len()), + |id| { + captured.push(id); + get(id) + }, + ) .unwrap(); assert_eq!(captured, [CF_DIBV5, CF_DIB]); let flavour = read.flavour().unwrap(); assert_eq!(flavour.mime, PNG); assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]); + // A bitmap larger than the limit is not copied, and the other one still pastes. + captured.clear(); + let read = win::read_dibs( + |id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) }, + |id| { + captured.push(id); + get(id) + }, + ) + .unwrap(); + assert_eq!(captured, [CF_DIB]); + assert_eq!(read.flavour().map(|f| f.mime), Some(PNG)); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 65cbf9e216..c83a9e8379 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1979,6 +1979,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Import and paste, 2026-10-13: a multi-artboard `.ai` with notes beside its artboards opens from its editing data, a page's art past its artboard no longer lying over the page before it (#1528); a `.ai` gradient whose stops are listed upwards keeps each midpoint on the stop that starts its part of the ramp (#1530); SVG text on a path follows basic shapes (circle, ellipse, rect, line, polyline, polygon) as their SVG 2 equivalent paths (#1531, fixes #1527); PDFs whose alpha soft masks are drawn as images import with the mask instead of empty art (#1551); EPS and PostScript type set in Type 42 (TrueType) fonts imports at its size instead of 1000 times too large (#1553); PDF and EPS import keep a clipping path whose bounding box covers the page but whose shape doesn't (#1544, fixes #1542). Opening or placing a file with an image too large to decode says so, and the Links panel shows it on the row (#1540, part of #1479). Paste takes a PDF or EPS another app copied as editable vector art: from the macOS pasteboard (with SVG), EPS on Windows beside PDF, and `.eps` files copied in a file manager, with the new command `clipboard.importEps` (#1538, fixes #1499). - A `.ai` or `.ait` file copied in a file manager pastes as its art: one that holds a PDF pastes the objects of its editing data, and one saved as PostScript pastes as a copied `.eps` file does. - Paste checks the size of a file copied in a file manager before reading it: a file of more than 64 MiB, VectorCraft's own limit, is skipped and the next copied file that is art pastes. A file that grows past the limit while it is read is skipped too, after at most one byte more than the limit is read. + - Paste checks the size of the data another app copied before copying it, and takes at most 64 MiB of a format, VectorCraft's own limit: on Windows each registered format, the two bitmap formats (CF_DIBV5 and CF_DIB, together), text (both its UTF-16 data and the UTF-8 text made from it) and the file list (CF_HDROP), and on macOS each pasteboard type. A larger format is skipped and the next one pastes. A list of more than 1,024 copied files pastes no file and no file in it is opened, as on the Linux clipboard; on Windows the names are counted before they are read (`clipboard::tests::clipboard_data_is_copied_only_when_its_size_fits`, `formats_copied_together_share_the_limit`, `a_copied_file_list_longer_than_the_limit_pastes_no_file`, `a_windows_file_list_is_counted_before_its_names_are_read`; not yet run on Windows or macOS). - A copied `.ai` or `.ait` file that holds a PDF pastes the objects of its editing data as File › Open reads them: every layer's objects go into the active layer in their stacking order, with their names, hidden objects and type objects, instead of the PDF page's art with its type as outlines. When the editing data can't be read, the file pastes its page as before (`clipboard.importPdf {editingData}`). The objects of a hidden layer come in hidden, from a pasted EPS too. - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). From 6ac45cd427451d7a2dbbc93f5080f70e36e44c71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:44:39 -0800 Subject: [PATCH 25/41] Docs: menu-breadth counts match the current menu tree The menu tree at 957397e7 has 717 items bound to commands and 2 stubs (Effect > 3D and Materials > Materials and Help > VectorCraft Help); Check Spelling now opens its dialog. The count leaves out 239 entries in the recent-file, recent-font, saved-selection and saved-view slots and in the Open With, Scripts, Plug-ins, Type > Font, Effect > SVG Filters and View > Perspective Grid preset submenus. The feature-breadth rows in ROADMAP.md and target-app-parity.md now give 717/719 (99.7%); the earlier counts stay as dated history. --- ROADMAP.md | 2 +- docs/target-app-parity.md | 17 +++++++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 0270db445e..db13a32b71 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 65cbf9e216..eac4760b69 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -185,7 +185,7 @@ the work list made from it. Deep areas have their own checklists: [UI and intera | 2026-10-22 | minor | PDF import: a gap between glyphs of two sizes reads as a space measured against the smaller size (#3623); mixed-size regression. Scores and hours unchanged. | | 2026-10-21 | minor | PDF import: letter-spaced type keeps its word spaces and gains none between letters; synthetic Tc and glyph-by-glyph regressions. Scores and hours unchanged. | | 2026-10-15 | minor | Image Trace retains nonzero positioned boundaries when a fixed-end returning piece has fewer than two fitted cubics. Source-generated tests check survival, winding, shared-edge reversal and Noise controls; see `image-trace-quality.md`. Scores and hours unchanged. | -| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 353 of 375 items wired (94.1%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | +| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 717 of 719 items wired (99.7%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 57 of 57 (100%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | | **Feature depth** (each area scored by behaviour, weighted) | **~75%** | estimated, area table below | | **Ready for real work, mainstream illustrator** | **~65%** (60–70%) | estimated, see [Ready for real work](#ready-for-real-work) | | **Ready for real work, full Illustrator** (decides the stage) | **~62%** (57–67%) | estimated: additive weighted sum over the dimensions, see [Ready for real work](#ready-for-real-work) | @@ -210,11 +210,16 @@ tests and the CI gate. See [Calibration](#calibration). Adobe install, its `Info.plist` and `.lproj` folders included, and forbids launching or measuring it. So nothing here is a menu dump or a side-by-side measurement: the numbers come from our own code against Illustrator's public documentation. -- **From the code (measured, origin/main `01e165af`):** - - Menu tree (`crates/ui-egui/src/menus.rs`, laid out in Illustrator's menu order): 348 items bound to - commands, 26 stubs (`todo(…)`/`todos(…)`), so 93.0% of menu items do something (348 and 26 after Snap to Glyph shipped in #3124; 348 and 27 after the - Revolve merge; 350 and 25, 93.3%, after Graph › Design and Marker; 353 and 22, 94.1%, after Extrude & Bevel, Inflate and Rotate). The menu stubs on `a47d7eec` are Effect › 3D and Materials › Materials, - Edit › Spelling › Check Spelling and Help › VectorCraft Help. +- **From the code (measured, origin/main `01e165af`; the menu tree at `957397e7`):** + - Menu tree (`crates/ui-egui/src/menus/tree.rs` and `submenus.rs`, laid out in Illustrator's menu order): walking + `menu_tree()` at `957397e7` finds 717 items bound to commands and 2 stubs (`todo(…)`), so 99.7% of menu items do + something. The two stubs are Effect › 3D and Materials › Materials and Help › VectorCraft Help; Edit › Spelling › + Check Spelling opens its dialog. The count includes the Effect entries built from the effect catalog. It leaves + out 239 entries in the recent-file, recent-font, saved-selection and saved-view slots and in the Open With, + Scripts, Plug-ins, Type › Font, Effect › SVG Filters and View › Perspective Grid preset submenus, some of which + also hold built-in commands. Earlier counts covered fewer entries: 348 items and 26 stubs (`todo(…)`/`todos(…)`), 93.0%, at `01e165af` and + after Snap to Glyph shipped in #3124; 348 and 27 after the Revolve merge; 350 and 25, 93.3%, after Graph › Design + and Marker; 353 and 22, 94.1%, after Extrude & Bevel, Inflate and Rotate. - Engine commands: ~710 ids registered with `cmd!` across `crates/engine/src/cmd` (plus macro-generated families), and 85 UI-only commands (`UI_COMMANDS`). - Tools: 91 in `crates/tools/src/catalog.rs`; Touch Type is listed but not implemented, and the Dimension From 4b636ea642abaa70227fbcde2ae502e6a2c3918f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:51:16 -0800 Subject: [PATCH 26/41] File Info: a template name that is not a file name is refused file.info.applyTemplate with a name such as a/b no longer opens the template its safe file name names (a-b.xmp): a name that matches no listed template and is not a file name as it is gives an error. docs/mcp.md cites the help page that describes metadata templates. --- crates/engine/src/cmd/fileinfo.rs | 3 +++ crates/engine/src/tests/fileinfo.rs | 9 +++++++++ docs/mcp.md | 2 +- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileinfo.rs b/crates/engine/src/cmd/fileinfo.rs index f4f38855dc..b6b1643ea4 100644 --- a/crates/engine/src/cmd/fileinfo.rs +++ b/crates/engine/src/cmd/fileinfo.rs @@ -257,6 +257,9 @@ fn template_bytes(s: &Session, p: &Value) -> Result> { .min_by_key(|f| (f != name, *f != own)); if let Some(file) = listed { path = dir.join(file).to_string_lossy().into_owned(); + } else if std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy()).as_deref() != Some(name) { + // A name that is not a file name as it is never opens another template. + return Err(bad(APPLY, "the template name isn't usable as a file name")); } let plain_file = |path: &str| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()); if std::fs::symlink_metadata(&path).is_ok() && !plain_file(&path) { diff --git a/crates/engine/src/tests/fileinfo.rs b/crates/engine/src/tests/fileinfo.rs index ba706e43c0..54482826b3 100644 --- a/crates/engine/src/tests/fileinfo.rs +++ b/crates/engine/src/tests/fileinfo.rs @@ -779,6 +779,15 @@ fn the_templates_folder_lists_only_xmp_files_and_can_be_made() { assert_eq!(r["author"], "Grace"); let r = s.execute("file.info.applyTemplate", &json!({"name": "b.XMP.xmp", "mode": "replace", "apply": false})).unwrap(); assert_eq!(r["author"], "Ada"); + // A name that is not a file name never opens the template its safe form names. + let grace = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo { author: Some("Grace".into()), ..Default::default() }); + std::fs::write(folder.join("a-b.xmp"), grace).unwrap(); + let r = s.execute("file.info.applyTemplate", &json!({"name": "a-b", "mode": "replace", "apply": false})).unwrap(); + assert_eq!(r["author"], "Grace"); + for name in ["a/b", "a\\b", "a:b"] { + let e = s.execute("file.info.applyTemplate", &json!({"name": name, "mode": "replace", "apply": false})).unwrap_err(); + assert!(e.to_string().contains("isn't usable as a file name"), "{name}: {e}"); + } } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f8c8be380b..549797968f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7608,7 +7608,7 @@ A PDF, `.ai` or `.ait` also opens with the `authorTitle` and `rating` its XMP pa `xmp:Rating`, a whole number from 0 to 5). Metadata templates (the menu at the top of File Info: Save Metadata Template…, Import…, the saved templates and -Templates Folder; https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260) keep File +Templates Folder; https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=278) keep File Info fields in an XMP file. `file.info.saveTemplate {name?, path?, fields?}` writes the `title` (when it is not the document's name), `author`, `authorTitle`, `description`, `keywords`, `rating` (from 1), `copyrightStatus`, `copyrightNotice` and `copyrightUrl` that have a value as an XMP packet, using the properties listed above; the dates From a97d2e221e68762771592e410d321d7b04ea080f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:52:10 -0800 Subject: [PATCH 27/41] Monitor profile: test that tiled panes blend translucent art over their own paper A tiled pane of a document behind the front one blends its translucent art with that document's simulated paper in sRGB before the display profile's conversion. The test tiles two documents with different paper colors and checks the back pane's backdrop and its middle pixel against the converted blend, the blend over the front paper and the art converted alone. --- crates/ui-egui/src/canvas/panes/tests.rs | 90 ++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 3a45d90157..34611fd0d7 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -536,3 +536,93 @@ fn other_panes_draw_through_their_documents_profiles() { assert!(close(shown, device), "the back CMYK document draws through its Device CMYK: {shown:?}, not {device:?} (front: {front:?})"); assert!(near(cms::active().display_rgb(&color).map(|v| (v * 255.0).round() as u8), p3), "the front document's profile stays active"); } + +/// With a display profile, the tiled pane of a document behind the front one blends its +/// translucent art with that document's own simulated paper in sRGB, then converts the blend: +/// drawn over its converted paper, the pane shows the converted blend, not the art converted alone +/// and not a blend with the front document's paper. Opaque and empty pixels convert as before. +#[test] +fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_conversion() { + use crate::display_profile::{Found, Reading}; + let mut app = app_with(2); + app.canvas.panes.worker_started = true; // every pane renders on this thread + let (front_paper, back_paper) = ([0x20, 0x40, 0xc0], [0xe0, 0xc0, 0x20]); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("document.setup", json!({"gridColors": ["#2040c0", "#ffffff"], "simulatePaper": true})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("document.setup", json!({"gridColors": ["#e0c020", "#ffffff"], "simulatePaper": true})).unwrap(); + let half = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap(); + app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + let uid = app.session.documents()[1].uid; + let ctx = egui::Context::default(); + // The second document's pane: the raster one frame uploads, its width, and the key it was rendered for. + let pane = |app: &mut VectorcraftApp| -> (Vec, usize, CacheKey) { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), + max_texture_side: Some(8192), + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| app.canvas_area(ui)); + let (key, tex) = app.canvas.panes.shown.iter().find(|(slot, _)| slot.0 == uid).map(|(_, s)| s).expect("the second document's pane rendered"); + let id = tex.id(); + let up = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (img.pixels.clone(), img.width()) + }); + let key = key.clone(); + out.textures_delta.clear(); + let (pixels, width) = up.expect("the pane uploads"); + (pixels, width, key) + }; + app.session.prefs.monitor_profile_display = false; + let (srgb, width, key) = pane(&mut app); + assert!(key.backdrop.is_none(), "no display profile: nothing to blend"); + let p3 = crate::display_profile::tests::p3(); + let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + app.session.prefs.monitor_profile_display = true; + let (shown, _, key) = pane(&mut app); + let backdrop = key.backdrop.as_deref().expect("the pane's Preview blends with its paper"); + assert!( + !backdrop.artboards.is_empty() && backdrop.artboards.iter().all(|(_, c)| *c == back_paper), + "the pane blends with its own document's paper: {backdrop:?}" + ); + assert_eq!(srgb.len(), shown.len()); + // What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it. + let over = |c: Color32, under: [u8; 3]| { + let k = 255 - u32::from(c.a()); + [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255) + }; + let plain = |s: Color32| { + let mut px = s.to_array(); + t.apply_premultiplied(&mut px); + Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + // Pixel `s` over the paper `paper` in sRGB, converted. + let blend = |s: Color32, paper: [u8; 3]| { + let k = 255 - u32::from(s.a()); + t.apply8([0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (u32::from(paper[j]) * k + 127) / 255).min(255) as u8)).map(u32::from) + }; + let differs = |a: [u32; 3], b: [u32; 3]| (0..3).any(|j| a[j].abs_diff(b[j]) > 2); + let under = t.apply8(back_paper); + for (s, c) in srgb.iter().zip(&shown) { + if s.a() == 0 || s.a() == 255 { + assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before"); + } + } + // The middle of the pane is the middle of the document, inside the 50% fill. + let at = srgb.len() / width / 2 * width + width / 2; + let (s, c) = (srgb[at], shown[at]); + assert!((50..=205).contains(&s.a()), "the 50% fill at the middle: {s:?}"); + assert_eq!(c.a(), s.a(), "the alpha is kept"); + let want = blend(s, back_paper); + let got = over(c, under); + assert!((0..3).all(|j| got[j].abs_diff(want[j]) <= 1), "{got:?} shown, {want:?} wanted"); + // The check tells the two papers and the plain conversion apart. + assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color"); + assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color"); +} From 3fbf957fe308490a7a7cce6a3dd4bb73d871c5a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:01:47 -0800 Subject: [PATCH 28/41] Recolor Artwork: Randomize leaves rows with no current colors out A New Row row has no current colors and recolors nothing, but recolor.randomize shuffled its new color with the other rows', so an art row's color could move onto the empty row and leave the art. Randomize now shuffles and varies only the rows that hold current colors and are not excluded; an empty row keeps its new color. docs/mcp.md says so, and says to Shift-click a row below the new row before Merge, since Merge keeps the topmost selected row's new color. --- crates/engine/src/cmd/recolor.rs | 11 +++++++---- crates/engine/src/tests/recolor.rs | 21 +++++++++++++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index e54d68204e..47e11f9e81 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Randomize Colors", [], None, - "{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", + "{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded and hold current colours), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0; an excluded row, and a row whose from is empty, keeps its new colour} → {map: the rows with their new colours as keys}", always, randomize ), @@ -1746,8 +1746,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); // Each new color with its row's tint and model: a tint moves with its color, and goes when - // the color changes; a model moves with its color. - let mut news: Vec<(Color, f32, Option)> = rows.iter().filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); + // the color changes; a model moves with its color. A row with no current colors recolors + // nothing, so it keeps its new color and takes no other row's. + let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some(); + let mut news: Vec<(Color, f32, Option)> = + rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); if order { rng.shuffle(&mut news); } @@ -1765,7 +1768,7 @@ fn randomize(_: &mut Session, p: &Value) -> Result { .iter() .map(|r| { let (to, tint, model) = - if r.new_color().is_some() { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; + if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 390248f2a9..eff144557a 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -380,6 +380,27 @@ fn randomize_shuffles_new_colours_and_skips_excluded_rows() { assert!((hue(&sb["map"][0]["to"]) - 0.0).abs() < 1.0 && (hue(&sb["map"][1]["to"]) - 120.0).abs() < 1.0, "hue kept"); } +/// A row with no current colors (New Row) keeps its new color through Randomize, and its color +/// goes to no row that holds current colors: the other rows shuffle their own colors only. +#[test] +fn randomize_leaves_an_empty_row_out() { + let mut s = session(); + let map = json!([ + {"from": [], "to": "rgb 0 255 0"}, + {"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, + {"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"}, + ]); + for seed in 0..16 { + let r = run(&mut s, "recolor.randomize", json!({"map": map, "seed": seed})); + assert_eq!(r["map"][0], map[0], "seed {seed}: the empty row keeps its color"); + let mut tos: Vec = [1, 2].iter().map(|i| r["map"][*i]["to"].as_str().unwrap().to_string()).collect(); + tos.sort(); + assert_eq!(tos, ["rgb 0 0 255", "rgb 255 0 0"], "seed {seed}: a permutation of the filled rows' colors"); + } + let sb = run(&mut s, "recolor.randomize", json!({"map": map, "order": false, "saturationBrightness": true, "seed": 3})); + assert_eq!(sb["map"][0], map[0], "the empty row keeps its saturation and brightness"); +} + #[test] fn edit_group_rewrites_in_order_as_one_undo_step() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..eb8aa7ecbf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4508,9 +4508,10 @@ darker than the row's average become tints and shades) or `hueShift` (the most s the others turn by the same hue). `limitTo` snaps new colours to a swatch library's nearest colour; `recolor.randomize {map, order?, saturationBrightness?, seed?}` shuffles or varies new colours; a row with `exclude: true` keeps its colours. A row's `from` may be an empty list: the row recolors nothing, adds no library swatch with -`limitTo` and gives `group` no color, and `recolor.randomize` and `recolor.weigh` keep it. A row without `from`, or with +`limitTo` and gives `group` no color, and `recolor.randomize` and `recolor.weigh` keep it; `recolor.randomize` leaves its +new color as it is and shuffles only the rows that hold current colors. A row without `from`, or with a current color that is not a color, is refused. With art selected, the Recolor Artwork dialog's New Row button (beside -Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click another row and Merge to move its colors into it. An +Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click a row below it and Merge to move that row's colors into it (Merge keeps the topmost selected row's new color). An empty row does not count toward Colors. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo From 22fbf01ea56c15c8bb32a6bf1097650fcaafce09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:46:47 -0800 Subject: [PATCH 29/41] Pathfinder: Outline edges keep their fill's opacity and blend mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Effect › Pathfinder › Outline stroked each edge with the paint of the source's top fill only. The fill's opacity, blend mode and overprint were dropped, and a hidden top fill still colored the edges. The edges now take the paint, opacity, blend mode and overprint of the top fill that paints, or of the top stroke that paints when no fill does. A hidden fill or a fill of no paint is skipped, so a painted fill under it colors the edges. A hidden stroke or a 0 pt stroke is skipped too, and an object with neither still gets edges with no paint. Soft Mix, Hard Mix and Trap had the same gap: they read the top fill even when it was hidden or had no paint. They now use the top fill that paints, so a hidden fill adds no color to a mix, and a member whose only fill is hidden takes no part in Trap. --- crates/effects/src/group.rs | 22 +++++-- crates/effects/src/group/tests.rs | 95 ++++++++++++++++++++++++++++++- 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 94c5509938..63215d897d 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -367,9 +367,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option Node { let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() }; if outline { - let fill = src.appearance.fill_paint(); - let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill }; - appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() }; + // The edges take the paint, opacity, blend mode and overprint of the top fill that paints, + // or of the top stroke that paints when no fill does. + let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i))); + let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0); + if let Some(i) = layer { + (stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint()); + } + appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() }; } let mut n = Node::path(src.id, path, appearance); n.opacity = src.opacity; @@ -504,7 +509,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option f64 { } fn fill_cmyk(src: &Node) -> Option<[f32; 4]> { - let paint = src.appearance.fill_paint(); + // The top fill that paints: a hidden fill adds no color. + let paint = top_painting_fill(&src.appearance)?.paint().clone(); let color = paint.color()?; let tinted = match paint { Paint::Solid { tint, .. } => color.tinted(tint), @@ -637,6 +644,11 @@ fn is_container(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) } +/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped. +fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> { + a.items.iter().rev().find(|i| i.is_fill() && paints(i)) +} + /// Does `item` paint anything? pub fn paints(item: &AppearanceItem) -> bool { item.visible() diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 50fbf8f759..3b8addadea 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -1,6 +1,6 @@ use super::*; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject}; +use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject}; use vectorcraft_geom::{Point, Rect, shapes}; /// Type tests need glyph outlines, which only the optional craft-fonts build input provides. @@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() { assert_eq!(fill.paint.color(), Some(yellow)); } +/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member +/// whose only fill is hidden does not take part. +#[test] +fn trap_skips_a_hidden_fill() { + let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0); + let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0); + let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + hidden.visible = false; + let trap = |members: Vec>| { + let mut g = Node::group(NodeId(10), members); + let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100}); + g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true }); + pathfinder_children(None, &g, None).unwrap() + }; + let mut covered = (*sq(1, 0.0, yellow)).clone(); + covered.appearance.items.push(AppearanceItem::Fill(hidden.clone())); + let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]); + assert_eq!(out.len(), 3, "both squares and one trap"); + assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow)); + let only_hidden = Node::path( + NodeId(1), + shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() }, + ); + assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap"); +} + #[test] fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() { let mut g = two_overlapping_cmyk_squares(); @@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() { assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}"); } +/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color. +#[test] +fn mixes_skip_a_hidden_fill() { + for effect in ["pathfinder.softMix", "pathfinder.hardMix"] { + let mut plain = two_overlapping_cmyk_squares(); + plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true }); + let mut covered = plain.clone(); + let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") }; + let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + hidden.visible = false; + for c in children.iter_mut() { + Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone())); + } + assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}"); + } +} + +/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend +/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill +/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes. +#[test] +fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() { + use vectorcraft_doc::StrokeLayer; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let mut fill = FillLayer::new(red.clone()); + (fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true); + let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + hidden.visible = false; + let mut stroke = StrokeLayer::new(blue.clone(), 2.0); + (stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true); + let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0); + hidden_stroke.visible = false; + let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0); + let look = |items: Vec| Appearance { items, ..Default::default() }; + let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke); + let cases = [ + (look(vec![f(fill.clone())]), Some(red.clone())), + (look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())), + (look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())), + (look(vec![f(hidden.clone())]), None), + (look(vec![s(stroke.clone())]), Some(blue.clone())), + (look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())), + (look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())), + (look(vec![s(zero_stroke)]), None), + ]; + for (appearance, want) in cases { + let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance)); + let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]); + g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect(); + assert!(!edges.is_empty(), "{out:#?}"); + for n in edges { + let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") }; + match &want { + Some(paint) => { + assert_eq!(&s.paint, paint); + assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}"); + } + None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"), + } + } + } +} + #[test] fn shape_modes_follow_the_pathfinder_panel() { let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap(); From f66aa6508350ca676414aba0defbbc9d634bd6a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:06:56 -0800 Subject: [PATCH 30/41] Clipboard: Windows text is bounded before it is converted, and each bitmap format has its own limit The size of a CF_UNICODETEXT block is checked against the most UTF-8 it could come to (3 bytes a code unit), so the converted text is never larger than the limit. CF_DIBV5 and CF_DIB are each copied when they fit the limit, so a large first format that doesn't decode still leaves the second to paste. --- apps/vectorcraft/src/clipboard.rs | 80 +++++++++++++++---------------- docs/target-app-parity.md | 2 +- 2 files changed, 40 insertions(+), 42 deletions(-) diff --git a/apps/vectorcraft/src/clipboard.rs b/apps/vectorcraft/src/clipboard.rs index 4ed77b2e05..cf42079691 100644 --- a/apps/vectorcraft/src/clipboard.rs +++ b/apps/vectorcraft/src/clipboard.rs @@ -210,23 +210,11 @@ fn copy_within(size: Option, limit: usize, copy: impl FnOnce() -> Option< copy().filter(|data| data.len() <= limit) } -/// The copies of `ids`' data, in order, [`copy_within`] what is left of `limit` bytes once the -/// copies before them are taken: an id whose data doesn't fit is skipped and the next one is tried. +/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at +/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4. #[cfg_attr(not(windows), allow(dead_code))] -fn copies_within( - ids: impl IntoIterator, - limit: usize, - mut size: impl FnMut(T) -> Option, - mut copy: impl FnMut(T) -> Option>, -) -> Vec> { - let mut left = limit; - ids.into_iter() - .filter_map(|id| { - let data = copy_within(size(id), left, || copy(id))?; - left = left.saturating_sub(data.len()); - Some(data) - }) - .collect() +fn utf8_most(utf16: usize) -> usize { + utf16.div_ceil(2).saturating_mul(3) } /// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a @@ -346,8 +334,8 @@ mod win { use clipboard_win::{formats, options::NoClear, raw}; use super::{ - BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copies_within, copy_within, - decode_png, dib_image, drop_files_within, png_flavour, windows_formats, + BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png, + dib_image, drop_files_within, png_flavour, utf8_most, windows_formats, }; /// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the @@ -484,16 +472,16 @@ mod win { } /// Copy both bitmap formats while the clipboard is open, then decode them in preference order. - /// `size` gives each format's size before `get` copies it, and the two copies come to at most - /// [`MAX_BYTES`] together ([`copies_within`]). - pub(super) fn read_dibs(size: impl FnMut(u32) -> Option, get: impl FnMut(u32) -> Option>) -> Option { - let dibs = copies_within(DIBS, MAX_BYTES, size, get); + /// `size` gives each format's size before `get` copies it, and a format of more than + /// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried. + pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option, mut get: impl FnMut(u32) -> Option>) -> Option { + let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect(); (!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib))))) } /// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and /// the work that comes back decodes each captured format in preference order. Text whose - /// UTF-16 block is larger than [`MAX_BYTES`], or comes to more as UTF-8, is not read. + /// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read. fn read_one(mime: &'static str) -> Option { let (mime, mut data) = match mime { BITMAP => match read_registered(PNG) { @@ -507,7 +495,7 @@ mod win { } }, TEXT => { - let text = copy_within(size_of(formats::CF_UNICODETEXT), MAX_BYTES, || { + let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || { let mut text = vec![]; raw::get_string(&mut text).ok()?; Some(text) @@ -3424,24 +3412,21 @@ mod tests { assert_eq!(MAX_BYTES, 64 << 20); } - /// Formats copied together come to the limit at most: one that doesn't fit what is left is - /// skipped without a copy and the next one is tried. + /// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before + /// the text is converted: a block that could pass the limit as UTF-8 is not read. #[test] - fn formats_copied_together_share_the_limit() { - let sizes = [5, 4, 2, 0]; - let mut asked = vec![]; - let copies = copies_within( - 0..sizes.len(), - 8, - |i| sizes.get(i).copied(), - |i| { - asked.push(i); - Some(vec![0; sizes[i]]) - }, - ); - assert_eq!(copies.iter().map(Vec::len).collect::>(), [5, 2]); - assert_eq!(asked, [0, 2]); - assert!(copies_within([0], 8, |_| None, |_| Some(vec![0])).is_empty()); + fn text_is_bounded_by_what_its_utf8_could_come_to() { + for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] { + let utf16 = text.encode_utf16().count() * 2; + assert!(utf8_most(utf16) >= text.len(), "{text:?}"); + } + // Every code unit at 3 bytes of UTF-8: the bound is exact. + assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len()); + let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some(); + assert!(copied(MAX_BYTES / 3 * 2)); + assert!(!copied(MAX_BYTES / 3 * 2 + 2)); + assert!(!copied(MAX_BYTES)); + assert_eq!(utf8_most(usize::MAX), usize::MAX); } /// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one @@ -3567,6 +3552,19 @@ mod tests { .unwrap(); assert_eq!(captured, [CF_DIB]); assert_eq!(read.flavour().map(|f| f.mime), Some(PNG)); + // Each format has the limit to itself: a first one at the limit that doesn't decode + // leaves the second to paste. + captured.clear(); + let read = win::read_dibs( + |id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) }, + |id| { + captured.push(id); + get(id) + }, + ) + .unwrap(); + assert_eq!(captured, [CF_DIBV5, CF_DIB]); + assert_eq!(read.flavour().map(|f| f.mime), Some(PNG)); } #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e306204afd..26fcc3fbbd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1982,7 +1982,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Import and paste, 2026-10-13: a multi-artboard `.ai` with notes beside its artboards opens from its editing data, a page's art past its artboard no longer lying over the page before it (#1528); a `.ai` gradient whose stops are listed upwards keeps each midpoint on the stop that starts its part of the ramp (#1530); SVG text on a path follows basic shapes (circle, ellipse, rect, line, polyline, polygon) as their SVG 2 equivalent paths (#1531, fixes #1527); PDFs whose alpha soft masks are drawn as images import with the mask instead of empty art (#1551); EPS and PostScript type set in Type 42 (TrueType) fonts imports at its size instead of 1000 times too large (#1553); PDF and EPS import keep a clipping path whose bounding box covers the page but whose shape doesn't (#1544, fixes #1542). Opening or placing a file with an image too large to decode says so, and the Links panel shows it on the row (#1540, part of #1479). Paste takes a PDF or EPS another app copied as editable vector art: from the macOS pasteboard (with SVG), EPS on Windows beside PDF, and `.eps` files copied in a file manager, with the new command `clipboard.importEps` (#1538, fixes #1499). - A `.ai` or `.ait` file copied in a file manager pastes as its art: one that holds a PDF pastes the objects of its editing data, and one saved as PostScript pastes as a copied `.eps` file does. - Paste checks the size of a file copied in a file manager before reading it: a file of more than 64 MiB, VectorCraft's own limit, is skipped and the next copied file that is art pastes. A file that grows past the limit while it is read is skipped too, after at most one byte more than the limit is read. - - Paste checks the size of the data another app copied before copying it, and takes at most 64 MiB of a format, VectorCraft's own limit: on Windows each registered format, the two bitmap formats (CF_DIBV5 and CF_DIB, together), text (both its UTF-16 data and the UTF-8 text made from it) and the file list (CF_HDROP), and on macOS each pasteboard type. A larger format is skipped and the next one pastes. A list of more than 1,024 copied files pastes no file and no file in it is opened, as on the Linux clipboard; on Windows the names are counted before they are read (`clipboard::tests::clipboard_data_is_copied_only_when_its_size_fits`, `formats_copied_together_share_the_limit`, `a_copied_file_list_longer_than_the_limit_pastes_no_file`, `a_windows_file_list_is_counted_before_its_names_are_read`; not yet run on Windows or macOS). + - Paste checks the size of the data another app copied before copying it, and takes at most 64 MiB of a format, VectorCraft's own limit: on Windows each registered format, each of the two bitmap formats (CF_DIBV5 and CF_DIB), text (the most UTF-8 its UTF-16 data could come to, checked before it is converted) and the file list (CF_HDROP), and on macOS each pasteboard type. A larger format is skipped and the next one pastes. A list of more than 1,024 copied files pastes no file and no file in it is opened, as on the Linux clipboard; on Windows the names are counted before they are read (`clipboard::tests::clipboard_data_is_copied_only_when_its_size_fits`, `text_is_bounded_by_what_its_utf8_could_come_to`, `a_copied_file_list_longer_than_the_limit_pastes_no_file`, `a_windows_file_list_is_counted_before_its_names_are_read`; not yet run on Windows or macOS). - A copied `.ai` or `.ait` file that holds a PDF pastes the objects of its editing data as File › Open reads them: every layer's objects go into the active layer in their stacking order, with their names, hidden objects and type objects, instead of the PDF page's art with its type as outlines. When the editing data can't be read, the file pastes its page as before (`clipboard.importPdf {editingData}`). The objects of a hidden layer come in hidden, from a pasted EPS too. - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). From 6c74a77a6d460a73f762cac8e06631a56a1f6b28 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:13:13 -0800 Subject: [PATCH 31/41] Eraser: an Alt-drag erases everything inside a marquee, a square with Shift With Alt held at the press, an Eraser drag draws a marquee from the press point to the pointer instead of a stroke, and the release erases everything inside it. Alt+Shift keeps the marquee square on its larger side, Escape cancels it, and a click or a drag along one axis erases nothing. path.eraseRegion takes {rect: [x, y, width, height]} in place of points. Closed paths lose the rectangle's area; open paths are cut where they cross its edges, found from the exact crossings, so a narrow rectangle across a long segment still cuts it. A width or height of 0 or less, a non-finite value, or points and rect together is an error, and nothing erased adds no undo step. Docs: docs/mcp.md, docs/ui-parity.md. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/cut.rs | 82 +++++++++++++++++++++++-- crates/engine/src/tests/draw2.rs | 78 +++++++++++++++++++++++ crates/tools/src/draw2/gesture.rs | 74 ++++++++++++++++++++++ crates/tools/src/draw2/gesture/tests.rs | 76 +++++++++++++++++++++++ docs/mcp.md | 9 +++ docs/ui-parity.md | 1 + 7 files changed, 315 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 49e277e5a0..38ac35c61a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 64b8bdee16..fca15e46c5 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -3,9 +3,10 @@ use super::common::{ samples_param, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ - Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session, + Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; +use kurbo::{CubicBez, Line, PathSeg}; use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation}; use vectorcraft_doc::StrokeLayer; use vectorcraft_tools::draw2::MIN_BRUSH_SIZE; @@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec { /// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment /// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least -/// `step` long is found. -fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { +/// `step` long is found, and also at the parameters `extra` gives for it. +fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let nseg = sp.segment_count(); if nseg == 0 { return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]); @@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot()); let wanted = (3.0 * edge / step).ceil(); let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K }; + let mut ts: Vec = (1..=samples).map(|k| k as f64 / samples as f64).collect(); + let more = extra(c); + if !more.is_empty() { + ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)); + ts.sort_by(f64::total_cmp); + ts.dedup(); + } let mut prev_t = 0.0; let mut prev_rm = remove(c.eval(0.0)); let mut start = if prev_rm { None } else { Some(0.0) }; @@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio runs.push(std::mem::take(&mut cur)); } } - for k in 1..=samples { - let t = k as f64 / samples as f64; + for t in ts { let rm = remove(c.eval(t)); if rm != prev_rm { let (mut lo, mut hi) = (prev_t, t); @@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio /// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output /// object (one object per piece when the path had a single subpath), or None if unchanged. pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { + erase_outline_at(pd, step, remove, &|_| vec![]) +} + +/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it. +fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let mut changed = false; let mut subs = vec![]; for sp in &pd.subpaths { - match cut_subpath(sp, step, remove) { + match cut_subpath(sp, step, remove, extra) { Some(pieces) => { changed = true; subs.extend(pieces); @@ -274,6 +286,12 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseRegion"; + if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) { + if p.get("points").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "give `points` or `rect`, not both")); + } + return erase_rect(s, marquee_param(rect, C)?); + } let samples = samples_param(p, "points", C)?; let size = number_or(p, "size", 10.0, C)?; if !(size.is_finite() && size > 0.0) { @@ -325,6 +343,58 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { apply_plan(s, "Eraser", plan) } +/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a +/// height above 0. +fn marquee_param(v: &Value, cmd: &str) -> Result { + const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0"; + let n: Vec = match v.as_array() { + Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::>().ok_or_else(|| bad(cmd, SHAPE))?, + _ => return Err(bad(cmd, SHAPE)), + }; + let [x, y, w, h] = [n[0], n[1], n[2], n[3]]; + if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) { + return Err(bad(cmd, SHAPE)); + } + Ok(Rect::new(x, y, x + w, y + h)) +} + +/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or +/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges. +fn erase_rect(s: &mut Session, r: Rect) -> Result { + let region = + PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true)); + let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1; + // An open path is sampled at least every half of the rectangle's shorter side, and also where + // each segment crosses the rectangle's edges and halfway between those crossings, so a stretch + // inside the rectangle is found however long the segment is. + let step = r.width().min(r.height()) / 2.0; + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + let crossings = |c: CubicBez| { + let mut ts: Vec = (0..4) + .flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4]))) + .map(|x| x.segment_t) + .filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0) + .collect(); + ts.sort_by(f64::total_cmp); + let mids: Vec = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect(); + ts.extend(mids); + ts + }; + let st = s.doc()?; + let mut plan: Vec<(NodeId, Vec)> = vec![]; + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? { + if pd.is_closed() { + if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { + continue; + } + plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); + } else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) { + plan.push((id, pieces)); + } + } + apply_plan(s, "Eraser", plan) +} + /// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and /// `sizeMode`. const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 45ff1f84c1..7698b9d2a7 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1337,6 +1337,84 @@ fn eraser_removes_small_shape_entirely() { assert!(paths(&s).is_empty()); } +/// `path.eraseRegion {rect}` (the Eraser's Alt-drag marquee) erases everything inside the +/// rectangle: a closed shape loses its area, an open path is cut where it crosses the edges, a +/// shape wholly inside goes, and only the selected paths take part when something is selected. One +/// undo step puts everything back, and a rectangle that touches nothing adds no undo step. +#[test] +fn erase_region_rect_erases_everything_inside_it() { + let filled = |s: &Session, x: f64, y: f64| { + paths(s).iter().any(|(_, pd)| pd.is_closed() && vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y))) + }; + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + rect(&mut s, 180.0, 140.0, 10.0, 10.0); + line(&mut s, 50.0, 150.0, 350.0, 150.0); + s.execute("select.none", &json!({})).unwrap(); + let undo = undo_steps(&s); + let r = s.execute("path.eraseRegion", &json!({"rect": [150, 120, 100, 60]})).unwrap(); + assert!(!r["ids"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!filled(&s, 200.0, 150.0) && !filled(&s, 185.0, 145.0), "the area inside is erased, the small square with it"); + assert!(filled(&s, 120.0, 150.0) && filled(&s, 200.0, 250.0) && filled(&s, 200.0, 110.0), "the rest stays filled"); + let ps = paths(&s); + assert_eq!(ps.iter().filter(|(_, pd)| pd.is_closed()).count(), 1, "the square keeps the rectangle as a hole: {ps:?}"); + let open: Vec = ps.iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2, "the line is cut in two: {open:?}"); + assert!(open.iter().all(|l| (l - 100.0).abs() < 0.01), "{open:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paths(&s).len(), 3); + assert!(filled(&s, 200.0, 160.0) && filled(&s, 185.0, 145.0)); + // A rectangle away from the art erases nothing and adds no undo step. + let undo = undo_steps(&s); + assert_eq!(s.execute("path.eraseRegion", &json!({"rect": [500, 500, 10, 10]})).unwrap(), json!({"ids": []})); + assert_eq!(undo_steps(&s), undo); + // With the line selected, only the line is erased. + let ln = paths(&s).into_iter().find(|(_, pd)| !pd.is_closed()).unwrap().0; + s.execute("select.set", &json!({"ids": [ln.0]})).unwrap(); + let closed: Vec = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + s.execute("path.eraseRegion", &json!({"rect": [90, 100, 30, 100]})).unwrap(); + let after: Vec = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + assert_eq!(after, closed, "the unselected squares are unchanged"); + let open: Vec = paths(&s).iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2); + assert!((open.iter().sum::() - 270.0).abs() < 0.01, "{open:?}"); +} + +/// A narrow `path.eraseRegion {rect}` across a long open path cuts it, wherever the rectangle +/// falls between the samples the path's length would give. +#[test] +fn erase_region_rect_cuts_a_long_line_with_a_narrow_rectangle() { + let mut s = session(); + line(&mut s, 0.0, 100.0, 10000.0, 100.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("path.eraseRegion", &json!({"rect": [5000.3, 90, 1, 20]})).unwrap(); + let mut open: Vec = paths(&s).iter().map(|(_, pd)| pd.length()).collect(); + open.sort_by(f64::total_cmp); + assert_eq!(open.len(), 2, "{open:?}"); + assert!((open[0] - 4998.7).abs() < 0.01 && (open[1] - 5000.3).abs() < 0.01, "{open:?}"); +} + +/// `path.eraseRegion` refuses a `rect` that is not four finite numbers with a width and a height +/// above 0, and `rect` given with `points`, and changes nothing. +#[test] +fn erase_region_rect_refuses_bad_values() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let shape = "rect is [x, y, width, height] in points, with a width and a height above 0"; + for p in [ + json!({"rect": [10, 10, 0, 20]}), + json!({"rect": [10, 10, 20, -5]}), + json!({"rect": [10, 10, 20]}), + json!({"rect": [10, "10", 20, 20]}), + json!({"rect": [1e308, 0, 1e308, 20]}), + json!({"rect": {"x": 10, "y": 10, "width": 20, "height": 20}}), + ] { + refuses_with(&mut s, "path.eraseRegion", &p, shape); + } + refuses_with(&mut s, "path.eraseRegion", &json!({"rect": [10, 10, 20, 20], "points": [[0, 0]]}), "give `points` or `rect`, not both"); +} + /// #4495: the Eraser cuts a compound path as one shape: its hole stays empty, the erased area is /// empty, and the rest stays filled, with either fill rule. A notch inside the ring keeps one /// compound path; a drag through the whole ring leaves compound paths whose holes stay holes. diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index a1f1785923..b732fef063 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -22,6 +22,8 @@ //! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths. //! Alt held at a Paintbrush press with a selected path also smooths; Alt pressed after its stroke //! begins closes the path on release. +//! Alt held at the Eraser's press draws a marquee instead of a stroke, a square while Shift is +//! held, and the release erases everything inside it. //! Alt held at the Knife's press makes it cut along the straight line from the press point to the //! pointer, even if Alt is released during the drag. Shift on each drag or release constrains that //! line to 45° steps from the canvas axes. @@ -163,6 +165,11 @@ pub struct GestureTool { /// The pointer has moved from the press point, by any distance (a move too short to add a /// point counts). moved: bool, + /// Active Eraser drag draws a marquee (Alt held at the press): the release erases the + /// rectangle from the press point to the pointer, a square while Shift is held. + marquee: bool, + /// Shift was held at the last event of the Eraser's marquee drag. + square: bool, /// Active Pencil drag draws a straight line (Shift or Alt held at the press), or active Knife /// drag cuts along one (Alt held at the press): the stroke is the press point and the pointer. straight: bool, @@ -867,6 +874,8 @@ impl GestureTool { smooth_fidelity: SMOOTH_FIDELITY, smoothing: false, moved: false, + marquee: false, + square: false, straight: false, unconstrained: false, shift_line: None, @@ -980,6 +989,11 @@ impl GestureTool { self.id == "blobBrush" && m.alt && !self.moved } + /// Would a press with `m` held draw the Eraser's marquee? Alt held at the press. + fn alt_marquee(&self, m: Mods) -> bool { + self.id == "eraser" && m.alt + } + /// Shift keeps an active straight Knife cut at 45° steps; without Shift it follows the pointer. /// Releasing Alt does not end a straight cut. fn knife_shift(&mut self, m: Mods) { @@ -1043,6 +1057,43 @@ impl GestureTool { ] } + /// The Eraser's marquee: the rectangle from the press point to the pointer, or with Shift held + /// the square on the larger of its sides, in the direction the pointer went. `None` outside a + /// marquee drag. + fn marquee_rect(&self) -> Option { + let (&a, &b) = (self.points.first()?, self.points.last()?); + if !self.marquee { + return None; + } + let d = b - a; + let b = if self.square { + let side = d.x.abs().max(d.y.abs()); + a + Vec2::new(side.copysign(d.x), side.copysign(d.y)) + } else { + b + }; + Some(Rect::from_points(a, b)) + } + + /// A drag or the release of the Eraser's marquee: the marquee runs from the press point to the + /// pointer, and the release erases it. `None` for any other event. + fn marquee_pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + if !(self.active && self.marquee && matches!(ev.kind, PointerKind::Drag | PointerKind::Up)) { + return None; + } + self.square = ev.mods.shift; + self.points.truncate(1); + self.points.push(ev.pos); + if !matches!(ev.kind, PointerKind::Up) { + return Some(vec![]); + } + let out = self.finish(cx, ev.mods); + self.active = false; + self.marquee = false; + self.clear(); + Some(out) + } + /// Forget the stroke. fn clear(&mut self) { self.moved = false; @@ -1329,6 +1380,13 @@ impl GestureTool { } return vec![]; } + if let Some(r) = self.marquee_rect() { + // A click, or a drag along one axis, encloses no area: nothing is erased. + if r.width() <= 0.0 || r.height() <= 0.0 || r.width().max(r.height()) < cx.tol(1.0) { + return vec![]; + } + return vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [r.x0, r.y0, r.width(), r.height()]}))]; + } match self.id { "pencil" | "paintbrush" => { if !self.began { @@ -1404,6 +1462,9 @@ impl Tool for GestureTool { if self.varies_size() { self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p); } + if let Some(out) = self.marquee_pointer(cx, ev) { + return out; + } match ev.kind { PointerKind::Down => { self.active = true; @@ -1420,6 +1481,9 @@ impl Tool for GestureTool { // too, the line keeps Shift's 45° steps. Alt makes the Knife cut along a straight line. self.straight = (self.id == "pencil" && !self.smoothing && (ev.mods.shift || ev.mods.alt)) || (self.id == "knife" && ev.mods.alt); self.unconstrained = self.straight && !ev.mods.shift; + // Alt makes the Eraser draw a marquee, and Shift keeps it square. + self.marquee = self.alt_marquee(ev.mods); + self.square = ev.mods.shift; let extend = if self.draws_path() && !self.smoothing { self.find_extend(cx, p) } else { None }; self.set_extend(cx, extend); // The stroke's previews select the path it continues, so the others are kept now. @@ -1601,6 +1665,7 @@ impl Tool for GestureTool { self.smoothing = false; self.straight = false; self.unconstrained = false; + self.marquee = false; self.clear(); if began { vec![Action::Cancel] } else { vec![] } } @@ -1633,6 +1698,7 @@ impl Tool for GestureTool { self.smoothing = false; self.straight = false; self.unconstrained = false; + self.marquee = false; self.clear(); if began { stale.into_iter().chain([Action::Commit]).collect() } else { vec![] } } @@ -1640,6 +1706,14 @@ impl Tool for GestureTool { self.area_pending.set(false); self.band_pending.set(false); let mut o = self.snap.guides().to_vec(); + // The Eraser's marquee shows without the tip outline. + if self.active + && self.points.len() >= 2 + && let Some(r) = self.marquee_rect() + { + o.push(Overlay::Marquee(r)); + return o; + } // A path being drawn shows itself, except with the Pencil's Live preview off. if !self.active || self.points.len() < 2 || (self.began && self.previews()) { o.extend(self.tip_outline(cx)); diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 9dfbdba2de..0d7d06427e 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2032,6 +2032,82 @@ fn eraser_and_knife_exec_on_release() { assert!(matches!(&a[0], Action::Exec(c, v) if c == "path.knife" && v["points"].as_array().unwrap().len() == 3)); } +/// An Alt-drag with the Eraser shows a marquee from the press point to the pointer, without the +/// tip outline, and the release erases that rectangle; a drag back up and left gives the same +/// kind of rectangle, measured from its top-left corner. +#[test] +fn eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 170.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 190.0).with_mods(alt)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(50.0, 150.0, 250.0, 190.0))]); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 200.0).with_mods(alt)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [50.0, 150.0, 200.0, 50.0]}))]); + assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_)))); + // A click erases nothing. + let acts = drag_held(&mut t, &cx, &[(250.0, 200.0)], alt); + assert!(acts.iter().all(Vec::is_empty), "a click: {acts:?}"); + // Alt only at the press is enough, and the drag can go up and left of the press point. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 250.0, 200.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 120.0)); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 120.0)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 120.0, 150.0, 80.0]}))]); + // Without Alt the drag is a stroke. + let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default()); + assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v.get("rect").is_none() && v["points"].is_array())); +} + +/// Alt+Shift keeps the Eraser's marquee square on its larger side, in the direction the pointer +/// went; Shift can be pressed or let go during the drag. +#[test] +fn eraser_alt_shift_drag_keeps_the_marquee_square() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let alt_shift = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(alt_shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt_shift)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 140.0, 260.0, 200.0))]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 170.0, 260.0, 200.0))], "Shift let go"); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 190.0, 280.0).with_mods(alt_shift)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [120.0, 200.0, 80.0, 80.0]}))]); + // A drag along one axis gives a square too. + let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 140.0)], alt_shift); + assert_eq!(acts[2], vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 100.0, 40.0, 40.0]}))]); +} + +/// A marquee that encloses no area erases nothing, and Escape during the drag cancels the marquee: +/// the release that follows sends nothing. +#[test] +fn eraser_marquee_click_or_escape_erases_nothing() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 160.0)], alt); + assert!(acts.iter().all(Vec::is_empty), "a drag along one axis: {acts:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(alt)); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![]); + assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_)))); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(alt)), vec![]); + // The next plain drag erases a stroke. + let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default()); + assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v["points"].is_array())); +} + /// The points of the Knife's release command. fn knife_points(acts: &[Action]) -> Vec<(f64, f64)> { let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..d23f7aa3c4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5748,6 +5748,15 @@ The command refuses another mode, and a variation below 0 or past its range, and the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases. `tool.setOption {tool: "eraser"}` takes the same keys. +`path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside +it from the paths (selected, or all), as an Alt-drag with the Eraser does ([Eraser tool +reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133)). +Closed shapes lose the rectangle's area, and open paths are cut where they cross its edges. The tip's size, angle, +roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or +`points` and `rect` together is refused, and when nothing is erased no undo step is added. In the desktop app an +Alt-drag with the Eraser draws the marquee from the press point to the pointer, Alt+Shift keeps it square on its +larger side, and Escape cancels it. + These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, naming the key; the document does not change and no undo step is recorded: `t`, `dx` and `dy` in `path.reshapeSegment` and `object.blend.spine.reshapeSegment`; `x`, `y` and `t` in `path.curvatureEdit`; `x` and `y` diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 071c8d4719..0a88043c3e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -169,6 +169,7 @@ tools, never checked side by side) isn't captured row by row. | Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | | Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | +| Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes lose the rectangle's area, open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` | | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | From 4f874088fc6621fe7dd5ca892ab379c13d59c662 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:13:38 -0800 Subject: [PATCH 32/41] Variables: compare the marked Data Set rows by name in the rename test egui builds the accessibility update's node list from a hash map, so the order of the open list's rows in it is not the display order. The test sorts the rows by name before checking that only Spring is marked. --- crates/ui-egui/src/panels/variables.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 4005c7f48f..b85f08a9c2 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -633,8 +633,10 @@ mod tests { let text = crate::tests_labels::painted_text(&mut app, show); assert!(text.contains("Spring"), "{text}"); let rows = d.open_data_set_list(&mut app); - let marked: Vec<(Option<&str>, bool)> = rows.iter().map(|n| (n.label(), n.toggled() == Some(egui::accesskit::Toggled::True))).collect(); - assert_eq!(marked, [(Some("Spring"), true), (Some("Data Set 2"), false)]); + // The accessibility update lists nodes in hash-map order, so the rows are compared by name. + let mut marked: Vec<(Option<&str>, bool)> = rows.iter().map(|n| (n.label(), n.toggled() == Some(egui::accesskit::Toggled::True))).collect(); + marked.sort(); + assert_eq!(marked, [(Some("Data Set 2"), false), (Some("Spring"), true)]); let other = rows.iter().find(|n| n.label() == Some("Data Set 2")).expect("the Data Set 2 row").clone(); d.click(&mut app, &other); assert_eq!(app.session.active().unwrap().doc.variables.active_dataset.as_deref(), Some("Data Set 2")); From 24c0f89ff9cd1e66c47f582641f1f8a553a53bc2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:41:36 -0800 Subject: [PATCH 33/41] Part of #7840: the Ellipse dialog sets how many anchors the ellipse has A click with the Ellipse tool opens a dialog with a new Anchors field under Height, 4 by default. With 4, OK draws the same live ellipse as before. Any other count from 2 to 1000 draws a closed plain path with that many smooth anchors spaced evenly by angle, from the left one and clockwise, with handles of 4/3*tan(theta/4) scaled along each axis and the path fitted to the typed width and height. The dialog sends the nearest whole number from 2 to 1000 (4 for an empty field or text that is not a number). The count confirmed last is kept as the Ellipse tool's anchors option, and the next Ellipse dialog opens on it. shape.ellipse takes an optional anchors param (default 4). A number that is not a whole number from 2 to 1000 gets one error naming that range, a value that is not a number gets the usual type error, and nothing is drawn. The MCP draw_shape tool lists anchors for ellipses. Docs: params text, docs/mcp.md, docs/target-app-parity.md (Shapes). --- crates/engine/src/cmd/create.rs | 24 +++++- crates/engine/src/tests.rs | 79 ++++++++++++++++++++ crates/engine/src/tests/constrain_new.rs | 19 +++++ crates/engine/src/tests/persp_text.rs | 16 ++++ crates/geom/src/shapes.rs | 55 ++++++++++++++ crates/mcp/src/tools/definitions.rs | 3 +- crates/tools/src/settings.rs | 2 + crates/tools/src/shape.rs | 6 ++ crates/ui-egui/src/dialogs/shapes.rs | 95 +++++++++++++++++++++++- crates/ui-egui/src/dialogs/tools.rs | 6 +- docs/mcp.md | 21 +++++- docs/target-app-parity.md | 1 + 12 files changed, 317 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 08944940a2..5571d24b28 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -26,7 +26,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -362,10 +362,28 @@ fn rectangle(s: &mut Session, p: &Value) -> Result { add_art_turned(s, label, path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) } +/// The most anchors `shape.ellipse` draws, as many as a polygon's sides. +const MAX_ELLIPSE_ANCHORS: u64 = 1000; + fn ellipse(s: &mut Session, p: &Value) -> Result { let r = rect_of(p, "shape.ellipse")?; - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? }; - add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), f64_or(p, "rotation", 0.0)) + // One message for every number that is not a whole count in range (a fraction, a negative, + // 0, 1, too many); a value that is not a number gets `number_or`'s. + let (key, min, max) = ("anchors", 2, MAX_ELLIPSE_ANCHORS); + let n = number_or(p, key, 4.0, "shape.ellipse")?; + if n.fract() != 0.0 || !(min as f64..=max as f64).contains(&n) { + return Err(bad("shape.ellipse", format!("`{key}` must be a whole number between {min} and {max} (got {n})"))); + } + let x = n as u64; + let xf = rect_transform(r, p, "shape.ellipse")?; + let rotation = f64_or(p, "rotation", 0.0); + if x != 4 { + // Another count is a plain path: a live ellipse always has 4 anchors. + let path = shapes::ellipse_with_anchors(Rect::new(0.0, 0.0, r.width(), r.height()), x as u32).transformed(xf); + return add_art_turned(s, "Ellipse", path_kind(path, None), rotation); + } + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf }; + add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b420d7805..64a551e872 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3310,6 +3310,85 @@ fn flare_ring_seed_moves_only_the_rings() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew. +#[test] +fn ellipse_with_four_anchors_is_the_live_ellipse() { + let mut s = session(); + let draw = |s: &mut Session, extra: Option| { + let mut p = json!({"x": 40, "y": 30, "width": 120, "height": 80}); + if let Some(n) = extra { + p["anchors"] = json!(n); + } + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + s.doc().unwrap().doc.node(id).unwrap().clone() + }; + let (plain, four) = (draw(&mut s, None), draw(&mut s, Some(4))); + for n in [&plain, &four] { + assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape()); + assert_eq!(n.path_data().unwrap().anchor_count(), 4); + } + assert_eq!(plain.path_data(), four.path_data()); + assert_eq!(plain.live_shape(), four.live_shape()); +} + +/// Any other count draws a closed plain path of that many smooth anchors on the ellipse, its +/// bounds the typed size, as one undo step. +#[test] +fn ellipse_anchors_draw_that_many_anchors_on_the_ellipse() { + let mut s = session(); + let (x, y, w, h) = (40.0, 30.0, 120.0, 80.0); + let (c, rx, ry) = (Point::new(x + w / 2.0, y + h / 2.0), w / 2.0, h / 2.0); + for n in [2u64, 3, 5, 6, 8] { + let undo = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": n})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{n}: one undo step"); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(node.live_shape().is_none(), "{n}: a plain path"); + let path = node.path_data().unwrap(); + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(sp.closed, "{n}"); + assert_eq!(sp.anchors.len() as u64, n); + for a in &sp.anchors { + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth, "{n}"); + let on = ((a.p.x - c.x) / rx).powi(2) + ((a.p.y - c.y) / ry).powi(2); + assert!((on - 1.0).abs() < 0.01, "{n}: {:?} is off the ellipse ({on})", a.p); + } + let b = path.bounds().unwrap(); + for (got, want) in [(b.x0, x), (b.y0, y), (b.x1, x + w), (b.y1, y + h)] { + assert!((got - want).abs() < 1e-6, "{n}: bounds {b:?}"); + } + } + // The first anchor is the left one, and they run clockwise on screen, as the live ellipse's do. + let id = NodeId(s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": w, "height": h, "anchors": 8})).unwrap()["id"].as_u64().unwrap()); + let sp = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + assert!(sp.anchors[0].p.distance(Point::new(x, c.y)) < 1e-6, "{:?}", sp.anchors[0].p); + assert!(sp.anchors[2].p.distance(Point::new(c.x, y)) < 1e-6, "{:?}", sp.anchors[2].p); +} + +/// An `anchors` that is not a whole number from 2 to 1000 is refused, and nothing is drawn. +#[test] +fn ellipse_refuses_a_bad_anchor_count() { + let mut s = session(); + let undo = s.doc().unwrap().history.undo.len(); + let range = |got: &str| format!("`anchors` must be a whole number between 2 and 1000 (got {got})"); + for (bad, want) in [ + (json!(0), range("0")), + (json!(1), range("1")), + (json!(2.5), range("2.5")), + (json!(-3), range("-3")), + (json!(1001), range("1001")), + (json!("x"), "`anchors` must be a number, not \"x\"".to_string()), + (json!("6"), "`anchors` must be a number, not \"6\"".to_string()), + (json!(true), "`anchors` must be a number, not true".to_string()), + ] { + let e = s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50, "anchors": bad})).unwrap_err().to_string(); + assert!(e.contains(&want), "{bad}: {e}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + assert!(s.doc().unwrap().doc.layers[0].children().unwrap().is_empty()); +} + /// Through the session, Ctrl/Cmd in the Flare tool's center drag keeps the center's size while the /// drag sizes the halo, and the flare drawn keeps both. #[test] diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index 49fd29e94b..50797e35e3 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -253,6 +253,25 @@ fn constrain_angle_turns_shapes_made_by_a_click() { } } +/// An ellipse of another anchor count made by a click turns along the Constrain Angle like the +/// live ellipse: it keeps its anchors and its box runs along the turned axes from the click. +#[test] +fn constrain_angle_turns_an_ellipse_of_six_anchors_made_by_a_click() { + let mut s = new_doc(); + set_angle(&mut s, 90.0); + let p = json!({"x": 10, "y": 200, "width": 100, "height": 50, "anchors": 6}); + let p = constrain_click(&s, "shape.ellipse", p.clone(), corner(&p)); + assert_eq!(p["anchors"], json!(6)); + let id = NodeId(s.execute("shape.ellipse", &p).unwrap()["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.live_shape().is_none()); + assert_eq!(n.path_data().unwrap().anchor_count(), 6); + let b = bounds(&s, id); + for (got, want) in [(b.x0, 10.0), (b.y0, 100.0), (b.x1, 60.0), (b.y1, 200.0)] { + assert!(close(got, want), "{b:?}"); + } +} + /// The Line Segment tool's Shift steps of 45° count from the Constrain Angle. #[test] fn constrain_angle_steps_the_line_segment_tool() { diff --git a/crates/engine/src/tests/persp_text.rs b/crates/engine/src/tests/persp_text.rs index b5dc5e7a53..443913a635 100644 --- a/crates/engine/src/tests/persp_text.rs +++ b/crates/engine/src/tests/persp_text.rs @@ -399,6 +399,22 @@ fn click_to_size_dialogs_draw_on_the_active_plane_in_plane_units() { assert!(crate::perspective_click(&s, "shape.rectangle", &json!({}), at).is_none()); } +/// The Ellipse dialog's anchor count reaches the ellipse drawn on the active plane. +#[test] +fn an_ellipse_of_six_anchors_made_by_a_click_draws_on_the_active_plane() { + let (mut s, _) = persp_session(); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap(); + let at = Point::new(470.0, 300.0); + let p = json!({"x": at.x, "y": at.y, "width": 50, "height": 30, "anchors": 6}); + let (cmd, p) = crate::perspective_click(&s, "shape.ellipse", &p, at).unwrap(); + let n = undo_len(&s); + let id = NodeId(s.execute(&cmd, &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(attached(&s, id).map(|a| a.0), Some(Plane::Right)); + assert_eq!(node(&s, id).path_data().unwrap().anchor_count(), 6); +} + #[test] fn the_canvas_draws_type_in_perspective_foreshortened() { let (mut s, rect) = persp_session(); diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 0ae8a75190..5bebc07384 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -103,6 +103,38 @@ pub fn ellipse(r: Rect) -> PathData { PathData::single(SubPath::new(anchors, true)) } +/// Ellipse inscribed in `r` with `n` smooth anchors (at least 2) spaced evenly by angle, clockwise +/// on screen from the left one, as [`ellipse`] runs. Each segment is a cubic whose handles are +/// 4/3·tan(θ/4) of the tangent at its ends (θ = 360°/`n`), scaled along each axis; the path is then +/// fitted to `r`, so its bounds are `r` whatever the count. 4 anchors give [`ellipse`]. +pub fn ellipse_with_anchors(r: Rect, n: u32) -> PathData { + let n = n.max(2); + let r = r.abs(); + let c = r.center(); + let (rx, ry) = (r.width() / 2.0, r.height() / 2.0); + let step = TAU / f64::from(n); + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let anchors = (0..n) + .map(|i| { + // From the left anchor (angle π). With y down, sin is negative just past π, so the next + // anchor is above the centre: left, then top, then right, as `ellipse` runs. + let a = PI + step * f64::from(i); + let p = Point::new(c.x + rx * a.cos(), c.y + ry * a.sin()); + let d = Vec2::new(-rx * a.sin(), ry * a.cos()) * k; + Anchor { p, h_in: p - d, h_out: p + d, kind: AnchorKind::Smooth } + }) + .collect(); + let path = PathData::single(SubPath::new(anchors, true)); + // Between anchors a curve can reach a little past the ellipse or stop short of it (0.15% of + // the height with 3 anchors): fit the bounds to `r` along each axis that has a size. + let Some(b) = path.bounds() else { return path }; + let fit = |want: f64, got: f64| if want > 0.0 && got > 0.0 { want / got } else { 1.0 }; + let (sx, sy) = (fit(r.width(), b.width()), fit(r.height(), b.height())); + path.transformed( + kurbo::Affine::translate(r.origin().to_vec2()) * kurbo::Affine::scale_non_uniform(sx, sy) * kurbo::Affine::translate(-b.origin().to_vec2()), + ) +} + /// How an ellipse or shape arc is closed or left open when cut between start and end angles. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -693,6 +725,29 @@ mod tests { assert!((area - PI * 50.0 * 30.0).abs() / area < 0.001); } + #[test] + fn ellipse_with_four_anchors_is_the_ellipse_and_others_fit_the_box() { + let r = Rect::new(10.0, 20.0, 110.0, 80.0); + let (four, plain) = (ellipse_with_anchors(r, 4), ellipse(r)); + for (a, b) in four.subpaths[0].anchors.iter().zip(&plain.subpaths[0].anchors) { + assert!(a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9 && a.h_out.distance(b.h_out) < 1e-9, "{a:?} {b:?}"); + } + for n in [2, 3, 5, 7, 9, 1000] { + let p = ellipse_with_anchors(r, n); + assert_eq!(p.anchor_count(), n as usize); + let b = p.bounds().unwrap(); + assert!( + (b.x0 - r.x0).abs() < 1e-9 && (b.y0 - r.y0).abs() < 1e-9 && (b.x1 - r.x1).abs() < 1e-9 && (b.y1 - r.y1).abs() < 1e-9, + "{n}: {b:?}" + ); + let area = p.subpaths[0].area().abs(); + assert!((area - PI * 50.0 * 30.0).abs() / area < if n == 2 { 0.1 } else { 0.01 }, "{n}: {area}"); + } + // A box with no height leaves the path flat rather than dividing by zero. + let flat = ellipse_with_anchors(Rect::new(0.0, 5.0, 40.0, 5.0), 6); + assert!(flat.subpaths[0].anchors.iter().all(|a| a.p.y == 5.0 && a.p.x.is_finite())); + } + #[test] fn rounded_rect_clamps() { let p = rounded_rectangle(Rect::new(0.0, 0.0, 20.0, 10.0), 100.0); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 4b55d6aff1..e549c2a362 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -244,7 +244,7 @@ pub fn tool_definitions() -> Vec { tool( "draw_shape", "Draw shape", - "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", + "Create a live shape and apply optional paint. rectangle/ellipse: x, y, width, height (rectangle: radius = corner radius; ellipse: anchors, default 4, where any other count from 2 to 1000 draws a plain path rather than a live shape). polygon: cx, cy, radius, sides. star: cx, cy, radius1, radius2, points. line: x1, y1, x2, y2. Omitted paint fields inherit the current new-art appearance (initially white fill and 1 pt black stroke); lines start with no fill and a visible stroke. For a filled shape without an outline, pass an explicit fill and stroke:\"none\". Stroke dash/cap/join, opacity, name and live effects apply to the new shape as in draw_path. Returns the new object id.", obj( with_draw_options(json!({ "shape": {"type": "string", "enum": ["rectangle", "ellipse", "polygon", "star", "line"]}, @@ -253,6 +253,7 @@ pub fn tool_definitions() -> Vec { "width": num("Width (rectangle/ellipse)"), "height": num("Height (rectangle/ellipse)"), "radius": num("Corner radius (rectangle) or radius (polygon)"), + "anchors": {"type": "integer", "minimum": 2, "maximum": 1000, "description": "Ellipse anchors, spaced evenly by angle (default 4, a live ellipse; any other count draws a plain path)"}, "cx": num("Centre x (polygon/star)"), "cy": num("Centre y (polygon/star)"), "sides": {"type": "integer", "minimum": 3, "description": "Polygon sides (default 6)"}, diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index a5c92b00b0..97e980e3c0 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -51,6 +51,8 @@ const ROWS: &[Row] = &[ (&["livePaintBucket"], None, &["paintFills", "paintStrokes", "cursorSwatchPreview", "highlight", "color", "width"]), (&["polygon"], None, &["sides"]), (&["star"], None, &["points"]), + // The Ellipse dialog's Anchors. + (&["ellipse"], None, &["anchors"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..9eda809c03 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -84,6 +84,9 @@ pub struct ShapeTool { began: bool, pub sides: u32, pub points: u32, + /// The anchors an ellipse made by a click has (the Ellipse dialog opens on it); 4 is a live + /// ellipse. + pub anchors: u32, pub corner_radius: f64, /// Star inner radius as a fraction of the outer radius. pub star_ratio: f64, @@ -146,6 +149,7 @@ impl ShapeTool { began: false, sides: 6, points: 5, + anchors: 4, corner_radius: 12.0, star_ratio: 0.5, inner: None, @@ -787,6 +791,7 @@ impl Tool for ShapeTool { json!({ "sides": self.sides, "points": self.points, + "anchors": self.anchors, "cornerRadius": self.corner_radius, "starRatio": self.star_ratio, "length": self.line_length, @@ -799,6 +804,7 @@ impl Tool for ShapeTool { match key { "sides" => self.sides = v.as_u64().unwrap_or(6).clamp(3, 1000) as u32, "points" => self.points = v.as_u64().unwrap_or(5).clamp(3, 1000) as u32, + "anchors" => self.anchors = v.as_u64().unwrap_or(4).clamp(2, 1000) as u32, "cornerRadius" => self.corner_radius = finite.unwrap_or(12.0).clamp(0.0, MAX_CORNER_RADIUS), "starRatio" => self.star_ratio = v.as_f64().unwrap_or(0.5).clamp(0.01, 1.0), "length" => self.line_length = finite.map_or(self.line_length, |n| n.abs().min(1e6)), diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 392c043f35..b807bc5274 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -306,6 +306,9 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { if d.kind == "roundedRectangle" { form::length_field(ui, d, "radius", &form::humanized("radius"), unit); } + if d.kind == "ellipse" { + form::field(ui, d, "anchors", "Anchors:"); + } }); let Some(rows) = rows else { return }; let on = d.bool(LINK); @@ -358,6 +361,13 @@ fn follow_link(d: &mut Dialog, typed: &str) { } } +/// The Ellipse dialog's Anchors: the nearest whole number from 2 to 1000 (4, a live ellipse, when +/// left empty or not a number). +fn ellipse_anchors(d: &Dialog) -> u64 { + let n = d.f64("anchors", 4.0); + if n.is_finite() { n.round().clamp(2.0, 1000.0) as u64 } else { 4 } +} + /// The top-left corner of a rectangle or ellipse: the click itself, or with Alt held (draw from centre) the click minus half the size. fn box_origin(d: &Dialog) -> (f64, f64) { let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); @@ -386,11 +396,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values[key] = json!(d.f64(key, default).clamp(min, 1000.0) as u64); values }) + .or_else(|| (d.kind == "ellipse").then(|| json!({"anchors": ellipse_anchors(d)}))) .or_else(|| OPTION_TOOLS.contains(&d.kind.as_str()).then(|| tool_options(d))); let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); let (bx, by) = box_origin(d); let (id, params) = match d.kind.as_str() { - "ellipse" => ("shape.ellipse", json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0)})), + "ellipse" => ( + "shape.ellipse", + json!({"x": bx, "y": by, "width": d.f64("width", 100.0), "height": d.f64("height", 100.0), "anchors": ellipse_anchors(d)}), + ), "polygon" => ("shape.polygon", json!({"cx": x, "cy": y, "radius": d.f64("radius", 50.0), "sides": d.f64("sides", 6.0) as u64})), "star" => ( "shape.star", @@ -649,6 +663,85 @@ mod tests { assert!((b.width() - 80.0).abs() < 1e-6 && (b.height() - 40.0).abs() < 1e-6, "{b:?}"); } + /// The Ellipse dialog opens with Anchors 4, which draws a live ellipse; OK with 6 draws a plain + /// path of 6 anchors, and the next Ellipse dialog opens on 6. + #[test] + fn the_ellipse_dialog_draws_and_keeps_its_anchor_count() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("tool.select", json!({"tool": "ellipse"})).unwrap(); + let last = |app: &VectorcraftApp| { + let doc = &app.session.doc().unwrap().doc; + doc.layers[0].children().unwrap().last().cloned().expect("an ellipse") + }; + + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 4.0); + super::super::confirm(&mut app).unwrap(); + let n = last(&app); + assert!(matches!(n.live_shape(), Some(vectorcraft_doc::LiveShape::Ellipse { .. })), "{:?}", n.live_shape()); + + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 150.0, "y": 150.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("anchors".into(), json!("6")); + super::super::confirm(&mut app).unwrap(); + let n = last(&app); + assert!(n.live_shape().is_none()); + assert_eq!(n.path_data().unwrap().anchor_count(), 6); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 100.0).abs() < 1e-6 && (b.height() - 100.0).abs() < 1e-6, "{b:?}"); + + // Kept as the Ellipse tool's `anchors` option for the next click, after another tool too. + assert_eq!(app.session.tool_options_of("ellipse")["anchors"], json!(6)); + app.run("tool.select", json!({"tool": "rectangle"})).unwrap(); + app.run("tool.select", json!({"tool": "ellipse"})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); + app.ui.dialog = None; + // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. + for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { + app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); + app.ui.dialog = None; + } + } + + /// The dialog's Anchors field is named, under Height, and typing into it sets the count. + #[test] + fn the_ellipse_dialog_shows_an_anchors_field() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0})); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + h.check_accessibility(); + let height = h.get_by_role_and_label(Role::TextInput, "Height:").rect(); + let anchors = h.get_by_role_and_label(Role::TextInput, "Anchors:").rect(); + assert!(anchors.center().y > height.center().y, "Anchors is below Height: {anchors:?} {height:?}"); + assert_eq!(ellipse_anchors(h.state().ui.dialog.as_ref().unwrap()), 4); + } + + #[test] + fn ellipse_anchors_take_the_nearest_whole_number_from_2_to_1000() { + let d = |v: Value| Dialog::new("ellipse", json!({ "anchors": v })); + for (v, want) in [(json!(6), 6), (json!("7"), 7), (json!(5.6), 6), (json!(1), 2), (json!(0), 2), (json!(-3), 2), (json!(5000), 1000)] { + assert_eq!(ellipse_anchors(&d(v.clone())), want, "{v}"); + } + assert_eq!(ellipse_anchors(&Dialog::new("ellipse", json!({}))), 4); + } + #[test] fn a_negative_line_length_draws_and_keeps_the_same_direction() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 3a8cc570d7..bf65dd4894 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -13,7 +13,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { let y = p.get("y").and_then(Value::as_f64).unwrap_or(0.0); let alt = p.get("alt").and_then(Value::as_bool).unwrap_or(false); let d = match kind { - "rectangle" | "ellipse" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})), + "rectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt"})), + "ellipse" => Dialog::new( + kind, + json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "anchors": app.session.tool_options_of(kind)["anchors"]}), + ), "roundedRectangle" => Dialog::new(kind, json!({"x": x, "y": y, "alt": alt, "width": "100 pt", "height": "100 pt", "radius": "12 pt"})), "polygon" => Dialog::new(kind, json!({"x": x, "y": y, "radius": "50 pt", "sides": app.session.tool_options_of(kind)["sides"]})), "star" => { diff --git a/docs/mcp.md b/docs/mcp.md index b7b4905ef4..22b5e7884b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -667,7 +667,7 @@ sampler. | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | -| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | +| `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners; an ellipse takes `anchors`, 2–1000, default 4). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | @@ -1187,6 +1187,18 @@ pixels per point, and the file stores the resolution that results, as with `ppi` either one wins over `ppi` and `scale`. A value that is not a positive number is refused. Export for Screens rows keep their own size (`scale: "512w"`). +`shape.ellipse` (and `draw_shape` with `shape: "ellipse"`) takes `anchors`, the number of smooth anchors (default 4). +Without it, or at 4, it draws a live ellipse. Any other count from 2 to 1000 draws a closed plain path with that many +anchors spaced evenly by angle, clockwise from the left one and fitted to `width` × `height`. The Ellipse dialog (a +click with the Ellipse tool) has an Anchors field that sends it, as the nearest whole number from 2 to 1000 (an +empty field, or text that is not a number, sends 4). The count confirmed last is kept as the Ellipse tool's `anchors` +option (`tool.setOption`), and the next Ellipse dialog opens on it. A drag with the Ellipse tool still draws a live +ellipse. + +```json +{"name":"run_command","arguments":{"command":"shape.ellipse","params":{"x":100,"y":100,"width":120,"height":80,"anchors":6}}} +``` + Long-tail commands: ```json @@ -2018,9 +2030,10 @@ and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `o `enhanced` in `imageTrace.make` and `imageTrace.makeAndExpand`. A null is read as a key left out. These commands refuse a string or another value that is not a number with `` `radius` must be a number, not "2" ``, -naming the key, and change nothing: `radius` in `shape.rectangle`; `sides` and `rotation` in `shape.polygon`; -`radius2`, `points` and `rotation` in `shape.star`; `diameter`, `opacity`, `brightness`, `growth`, `fuzziness`, -`rays`, `longest`, `rayFuzziness`, `rotation`, `rings`, `largest`, `x2`, `y2`, `direction`, `pathLength`, `seed` and +naming the key, and change nothing: `radius` in `shape.rectangle`; `anchors` in `shape.ellipse` (a number that is +not a whole number from 2 to 1000 gets `` `anchors` must be a whole number between 2 and 1000 (got 2.5) ``); `sides` +and `rotation` in `shape.polygon`; `radius2`, `points` and `rotation` in `shape.star`; `diameter`, `opacity`, +`brightness`, `growth`, `fuzziness`, `rays`, `longest`, `rayFuzziness`, `rotation`, `rings`, `largest`, `x2`, `y2`, `direction`, `pathLength`, `seed` and `ringSeed` in `shape.flare` (`seed` must also be a whole number of at least 0, and `ringSeed` a whole number from 0 to 2^53 - 1); `decay` and `segments` in `shape.spiral`; `rows` and `columns` in `shape.rectangularGrid`; `concentric` and `radial` in `shape.polarGrid`; `size` and the `width`, `height` and `fitMinPercent` of `area` in `text.create`; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..a8f561d875 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1166,6 +1166,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While an arc is dragged out, C switches it between open and closed, F switches its base between the X and Y axes in the same box, and Up/Down raise and lower its slope by 10 within −100…100; each press switches once, and the values stay as the Arc tool's options. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list C, F and Up/Down for an arc being dragged out. F as the base switch, the arrows changing the slope, the step of 10 and one switch per press are our own rules. While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind and Decay as the amount each wind decreases. An 80% spiral has 80% of its outer radius after four segments; newly drawn spirals with the same settings wind more broadly than in earlier VectorCraft builds. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. Escape while an arc, spiral or grid is dragged out cancels it and puts back the options its keys, Alt and Ctrl/Cmd changed (slope, open or closed, base axis, segments, decay, dividers and skews), so the next drag and the tool's options start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. + VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. From 9c5eac0d17707065d0bcb1e3d15e455d39896b2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:19:17 -0800 Subject: [PATCH 34/41] SVG: an artboard's SVG keeps a brushed path whose brush art reaches it An SVG or SVGZ of a chosen artboard left out a brushed path lying just off the artboard even when its brush art painted onto it, as the artboard filter measured the path without room for its brush art. The filter now leaves the room PDF and EPS export leave (vectorcraft_brush::reach_within): none for a brushed stroke without a paint, only the clipping path's for a clip group, and only a compound path's own strokes. --- crates/engine/src/cmd/fileio/export.rs | 12 ++- crates/engine/src/cmd/fileio/tests_svgenc.rs | 103 +++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 113 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index c3249ba408..9a5474b1e6 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -199,8 +199,12 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet 0.0 { b.inflate(reach, reach) } else { b }); + (n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone()) } let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); diff --git a/crates/engine/src/cmd/fileio/tests_svgenc.rs b/crates/engine/src/cmd/fileio/tests_svgenc.rs index d1d9123139..7884c1e86b 100644 --- a/crates/engine/src/cmd/fileio/tests_svgenc.rs +++ b/crates/engine/src/cmd/fileio/tests_svgenc.rs @@ -1,7 +1,10 @@ //! SVG encodings, profiles and embedded fonts through the engine: the options reach the file, //! files in each encoding open again, and `document.serialize` reads them as text. +use std::sync::Arc; + use serde_json::json; +use vectorcraft_doc::Document; use super::*; @@ -109,6 +112,106 @@ fn a_chosen_artboard_s_svg_keeps_an_object_whose_shadow_reaches_it() { assert_eq!(paths(&mut s), 1, "its shadow reaches 10 pt onto the artboard"); } +/// A 100 × 100 document whose 3 pt. Round brush paints with a 20 pt nib, and the left edge of its +/// artboard. +fn nib_doc() -> (Document, f64) { + let mut d = Document::new(100.0, 100.0); + let mut lib = vectorcraft_brush::library(&d); + let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == "3 pt. Round").map(|b| &mut b.kind) else { + panic!("the 3 pt. Round brush") + }; + c.size = 20.0; + vectorcraft_brush::store(&mut d, &lib); + let x0 = d.artboards[0].rect.x0; + (d, x0) +} + +/// A line from (`x`, 40) to (`x`, 60) with a 1 pt stroke in `paint`, painted by the 20 pt nib of +/// [`nib_doc`] when `brushed`: the nib paints 10 pt either side of the line. +fn nib_line(d: &mut Document, x: f64, paint: vectorcraft_color::Paint, brushed: bool) -> vectorcraft_doc::Node { + let mut look = vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, paint, 1.0); + if brushed { + look.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + } + let line = vectorcraft_geom::shapes::line((x, 40.0).into(), (x, 60.0).into()); + vectorcraft_doc::Node::path(d.alloc_id(), line, look) +} + +fn black() -> vectorcraft_color::Paint { + vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) +} + +/// A brushed path just left of a chosen artboard, whose brush art paints onto it, is in that +/// artboard's SVG and SVGZ; a brushed path too far off for its brush art to reach it is not. +#[test] +fn a_chosen_artboard_s_svg_keeps_brush_art_reaching_in() { + let (mut d, x0) = nib_doc(); + let layer = d.layers[0].id; + let near = nib_line(&mut d, x0 - 5.0, black(), true); + let far = nib_line(&mut d, x0 - 200.0, black(), true); + let (near, far) = (d.insert(Some(layer), 0, near).unwrap(), d.insert(Some(layer), 0, far).unwrap()); + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + assert!(kept.node(near).is_some(), "the nib paints 5 pt onto the artboard"); + assert!(kept.node(far).is_none(), "the nib paints 190 pt short of the artboard"); + let mut s = Session::new(); + s.add_document(d, None); + let svg = s.execute("document.serialize", &json!({"format": "svg", "artboard": 0})).unwrap(); + let svg = svg["text"].as_str().unwrap().to_string(); + assert!(vectorcraft_testkit::svg_shapes(&svg) > 0, "{svg}"); + let svgz = s.execute("document.serialize", &json!({"format": "svgz", "artboard": 0})).unwrap(); + let svgz = vectorcraft_format::base64_decode(svgz["dataBase64"].as_str().unwrap()).unwrap(); + assert_eq!(vectorcraft_svg::text_of(&svgz).unwrap(), svg, "the SVGZ is the SVG gzipped"); +} + +/// The room for brush art also keeps a brushed path in a plain group on a sublayer. A brushed +/// stroke without a paint draws no brush art, a clipping group's clip keeps its members' brush art +/// inside it, and a compound path is painted with its own appearance, not its paths': those stay +/// out when only brush art could reach the artboard. +#[test] +fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_art() { + use vectorcraft_doc::{LayerColor, Node, NodeKind}; + let (mut d, x0) = nib_doc(); + let layer = d.layers[0].id; + let x = x0 - 5.0; + // A brushed line in a plain group on a sublayer. + let line = nib_line(&mut d, x, black(), true); + let nested = line.id; + let group = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(line)], clip: false }); + let mut sublayer = Node::layer(d.alloc_id(), "Sublayer", LayerColor::Preset(1)); + sublayer.children_mut().unwrap().push(Arc::new(group)); + d.insert(Some(layer), 0, sublayer).unwrap(); + // A brushed stroke without a paint. + let unpainted = nib_line(&mut d, x, vectorcraft_color::Paint::None, true); + let unpainted = d.insert(Some(layer), 0, unpainted).unwrap(); + // A clipping group whose clip, far left of the artboard, holds a brushed line just off it. + let mut clip = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x0 - 100.0, 40.0, x0 - 90.0, 60.0)), + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0), + ); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let member = nib_line(&mut d, x, black(), true); + let clipped = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(member)], clip: true }); + let clipped = d.insert(Some(layer), 0, clipped).unwrap(); + // Compound paths of a brushed line: plain itself, then brushed itself. + let mut compounds = vec![]; + for own in [false, true] { + let member = nib_line(&mut d, x, black(), true); + let mut compound = + Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: vectorcraft_geom::FillRule::NonZero }); + compound.appearance = nib_line(&mut d, x, black(), own).appearance; + compounds.push(d.insert(Some(layer), 0, compound).unwrap()); + } + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + assert!(kept.node(nested).is_some(), "the brushed line in the group on the sublayer"); + assert!(kept.node(unpainted).is_none(), "a brushed stroke without a paint"); + assert!(kept.node(clipped).is_none(), "a clipping group whose clip misses the artboard"); + assert!(kept.node(compounds[0]).is_none(), "a compound path that is not brushed itself"); + assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself"); +} + /// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset) /// has the artboard's (or asset's) name as ``; Save's SVG and Export for Screens' Full /// Document keep the document's. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..89e41cce30 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2173,6 +2173,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged. - **Painted pieces with brushed strokes are culled and measured by their brush art (G17):** a piece that keeps the object's brushed stroke draws the brush along the piece's own path at the piece's stroke width. Culling leaves VectorCraft's usual room for brush art (16 × the stroke width + 8 pt) past each piece, from the piece's width rather than the object's, and so does culling of a group, layer, symbol instance, blend, envelope or repeat that holds the object. A group or layer also leaves that room for each brushed path among its members, painted or not. Object › Rasterize takes the brush art drawn along each piece and leaves out the object's own brush art, which is not drawn. Pieces without a brush are culled as before. Regressions: `crates/render/src/tests/paintedbrush.rs`. Scores and hours unchanged. - **Brushed paths just off the page are exported and printed:** PDF and EPS export keep a path or compound path whose brush art reaches the page while the path lies just off it, alone or in a group, by leaving the canvas's room for brush art (16 × the widest stroke + 8 pt, VectorCraft's own value) past its box. Skip Blank Artboards keeps an artboard such brush art reaches, and Print with Ignore Artboards frames the page with that room around brushed paths and around instances whose art holds brushed strokes. A clip group leaves room only for its clipping path. Art without brushed strokes is written as before. Regressions: `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/print.rs`, `crates/eps/src/tests.rs`. Scores and hours unchanged. +- **Brushed paths just off an artboard are in its SVG:** the SVG or SVGZ of a chosen artboard (`artboard`, or Use Artboards with a range) keeps a path whose brush art reaches the artboard while the path lies just off it, alone, in a group or on a sublayer, with the room for brush art that PDF and EPS export leave (16 × the widest stroke + 8 pt, VectorCraft's own value). A brushed stroke without a paint gets no room, a clip group leaves room only for its clipping path, and a compound path only for its own strokes. Regressions: `crates/engine/src/cmd/fileio/tests_svgenc.rs`. Scores and hours unchanged. - **Live-effect plug-ins while a document opens (G17):** the live-effect plug-in runs of a document's first view on screen share a 2,000 ms budget (VectorCraft's own value). A stage left out for time, or one that times out, fails, has no plug-in or meets Safe Mode, draws its input unchanged and is deferred; the status bar says how many, `effect.deferredStatus` lists them with their object, effect and reason, and Effect › Refresh Deferred Effects (`effect.refreshDeferred`) runs them again with a fresh budget. Each document has its own budget, an edit runs the stages it changes, and exports, Expand Appearance and commands run every stage under the 5 s limit of each run. The web build times the budget and each run's limit with the page's `performance.now()`. Regressions: `crates/plugins/src/deferred.rs`, `crates/plugins/src/effect.rs`, `crates/plugins/src/host.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/canvas/tests.rs`. Scores and hours unchanged. - **Refreshing many deferred effects (G17):** Refresh Deferred Effects (`effect.refreshDeferred`) looks up the objects asked for, the stages reached, the objects drawn whole and the inputs that ran in hash sets, so its time no longer grows with the square of the number of deferred stages. The deferred records are indexed by stage and input, so asking whether a stage stays deferred, replacing a stage's records when it runs, and ending a drawing after the first view look at that stage's records only, and the records keep the order they were made in. With 40,000 deferred stages, one refresh in a release build took 38 ms, down from 1,036 ms, and asking about and running each stage once took 16 ms, down from 2,287 ms (wall-clock time on a computer busy with other builds, one run each). Regressions: `crates/plugins/src/deferred.rs`. Scores and hours unchanged. - **Refresh Deferred Effects by object (G17):** `effect.refreshDeferred` takes `ids`, or `id` for one, naming objects in the layers or in the art of a symbol, pattern, brush or opacity mask, the objects `effect.deferredStatus` lists; an object without a deferred stage adds nothing to the counts, and an id of no object in the document is an error. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. From 3a84466917bc4f15e409383630a5fd67dcc2ea33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:25:35 -0800 Subject: [PATCH 35/41] =?UTF-8?q?Symbols:=20Symbol=20Options=20=E2=80=BA?= =?UTF-8?q?=20Align=20to=20Pixel=20Grid=20keeps=20a=20symbol's=20instances?= =?UTF-8?q?=20on=20the=20pixel=20grid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit symbol.new and symbol.options take alignToPixelGrid (off by default), symbol.list rows report it, and the New Symbol and Symbol Options dialogs show the checkbox. When it is on, the horizontal and vertical straight segments of the paths in the symbol's art, opacity mask art included, snap to whole points (half points for an odd centered stroke) at the symbol's natural size, and its stroke weights become whole points. Each instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after every move. A scaled, rotated or sheared instance, and an instance in another symbol's art, stays where it is. In symbol editing mode the stored art and the editing layer snap after each edit. Duplicate Symbol, rename, copy and paste and symbol libraries keep the setting, and Delete Symbol removes it. Docs: docs/mcp.md, docs/ui-parity.md. --- crates/doc/src/lib.rs | 2 + crates/doc/src/symbol_pixel_aligned.rs | 80 +++++ crates/engine/src/cmd/brushsym.rs | 6 +- crates/engine/src/cmd/brushsym/symbols.rs | 51 +++- crates/engine/src/cmd/clipboard/resources.rs | 4 + crates/engine/src/cmd/object.rs | 2 +- crates/engine/src/cmd/object/pixelgrid.rs | 243 ++++++++++++++- crates/engine/src/cmd/symboledit.rs | 18 ++ crates/engine/src/cmd/symbollib.rs | 3 +- crates/engine/src/tests/pixelalign.rs | 301 +++++++++++++++++++ crates/ui-egui/src/dialogs/symbol_options.rs | 15 +- crates/ui-egui/src/panels/symbols.rs | 20 ++ docs/mcp.md | 18 +- docs/ui-parity.md | 2 +- 14 files changed, 739 insertions(+), 26 deletions(-) create mode 100644 crates/doc/src/symbol_pixel_aligned.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7b7ef4fee7..902d29e7c5 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -28,6 +28,7 @@ pub mod shared; mod symbol_export_type; mod symbol_nine_slice; pub mod symbol_overrides; +mod symbol_pixel_aligned; mod symbol_registration; pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; @@ -37,6 +38,7 @@ pub use symbol_nine_slice::{ SymbolNineSlice, charge_symbol_art, }; pub use symbol_overrides::SymbolOverride; +pub use symbol_pixel_aligned::SYMBOL_PIXEL_ALIGNED; pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration}; pub mod links; pub mod live; diff --git a/crates/doc/src/symbol_pixel_aligned.rs b/crates/doc/src/symbol_pixel_aligned.rs new file mode 100644 index 0000000000..6eb9d226dc --- /dev/null +++ b/crates/doc/src/symbol_pixel_aligned.rs @@ -0,0 +1,80 @@ +//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their +//! actual size wherever they are placed +//! (). +//! +//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned +//! (the default) is left out of the map. + +use std::collections::HashSet; + +use crate::Document; + +/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol. +pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned"; + +impl Document { + /// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off). + pub fn symbol_pixel_aligned(&self, name: &str) -> bool { + self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false) + } + + /// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map, + /// and the map goes when it is empty. + pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) { + if on { + let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({})); + if let Some(o) = m.as_object_mut() { + o.insert(name.into(), serde_json::json!(true)); + } + return; + } + let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return }; + o.remove(name); + if o.is_empty() { + self.unknown.remove(SYMBOL_PIXEL_ALIGNED); + } + } + + /// Move the stored setting when a symbol is renamed. + pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) { + if from == to { + return; + } + let on = self.symbol_pixel_aligned(from); + self.set_symbol_pixel_aligned(from, false); + self.set_symbol_pixel_aligned(to, on); + } + + /// The names of the pixel-aligned symbols the document holds (empty for most documents). + pub fn pixel_aligned_symbols(&self) -> HashSet { + let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() }; + o.iter() + .filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name)) + .map(|(name, _)| name.clone()) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_setting_is_off_by_default_and_follows_a_rename() { + let mut d = Document::new(100.0, 100.0); + let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![])); + d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art }); + assert!(!d.symbol_pixel_aligned("A")); + assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none()); + d.set_symbol_pixel_aligned("A", true); + assert!(d.symbol_pixel_aligned("A")); + assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()])); + d.symbols[0].name = "B".into(); + d.rename_symbol_pixel_aligned("A", "B"); + assert!(!d.symbol_pixel_aligned("A")); + assert!(d.symbol_pixel_aligned("B")); + d.set_symbol_pixel_aligned("B", false); + assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none()); + assert!(d.pixel_aligned_symbols().is_empty()); + } +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index db6e4e28a1..1f9490f24e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Symbols", [], None, - "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic}], current}", + "{} → {symbols: [{name, instances, size: [w,h], registration: 0..8, exportType: movieClip|graphic, nineSlice, type: static|dynamic, alignToPixelGrid: bool}], current}", has_doc, symbol_list ), @@ -199,7 +199,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions → {name, id, registration, exportType, nineSlice, type}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), @@ -208,7 +208,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", has_doc, symbol_options ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 1bfb8edea7..9b718c61b4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -69,6 +69,15 @@ fn nine_slice_param(p: &Value, cmd: &str, current: Option) -> R }) } +/// `alignToPixelGrid` (Symbol Options › Align to Pixel Grid): `None` when it is not given; any +/// value other than true or false, null included, is an error. +fn pixel_grid_param(p: &Value, cmd: &str) -> Result> { + match p.get("alignToPixelGrid") { + None => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, "alignToPixelGrid must be true or false")), + } +} + fn nine_slice_json(d: &Document, name: &str) -> Value { d.symbol_nine_slice(name).map_or(Value::Null, SymbolNineSlice::to_value) } @@ -187,6 +196,7 @@ pub(super) fn symbol_list(s: &mut Session, _: &Value) -> Result { "exportType": d.symbol_export_type(&sym.name).id(), "nineSlice": nine_slice_json(d, &sym.name), "type": type_id(sym.dynamic), + "alignToPixelGrid": d.symbol_pixel_aligned(&sym.name), }) }) .collect(); @@ -239,6 +249,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let export = export_type_param(p, C)?.unwrap_or_default(); let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); + let pixel = pixel_grid_param(p, C)?.unwrap_or(false); // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -249,6 +260,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(&name, reg); d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); + d.set_symbol_pixel_aligned(&name, pixel); let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); Ok(id) @@ -260,6 +272,7 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), "type": type_id(dynamic), + "alignToPixelGrid": pixel, })) } @@ -270,9 +283,15 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { let reg = registration_param(p, C)?; let nine = nine_slice_param(p, C, s.doc()?.doc.symbol_nine_slice(&name))?; let dynamic = type_param(p, C)?; + let pixel = pixel_grid_param(p, C)?; let new_name = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); if new_name.is_none() && export.is_none() && reg.is_none() && nine.is_none() && dynamic.is_none() { - return Err(bad(C, "pass newName, registration, exportType, nineSlice and/or type")); + match pixel { + None => return Err(bad(C, "pass newName, registration, exportType, nineSlice, type and/or alignToPixelGrid")), + // Align to Pixel Grid alone, already as asked: nothing changes and no undo step is added. + Some(on) if on == s.doc()?.doc.symbol_pixel_aligned(&name) => return Ok(options_json(&s.doc()?.doc, &name)), + Some(_) => {} + } } if let Some(ref n) = new_name && n != &name @@ -324,6 +343,7 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { d.rename_symbol_registration(&name, n); d.rename_symbol_export_type(&name, n); d.rename_symbol_nine_slice(&name, n); + d.rename_symbol_pixel_aligned(&name, n); if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.insert(CURRENT_SYMBOL.into(), json!(n)); } @@ -352,16 +372,26 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { sym.dynamic = dynamic; fit_overrides(d, &instances_of(d, Some(&final_name))); } + // Turning it on snaps the art and the instances at actual size when the edit ends + // (`object::refresh_pixel_aligned`). + if let Some(on) = pixel { + d.set_symbol_pixel_aligned(&final_name, on); + } Ok(()) })?; - let d = &s.doc()?.doc; - Ok(json!({ - "name": final_name, - "registration": d.symbol_registration(&final_name).0, - "exportType": d.symbol_export_type(&final_name).id(), - "nineSlice": nine_slice_json(d, &final_name), - "type": type_id(d.symbols.iter().any(|x| x.name == final_name && x.dynamic)), - })) + Ok(options_json(&s.doc()?.doc, &final_name)) +} + +/// What `symbol.options` answers for symbol `name`. +fn options_json(d: &Document, name: &str) -> Value { + json!({ + "name": name, + "registration": d.symbol_registration(name).0, + "exportType": d.symbol_export_type(name).id(), + "nineSlice": nine_slice_json(d, name), + "type": type_id(d.symbols.iter().any(|x| x.name == name && x.dynamic)), + "alignToPixelGrid": d.symbol_pixel_aligned(name), + }) } fn resolve_symbol(d: &Document, p: &Value, cmd: &str) -> Result { @@ -702,6 +732,7 @@ pub(super) fn symbol_delete(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(name, SymbolRegistration::CENTER); d.clear_symbol_export_type(name); d.set_symbol_nine_slice(name, None); + d.set_symbol_pixel_aligned(name, false); if d.unknown.get(CURRENT_SYMBOL).and_then(Value::as_str) == Some(name.as_str()) { d.unknown.remove(CURRENT_SYMBOL); } @@ -725,6 +756,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { let reg = d.symbol_registration(&name); let export = d.symbol_export_type(&name); let nine = d.symbol_nine_slice(&name); + let pixel = d.symbol_pixel_aligned(&name); s.edit("Duplicate Symbol", |d, _| { let art = d.reid(&sym.art); d.symbols.push(Symbol { dynamic: sym.dynamic, name: new.clone(), art: Arc::new(art) }); @@ -732,6 +764,7 @@ pub(super) fn symbol_duplicate(s: &mut Session, p: &Value) -> Result { d.set_symbol_registration(&new, reg); d.set_symbol_export_type(&new, export); d.set_symbol_nine_slice(&new, nine); + d.set_symbol_pixel_aligned(&new, pixel); Ok(()) })?; Ok(json!({ "name": new, "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value) })) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index fa69f1f820..c8c812bd0f 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -766,6 +766,8 @@ pub struct SymbolOptions { pub export_type: SymbolExportType, /// 9-slice guides (`None`: 9-slice scaling off). pub nine_slice: Option, + /// Align to Pixel Grid. + pub pixel_aligned: bool, } impl SymbolOptions { @@ -776,6 +778,7 @@ impl SymbolOptions { registration: d.symbol_registration(name), export_type: d.symbol_export_type(name), nine_slice: d.symbol_nine_slice(name), + pixel_aligned: d.symbol_pixel_aligned(name), } } @@ -785,6 +788,7 @@ impl SymbolOptions { d.set_symbol_registration(name, self.registration); d.set_symbol_export_type(name, self.export_type); d.set_symbol_nine_slice(name, self.nine_slice); + d.set_symbol_pixel_aligned(name, self.pixel_aligned); } } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 5eee2d3fce..a58f206c84 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -38,7 +38,7 @@ pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, - snap_if_aligned, + snap_if_aligned, snap_symbol_art, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 64d47ca0a9..a8bb12b429 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -1,6 +1,9 @@ //! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that //! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid -//! (). +//! (), +//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid. + +use std::collections::HashMap; use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign}; @@ -150,10 +153,234 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) { keep_pixel_aligned(n, Scaling::default()); } } + refresh_symbols(before, doc); +} + +/// How far the linear part of an instance's transform may be from its symbol's natural size, as a +/// fraction of that size, for the instance to count as placed at actual size. +const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9; + +/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to +/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes +/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends +/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance +/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a +/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included. +/// An instance in another symbol's art is placed by that symbol's instances and is left as it is. +/// A document without pixel-aligned symbols is not walked. +fn refresh_symbols(before: &Document, doc: &mut Document) { + let aligned = doc.pixel_aligned_symbols(); + if aligned.is_empty() { + return; + } + let was = before.pixel_aligned_symbols(); + let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str()); + let mut every = false; + for name in &aligned { + let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); + let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art); + let art_changed = match (art_before, art_now) { + (Some(b), Some(a)) => !Arc::ptr_eq(b, a), + _ => true, + }; + let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name); + if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed { + snap_symbol_art(doc, name); + every = true; + } + } + let natural: HashMap = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + if every { + for layer in doc.layers.iter_mut() { + if holds_instance(layer, &natural) { + snap_instances_in(Arc::make_mut(layer), &natural); + } + } + return; + } + let (mut ids, mut masked) = (vec![], vec![]); + changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked); + for id in ids { + if let Some(n) = doc.node_mut(id) { + snap_instance(n, &natural); + } + } + for id in masked { + if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) { + snap_instances_in(Arc::make_mut(&mut m.art), &natural); + } + } +} + +/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in +/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity +/// mask art holds such instances (`masked`). +fn changed_instances(before: &[Arc], after: &[Arc], natural: &HashMap, ids: &mut Vec, masked: &mut Vec) { + let mut by_id: Option>> = None; + for (i, a) in after.iter().enumerate() { + let b = match before.get(i) { + Some(b) if b.id == a.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), + }; + if b.is_some_and(|b| Arc::ptr_eq(b, a)) { + continue; + } + if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) { + masked.push(a.id); + } + if let NodeKind::SymbolInstance { symbol, .. } = &a.kind { + if natural.contains_key(symbol) { + ids.push(a.id); + } + } else if let Some(children) = a.children() { + changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked); + } + } +} + +/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in +/// `natural`. +fn holds_instance(n: &Node, natural: &HashMap) -> bool { + matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol)) + || n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) + || n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural))) +} + +/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity +/// masks included. Only what holds such an instance is copied for editing. +fn snap_instances_in(n: &mut Node, natural: &HashMap) { + snap_instance(n, natural); + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && holds_instance(&m.art, natural) + { + snap_instances_in(Arc::make_mut(&mut m.art), natural); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if holds_instance(c, natural) { + snap_instances_in(Arc::make_mut(c), natural); + } + } + } +} + +/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's +/// natural size: each path and compound path in it snaps as a pixel-aligned object does +/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when +/// something in it moved, and the answer says whether it did. +pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool { + let natural = doc.symbol_natural_xf(name); + let det = natural.determinant(); + if !det.is_finite() || det.abs() < 1e-18 { + return false; + } + let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false }; + // Instances draw the art's strokes at their stored width, and the art of unlinked opacity + // masks, which `Node::transform` leaves alone, at the natural size too. + let mut art = (*sym.art).clone(); + art.transform(natural, false); + transform_unlinked_masks(&mut art, natural); + if !snap_art(&mut art) { + return false; + } + let inverse = natural.inverse(); + art.transform(inverse, false); + transform_unlinked_masks(&mut art, inverse); + sym.art = Arc::new(art); + true +} + +/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks +/// too. Only what holds such a mask is copied for editing. +fn transform_unlinked_masks(n: &mut Node, xf: Affine) { + if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) + && holds_unlinked_mask(&m.art, !m.linked) + { + let linked = m.linked; + let art = Arc::make_mut(&mut m.art); + if !linked { + art.transform(xf, false); + } + transform_unlinked_masks(art, xf); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if holds_unlinked_mask(c, false) { + transform_unlinked_masks(Arc::make_mut(c), xf); + } + } + } +} + +/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of +/// its masks too, has an unlinked opacity mask. +fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool { + unlinked + || n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked)) + || n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false))) +} + +/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of +/// opacity masks included (those of a compound path's paths too). Returns whether anything +/// changed. +fn snap_art(n: &mut Node) -> bool { + let mut moved = false; + if can_align(n) { + let was = n.clone(); + snap_object(n, Scaling::default()); + moved = *n != was; + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + if c.extras().mask.is_some() { + moved |= snap_mask(Arc::make_mut(c)); + } + } + } + } else if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + moved |= snap_art(Arc::make_mut(c)); + } + } + // After the object itself, which a linked mask follows. + snap_mask(n) || moved +} + +/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed. +fn snap_mask(n: &mut Node) -> bool { + let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false }; + let mut art = (*m.art).clone(); + if !snap_art(&mut art) { + return false; + } + m.art = Arc::new(art); + true +} + +/// Move symbol instance `n` to whole points when its transform places its symbol's art at the +/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled, +/// rotated (a half turn included) or sheared instance stays where it is. +fn snap_instance(n: &mut Node, natural: &HashMap) { + let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return }; + let Some(nat) = natural.get(symbol.as_str()) else { return }; + let [a, b, c, d, e, f] = xf.as_coeffs(); + let [na, _, _, nd, _, _] = nat.as_coeffs(); + let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0); + let actual = + near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0); + // Flipped along both axes is a half turn, which counts as rotated. + let half_turn = a * na < 0.0 && d * nd < 0.0; + if !actual || half_turn || !e.is_finite() || !f.is_finite() { + return; + } + let (x, y) = (e.round(), f.round()); + if x != e || y != f { + *xf = Affine::new([a, b, c, d, x, y]); + } } /// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the -/// pixel-aligned objects in them to the pixel grid again. +/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid +/// again. pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { for id in ids { if doc.node(*id).is_some_and(holds_aligned) @@ -162,6 +389,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) { keep_pixel_aligned(n, Scaling::default()); } } + let aligned = doc.pixel_aligned_symbols(); + if aligned.is_empty() { + return; + } + let natural: HashMap = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect(); + for id in ids { + if doc.node(*id).is_some_and(|n| holds_instance(n, &natural)) + && let Some(n) = doc.node_mut(*id) + { + snap_instances_in(n, &natural); + } + } } /// The objects of `after` that differ from their counterparts in `before` (or are new) and are diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index 606ab40fcf..c3fc9a4392 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -529,6 +529,24 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> { }; d.symbols[index].art = Arc::new(new_art); follow_objects(d, &se.symbol, (&old, old_group), (&art, group)); + // A pixel-aligned symbol stores its art on the pixel grid while it is edited too, and the + // editing layer shows the snapped art. + if d.symbol_pixel_aligned(&se.symbol) && super::object::snap_symbol_art(d, &se.symbol) { + let stored = &d.symbols[index].art; + let snapped: Vec> = if group { stored.children().map(|c| c.to_vec()).unwrap_or_default() } else { vec![stored.clone()] }; + let mut snapped = snapped.into_iter().map(|n| { + let mut n = (*n).clone(); + n.transform(se.xf, false); + Arc::new(n) + }); + if let Some(ch) = d.node_mut(se.layer).and_then(Node::children_mut) { + for c in ch.iter_mut().filter(|c| !c.is_ruler_guide()) { + if let Some(n) = snapped.next() { + *c = n; + } + } + } + } if let Some(e) = d.symbol_edit.as_mut() { e.changed = true; e.group = group; diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 63096c9d98..b82be77f43 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -499,12 +499,13 @@ fn instance(name: &str) -> Node { } /// Symbol `from`'s Symbol Options in `src` (natural size, registration, export type, 9-slice -/// guides) given to symbol `to` of `d`. +/// guides, Align to Pixel Grid) given to symbol `to` of `d`. fn copy_options(src: &Document, from: &str, d: &mut Document, to: &str) { set_natural_size(d, to, Some(natural_size(src, from))); d.set_symbol_registration(to, src.symbol_registration(from)); d.set_symbol_export_type(to, src.symbol_export_type(from)); d.set_symbol_nine_slice(to, src.symbol_nine_slice(from)); + d.set_symbol_pixel_aligned(to, src.symbol_pixel_aligned(from)); } fn builtin_info(b: &BuiltinSymbolLibrary) -> LibraryInfo { diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 06057d1fc0..b70098d9c9 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -1158,3 +1158,304 @@ fn not_aligned_to_pixel_grid_takes_a_compound_path_by_its_own_property() { assert!(!aligned(&s, off)); assert_eq!(not_aligned(&mut s, &[compound]), vec![other]); } + +/// The anchors of the paths in the art of symbol instance `inst`, where its transform places them. +fn placed_points(s: &Session, inst: u64) -> Vec<(f64, f64)> { + let d = &s.doc().unwrap().doc; + let NodeKind::SymbolInstance { symbol, xf } = &d.node(NodeId(inst)).unwrap().kind else { panic!("{inst} is not a symbol instance") }; + let art = &d.symbols.iter().find(|x| &x.name == symbol).unwrap().art; + let mut out = vec![]; + art.walk(&mut |n| { + if let Some(p) = n.path_data() { + out.extend(p.anchors().map(|(_, _, a)| { + let q = *xf * a.p; + (q.x, q.y) + })); + } + }); + out +} + +/// The transform of symbol instance `inst`. +fn instance_xf(s: &Session, inst: u64) -> vectorcraft_geom::Affine { + match &s.doc().unwrap().doc.node(NodeId(inst)).unwrap().kind { + NodeKind::SymbolInstance { xf, .. } => *xf, + _ => panic!("{inst} is not a symbol instance"), + } +} + +/// Symbol Options › Align to Pixel Grid on a new symbol: the instance that replaces the selection +/// draws its art's edges on whole points, and goes back to them after a move by a fraction of a +/// point; a symbol made without it keeps the art where it was drawn. +#[test] +fn a_pixel_aligned_symbol_keeps_its_instance_on_whole_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let r = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(r["alignToPixelGrid"], true); + let inst = r["id"].as_u64().unwrap(); + let pts = placed_points(&s, inst); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!(list["symbols"][0]["alignToPixelGrid"], true); + + path(&mut s, "M100.3 20.6 L140.7 20.6 L140.7 30.3 L100.3 30.3 Z", 2.0); + let plain = s.execute("symbol.new", &json!({"name": "Plain"})).unwrap(); + assert_eq!(plain["alignToPixelGrid"], false); + let pts = placed_points(&s, plain["id"].as_u64().unwrap()); + assert!(!whole(&pts), "{pts:?}"); +} + +/// A centered stroke of odd weight puts the art's edges on half points, so the stroke's own edges +/// fall on the grid. +#[test] +fn a_pixel_aligned_symbol_with_an_odd_stroke_goes_to_half_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let pts = placed_points(&s, inst); + assert!(halves(&pts), "{pts:?}"); +} + +/// Turning it on in Symbol Options snaps the instances placed at actual size and leaves a scaled +/// one where it is; instances placed later land on whole points; asking again for the value the +/// symbol has adds no undo step; a duplicate and a rename keep it, a delete clears it, and a value +/// that is not true or false is refused. +#[test] +fn symbol_options_align_to_pixel_grid_snaps_instances_at_actual_size() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("object.scale", &json!({"sx": 150, "sy": 150})).unwrap(); + let scaled = instance_xf(&s, b); + assert!(!whole(&placed_points(&s, a))); + + let r = s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(r["alignToPixelGrid"], true); + let pts = placed_points(&s, a); + assert!(whole(&pts), "{pts:?}"); + assert_eq!(instance_xf(&s, b), scaled); + let c = s.execute("symbol.place", &json!({"name": "Px", "x": 50.3, "y": 60.6})).unwrap()["id"].as_u64().unwrap(); + let pts = placed_points(&s, c); + assert!(whole(&pts), "{pts:?}"); + + let steps = undo_len(&s); + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + assert_eq!(undo_len(&s), steps); + + assert_eq!(s.execute("symbol.duplicate", &json!({"name": "Px"})).unwrap()["name"], "Px copy"); + assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Px copy")); + s.execute("symbol.options", &json!({"name": "Px", "newName": "Grid"})).unwrap(); + assert!(s.doc().unwrap().doc.symbol_pixel_aligned("Grid")); + assert!(!s.doc().unwrap().doc.symbol_pixel_aligned("Px")); + s.execute("symbol.delete", &json!({"names": ["Grid", "Px copy"]})).unwrap(); + assert!(s.doc().unwrap().doc.unknown.get(vectorcraft_doc::SYMBOL_PIXEL_ALIGNED).is_none()); + + path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0); + assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": "yes"})).is_err()); + assert!(s.execute("symbol.new", &json!({"alignToPixelGrid": null})).is_err()); + s.execute("symbol.new", &json!({"name": "Q"})).unwrap(); + assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": 1})).is_err()); + assert!(s.execute("symbol.options", &json!({"name": "Q", "alignToPixelGrid": null})).is_err()); +} + +/// An instance reflected across one axis goes back to whole points after a move; one turned a half +/// turn counts as rotated and moves by exactly the amount asked. +#[test] +fn a_reflected_instance_snaps_and_a_half_turned_one_does_not() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let [.., e, f] = instance_xf(&s, inst).as_coeffs(); + assert!(whole(&[(e, f)]), "{e} {f}"); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + s.execute("object.rotate", &json!({"angle": 180})).unwrap(); + let [.., e0, f0] = instance_xf(&s, inst).as_coeffs(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + let [.., e1, f1] = instance_xf(&s, inst).as_coeffs(); + assert!((e1 - e0 - 0.3).abs() < 1e-9 && (f1 - f0 - 0.45).abs() < 1e-9, "{e0} {f0} -> {e1} {f1}"); +} + +/// An instance of a pixel-aligned symbol attached to a path goes back to whole points each time the +/// path places it. +#[test] +fn an_instance_on_a_path_stays_on_whole_points() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let spine = s.execute("path.create", &json!({"d": "M 0.3 100.4 L 300.3 100.4"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.objectsOnPath.attach", &json!({"path": spine, "ids": [inst]})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "attached: {pts:?}"); + let anchors = json!([{"x": 0.6, "y": 120.7}, {"x": 300.6, "y": 120.7}]); + s.execute("path.setAnchors", &json!({"id": spine, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "path edited: {pts:?}"); +} + +/// A path in the art of an opacity mask in a pixel-aligned symbol's art snaps with the rest of +/// the art. +#[test] +fn mask_art_in_a_pixel_aligned_symbol_snaps() { + let mut s = new_doc(); + let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + } + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// A path in the art of an unlinked opacity mask in a pixel-aligned symbol's art snaps as the mask +/// is drawn at the symbol's natural size. +#[test] +fn unlinked_mask_art_in_a_pixel_aligned_symbol_snaps_at_natural_size() { + let mut s = new_doc(); + let r = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), false))); + } + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap(); + assert_ne!(s.doc().unwrap().doc.symbol_natural_xf("Px"), vectorcraft_geom::Affine::IDENTITY); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let sym = d.symbols.iter_mut().find(|x| x.name == "Px").unwrap(); + std::sync::Arc::make_mut(&mut sym.art).extras_mut().mask.as_mut().unwrap().linked = false; + } + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// A path in the art of an opacity mask on a path of a compound path in a pixel-aligned symbol's +/// art snaps with the rest of the art. +#[test] +fn mask_art_on_a_compound_paths_path_in_a_pixel_aligned_symbol_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let b = path(&mut s, "M50.3 20.6 L60.7 20.6 L60.7 30.3 L50.3 30.3 Z", 2.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let m = path(&mut s, "M12.3 22.6 L30.7 22.6 L30.7 28.3 L12.3 28.3 Z", 2.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let art = d.remove(NodeId(m)).unwrap(); + let first = d.node(NodeId(c)).unwrap().children().unwrap()[0].id; + d.node_mut(first).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + } + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let xf = instance_xf(&s, inst); + let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art; + let mut pts = vec![]; + art.walk(&mut |n| { + if let Some(mask) = n.extras().mask.as_ref() { + mask.art.walk(&mut |c| { + if let Some(p) = c.path_data() { + pts.extend(p.anchors().map(|(_, _, a)| { + let q = xf * a.p; + (q.x, q.y) + })); + } + }); + } + }); + assert_eq!(pts.len(), 4); + assert!(whole(&pts), "{pts:?}"); +} + +/// An instance in the art of an object's opacity mask goes to whole points when its symbol is made +/// pixel-aligned. +#[test] +fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + s.execute("symbol.new", &json!({"name": "Px"})).unwrap(); + let b = s.execute("symbol.place", &json!({"name": "Px", "x": 100.3, "y": 200.7})).unwrap()["id"].as_u64().unwrap(); + let r = path(&mut s, "M80 180 L160 180 L160 240 L80 240 Z", 1.0); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inst = d.remove(NodeId(b)).unwrap(); + d.node_mut(NodeId(r)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*inst).clone(), true))); + } + s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap(); + let d = &s.doc().unwrap().doc; + let mask = d.node(NodeId(r)).unwrap().extras().mask.clone().unwrap(); + let NodeKind::SymbolInstance { xf, .. } = &mask.art.kind else { panic!("the mask art is not the instance") }; + let [.., e, f] = xf.as_coeffs(); + assert!(whole(&[(e, f)]), "{e} {f}"); +} + +/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored +/// on the pixel grid, so its instances stay on it. +#[test] +fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() { + let mut s = new_doc(); + path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0); + let inst = s.execute("symbol.new", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap(); + let st = s.doc().unwrap(); + let layer = st.doc.symbol_edit.as_ref().unwrap().layer; + let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [part]})).unwrap(); + s.execute("object.move", &json!({"dx": 0.3, "dy": 0.45})).unwrap(); + assert!(s.doc().unwrap().doc.symbol_edit.is_some()); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); + // The editing layer shows the art as it is stored. + let shown = points(&s, part); + assert!(whole(&shown), "{shown:?}"); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + let pts = placed_points(&s, inst); + assert!(whole(&pts), "{pts:?}"); +} diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 9e6fa98f82..146e02c6eb 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -7,7 +7,8 @@ //! (percent of the symbol's size, -1600..1600: below 0 or above 100 for a guide outside the art), //! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; -//! 4 = centre), `__edit` (true when editing an existing symbol). Help: +//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an +//! existing symbol). Help: //! . use serde_json::{Map, Value, json}; @@ -75,7 +76,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result { return Err("nothing selected".into()); } let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "__edit": false }); + let mut fields = + json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false }); if let Some(o) = fields.as_object_mut() { o.extend(slice_fields(None)); } @@ -107,6 +109,7 @@ pub fn open_edit(app: &mut VectorcraftApp, name: Option<&str>) -> Result bool { ui.end_row(); } } + label(ui, ""); + form::check(ui, d, "alignToPixelGrid", tl!("Align to Pixel Grid")); + ui.end_row(); }); false } @@ -175,16 +181,17 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let kind = d.str("type"); let registration = d.fields.get("registration").and_then(Value::as_u64).unwrap_or(4); let edit = d.fields.get("__edit").and_then(Value::as_bool).unwrap_or(false); + let pixel = d.bool("alignToPixelGrid"); let r = if edit { let from = d.fields.get("__from").and_then(Value::as_str).unwrap_or(name); - let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration }); + let mut params = json!({ "name": from, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); if from != name { params["newName"] = json!(name); } app.run("symbol.options", params) } else { - let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration }); + let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); app.run("symbol.new", params) }; diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index fd77707fcd..6e933d44cd 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -944,6 +944,26 @@ mod tests { assert_eq!(nine, json!([-0.123456789, 1.5, -1.255, -2.75])); } + /// Symbol Options › Align to Pixel Grid is off for a new symbol, OK sends it, and the dialog + /// reopens with the symbol's setting. + #[test] + fn symbol_options_sets_align_to_pixel_grid() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10.3, "y": 10.6, "width": 30, "height": 20})).unwrap(); + app.run("ui.symbolOptions", json!({})).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().bool("alignToPixelGrid")); + app.ui.dialog.as_mut().unwrap().fields.insert("alignToPixelGrid".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + let name = symbols(&mut app)[0].clone(); + assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], true); + app.run("ui.symbolOptions", json!({"edit": true, "name": name})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("alignToPixelGrid")); + app.ui.dialog.as_mut().unwrap().fields.insert("alignToPixelGrid".into(), json!(false)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], false); + } + /// F8 is Symbol Options… (`ui.symbolOptions`) by default, on every platform. Shift+F8 and Cmd+F8 /// are still the Transform and Info panels' keys, and Cmd+Shift+F8 is still Edit Pattern's. No /// other command, tool or panel has F8 by default. diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..0dffc3a46c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3271,16 +3271,24 @@ horizontal guide between its top and bottom. Released anywhere else, it makes no These families are in the live catalog (`command_list` / `vectorcraft://commands`); the prompt `trace-and-style` already walks Image Trace. Short agent entry points: -- Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic` and `type`: - `static`|`dynamic`), - `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, ids?}`, - `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?}` (`nineSlice` bool turns +- Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic`, `type`: + `static`|`dynamic` and `alignToPixelGrid`), + `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?}`, + `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions of the symbol size in from each edge, each -16..16 with `left + right < 1` and `top + bottom < 1`, a quarter each when none are given; below 0 or above 1 puts a guide outside the art, and the art then scales by the cells it falls in; rows of `symbol.list` carry `nineSlice`: the guides or `null`; a scaled instance of a symbol with guides keeps its corners at their size, and `symbol.breakLink` gives its art as it draws; dragging a guide on the canvas in symbol editing mode sends `nineSliceGuides` in one undo step; `type` is - Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog), + Symbol Type, `static` by default for the command and `dynamic` by default in the Symbol Options dialog; + `alignToPixelGrid` is Symbol Options › Align to Pixel Grid, off by default: when it is on, the horizontal and + vertical straight segments of the paths in the symbol's art snap to whole points (half points for an odd centered + stroke) as the art is drawn at the symbol's natural size, its stroke weights become whole points, and each instance + placed at that size, reflected across one axis or not, moves to whole points and goes back to them after every move; + VectorCraft leaves a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's + art, where it is, snaps the art again after it is edited, and does not count + instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has + adds no undo step), `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after `object.resetBoundingBox`; a hidden or locked instance's art stays hidden or locked and is not selected), `symbol.replace`, diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 071c8d4719..5926c006fb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -436,7 +436,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | -| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | +| Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | | Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | | Pathfinder panel on one group selected alone; a greyed-out button says what it needs | partial | #1450; the group's members are combined; one plain path selected alone stays disabled (the public documentation doesn't say what the operations do to a single path) | From 1c95aa2b6558ee8495069bfd8be5cfb2485229ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:56:14 -0800 Subject: [PATCH 36/41] Glyphs: the Show menu lists the font's OpenType glyph categories After Alternates for Current Selection, the Glyphs panel's Show menu and panel menu list the categories the browsed font's GSUB features give glyphs to: Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures. Choosing one shows that category's glyphs, the characters first and then the glyphs no character maps. A font without the chosen category shows Entire Font. - text: FontFace::glyph_categories reads the single, alternate, multiple and ligature substitutions of each category's features, once per face, leaving out a substitution an earlier subtable of its lookup shadows, within a total glyph budget. - engine: text.glyphCategories {family, style?} lists them. - ui-egui: the Show menu and panel menu entries, with Ligatures, Ornaments and Figures rows in every catalog. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fonts.rs | 47 +++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/fontlist.rs | 35 +++ crates/text/src/fontdb.rs | 2 +- crates/text/src/fontdb/gsub.rs | 271 ++++++++++++++++++ crates/text/src/lib.rs | 8 +- crates/text/src/test_fonts.rs | 60 ++++ 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/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.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/glyphs.rs | 176 ++++++++++-- crates/ui-egui/src/panels/opentype.rs | 5 +- docs/mcp.md | 18 ++ docs/target-app-parity.md | 1 + 39 files changed, 676 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 28662f013c..541cdd1118 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -53,6 +53,15 @@ pub fn specs() -> Vec { always, font_list ), + cmd!( + query "text.glyphCategories", + "Glyph Categories", + [], + None, + "{family, style?} the OpenType categories of the font's glyphs, what the Glyphs panel's Show menu lists after Alternates for Current Selection: from the font's GSUB table, the glyphs that the single, alternate, multiple and ligature substitutions of each kind's features give, each glyph once by id, in this order: `ligatures` (liga, dlig, hlig), `swashes` (swsh, cswh), `stylisticAlternates` (salt), `ss01` to `ss20`, `smallCaps` (smcp, c2sc), `ornaments` (ornm), `fractions` (frac, afrc, numr, dnom) and `figures` (lnum, onum, pnum, tnum); a kind without glyphs is left out; contextual lookups are not followed → {family, style, categories: [{id, name?: a stylistic set's name in the font, glyphs: [glyph id]}]} (style omitted: the family's first style; an error when the family or style isn't available)", + always, + glyph_categories + ), cmd!( "text.rescanFonts", "Refresh Font List", @@ -1137,6 +1146,44 @@ fn font_list(_: &mut Session, p: &Value) -> Result { } } +/// `text.glyphCategories`: the OpenType categories of a font's glyphs +/// ([`vectorcraft_text::FontFace::glyph_categories`]). +fn glyph_categories(_: &mut Session, p: &Value) -> Result { + const C: &str = "text.glyphCategories"; + let text = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.as_str())), + Some(_) => Err(bad(C, format!("`{key}` must be a string"))), + }; + let family = text("family")?.ok_or_else(|| bad(C, "missing `family`"))?; + let db = vectorcraft_text::FontDb::global(); + if !db.has_family(family) { + return Err(bad(C, format!("font family `{family}` is not available"))); + } + let styles = db.styles(family); + let style = match text("style")? { + Some(style) => styles + .iter() + .find(|s| s.eq_ignore_ascii_case(style)) + .cloned() + .ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?, + None => styles.first().cloned().unwrap_or_else(|| "Regular".into()), + }; + let face = db.face(family, &style).ok_or_else(|| bad(C, format!("style `{style}` of `{family}` is not available")))?; + let categories: Vec = face + .glyph_categories() + .iter() + .map(|c| { + let mut v = json!({"id": c.kind.id(), "glyphs": c.glyphs}); + if let Some(name) = &c.name { + v["name"] = json!(name); + } + v + }) + .collect(); + Ok(json!({"family": face.family, "style": face.style, "categories": categories})) +} + pub(crate) fn rescan(s: &mut Session, _: &Value) -> Result { let db = vectorcraft_text::FontDb::global(); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f445237d83..6c7be12540 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -624,6 +624,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.fonts", "text.getRange", "text.glyphAlternates", + "text.glyphCategories", "text.insertInline", "text.missingFonts", "text.replaceFont", diff --git a/crates/engine/src/tests/fontlist.rs b/crates/engine/src/tests/fontlist.rs index 6202a8ce70..5eb059bd3b 100644 --- a/crates/engine/src/tests/fontlist.rs +++ b/crates/engine/src/tests/fontlist.rs @@ -49,6 +49,41 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() { assert!(!d.is_dirty(), "nothing to save"); } +/// `text.glyphCategories` lists the kinds of glyph a font's OpenType features give, with a +/// stylistic set's name, and refuses a font that isn't available and params that aren't strings. +#[test] +fn glyph_categories_list_the_glyphs_of_each_kind_of_feature() { + use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid}; + FontDb::global().add_font(categories_font().expect("the test font builds")); + let mut s = Session::new(); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let mut figures = vec![g('7'), g('8')]; + figures.sort_unstable(); + let r = s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY})).unwrap(); + assert_eq!(r["family"], CATEGORIES_FAMILY); + assert_eq!(r["style"], "Regular"); + assert_eq!( + r["categories"], + json!([ + {"id": "ligatures", "glyphs": [g('L')]}, + {"id": "ss02", "name": "Round Dots", "glyphs": [g('G')]}, + {"id": "smallCaps", "glyphs": [g('B')]}, + {"id": "figures", "glyphs": figures}, + ]) + ); + assert_eq!(s.execute("text.glyphCategories", &json!({"family": CATEGORIES_FAMILY, "style": "regular"})).unwrap(), r); + for (p, says) in [ + (json!({}), "missing `family`"), + (json!({"family": 3}), "`family` must be a string"), + (json!({"family": "No Such Font"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": "Black"}), "is not available"), + (json!({"family": CATEGORIES_FAMILY, "style": true}), "`style` must be a string"), + ] { + let e = s.execute("text.glyphCategories", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } +} + /// Refreshing the font list while a background save writes the file leaves the document saved /// once the file is written. #[test] diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index e96e1d0fae..b45564c887 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -54,7 +54,7 @@ pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins}; pub(crate) use glyph_pen::FlipPen; -pub use gsub::{GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index a245efeea2..a88d4ed86a 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -94,6 +94,211 @@ pub(super) struct GsubIndex { /// The first feature, listed ones first, that gives each glyph: by a single, multiple, /// alternate or ligature substitution, and the glyph it replaces (not known for a ligature). reached: HashMap)>, + /// The face's glyph categories ([`FontFace::glyph_categories`]), read the first time they are + /// asked for. + categories: std::sync::OnceLock>, +} + +/// A kind of glyph that the Glyphs panel's Show menu lists by OpenType feature +/// ([`FontFace::glyph_categories`]). The kinds, the features in each and their order are +/// VectorCraft's own. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum GlyphCategoryKind { + /// `liga`, `dlig` and `hlig`. + Ligatures, + /// `swsh` and `cswh`. + Swashes, + /// `salt`. + StylisticAlternates, + /// One of `ss01` to `ss20`, by its number. + StylisticSet(u8), + /// `smcp` and `c2sc`. + SmallCaps, + /// `ornm`. + Ornaments, + /// `frac`, `afrc`, `numr` and `dnom`. + Fractions, + /// `lnum`, `onum`, `pnum` and `tnum`. + Figures, +} + +impl GlyphCategoryKind { + /// Every kind in the order the Show menu lists them, the stylistic sets by number. + pub fn all() -> Vec { + let sets = (1..=20).map(Self::StylisticSet); + [Self::Ligatures, Self::Swashes, Self::StylisticAlternates] + .into_iter() + .chain(sets) + .chain([Self::SmallCaps, Self::Ornaments, Self::Fractions, Self::Figures]) + .collect() + } + + /// The `GSUB` features whose substitutions give the kind's glyphs. + pub fn features(self) -> Vec<[u8; 4]> { + match self { + Self::Ligatures => vec![*b"liga", *b"dlig", *b"hlig"], + Self::Swashes => vec![*b"swsh", *b"cswh"], + Self::StylisticAlternates => vec![*b"salt"], + Self::StylisticSet(n) => { + let [a, b] = [b'0' + n / 10 % 10, b'0' + n % 10]; + vec![[b's', b's', a, b]] + } + Self::SmallCaps => vec![*b"smcp", *b"c2sc"], + Self::Ornaments => vec![*b"ornm"], + Self::Fractions => vec![*b"frac", *b"afrc", *b"numr", *b"dnom"], + Self::Figures => vec![*b"lnum", *b"onum", *b"pnum", *b"tnum"], + } + } + + /// The kind's id: `ligatures`, `swashes`, `stylisticAlternates`, `ss01` to `ss20`, `smallCaps`, + /// `ornaments`, `fractions` or `figures`. + pub fn id(self) -> String { + match self { + Self::Ligatures => "ligatures".into(), + Self::Swashes => "swashes".into(), + Self::StylisticAlternates => "stylisticAlternates".into(), + Self::StylisticSet(n) => format!("ss{n:02}"), + Self::SmallCaps => "smallCaps".into(), + Self::Ornaments => "ornaments".into(), + Self::Fractions => "fractions".into(), + Self::Figures => "figures".into(), + } + } + + /// The kind whose [`Self::id`] is `id`. + pub fn from_id(id: &str) -> Option { + Self::all().into_iter().find(|k| k.id() == id) + } +} + +/// The glyphs of one [`GlyphCategoryKind`] that a face has ([`FontFace::glyph_categories`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GlyphCategory { + pub kind: GlyphCategoryKind, + /// A stylistic set's name from the font's `name` table, when the font gives one. + pub name: Option, + /// The glyphs the kind's features give, each once, by glyph id. + pub glyphs: Vec, +} + +/// Read `face`'s glyph categories ([`FontFace::glyph_categories`]). The caps of [`GsubIndex::read`] +/// bound what a damaged table makes it read, and all the lookups together give at most +/// `MAX_ENTRIES` glyphs. +fn read_categories(face: &FontFace) -> Vec { + let Some(font) = face.skrifa() else { return vec![] }; + let Ok(gsub) = font.gsub() else { return vec![] }; + let (Ok(features), Ok(lookups)) = (gsub.feature_list(), gsub.lookup_list()) else { return vec![] }; + let glyphs = font.maxp().map_or(0, |m| u32::from(m.num_glyphs())); + let kinds = GlyphCategoryKind::all(); + // The lookups of each kind's features, in every script's feature records. + let mut wanted: Vec> = vec![vec![]; kinds.len()]; + let mut total = 0_usize; + for record in features.feature_records().iter().take(MAX_FEATURES) { + let tag = record.feature_tag().to_be_bytes(); + let Some(k) = kinds.iter().position(|kind| kind.features().contains(&tag)) else { continue }; + let Ok(feature) = record.feature(features.offset_data()) else { continue }; + for i in feature.lookup_list_indices().iter().take(MAX_FEATURE_LOOKUPS) { + if total >= MAX_LOOKUPS { + break; + } + if !wanted[k].contains(&i.get()) { + wanted[k].push(i.get()); + total += 1; + } + } + } + let all = lookups.lookups(); + let mut reads = MAX_SUBTABLE_READS; + // What each lookup gives, read once when several kinds share it. + let mut read: HashMap> = HashMap::new(); + // The glyphs all the lookups read together may give: at most `MAX_ENTRIES`. + let mut left = MAX_ENTRIES; + let mut outputs = |lookup: u16, reads: &mut usize| -> Vec { + if let Some(out) = read.get(&lookup) { + return out.clone(); + } + // A lookup not read yet once the read budget is spent gives nothing, and is not cached. + if *reads == 0 || left == 0 { + return vec![]; + } + // Each subtable adds only what still fits in what is left of the glyph budget. + let cap = left; + let mut out: Vec = vec![]; + // The glyphs an earlier subtable of the lookup covers: OpenType applies the first subtable + // that covers a glyph, so a later one's substitution of it is never made. + let mut covered: std::collections::HashSet = std::collections::HashSet::new(); + let mut first = |from: u32| covered.insert(from); + if let Ok(subtables) = all.get(usize::from(lookup)).and_then(|l| l.subtables()) { + let n = MAX_SUBTABLES.min(*reads); + let room = |out: &Vec| cap.saturating_sub(out.len()); + match subtables { + SubstitutionSubtables::Single(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(single_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).map(|(_, to)| to).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Alternate(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(alternate_sets(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, set)| set).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Multiple(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(multiple_pairs(&t, r).into_iter().filter(|(from, _)| first(*from)).flat_map(|(_, to)| to).take(r)); + if room(&out) == 0 { + break; + } + } + } + SubstitutionSubtables::Ligature(s) => { + for t in s.iter().take(n).inspect(|_| *reads -= 1).flatten() { + let r = room(&out); + out.extend(ligature_glyphs(&t, r).into_iter().take(r)); + if room(&out) == 0 { + break; + } + } + } + _ => {} + } + } + left = left.saturating_sub(out.len()); + read.insert(lookup, out.clone()); + out + }; + let names = face.stylistic_sets(); + let mut categories = vec![]; + for (kind, lookups) in kinds.into_iter().zip(wanted) { + let mut found: Vec = vec![]; + for lookup in lookups { + let room = MAX_ENTRIES.saturating_sub(found.len()); + found.extend(outputs(lookup, &mut reads).into_iter().filter(|g| *g != 0 && *g < glyphs).take(room)); + if found.len() >= MAX_ENTRIES { + break; + } + } + found.sort_unstable(); + found.dedup(); + found.truncate(MAX_ENTRIES); + if found.is_empty() { + continue; + } + let name = match kind { + GlyphCategoryKind::StylisticSet(n) => names.iter().find(|s| s.number == n).and_then(|s| s.name.clone()), + _ => None, + }; + categories.push(GlyphCategory { kind, name, glyphs: found }); + } + categories } /// The glyph single substitution `t` puts in place of each glyph its coverage holds. @@ -383,4 +588,70 @@ impl FontFace { let name = font.glyph_names().get(skrifa::GlyphId::new(gid))?; (!name.is_synthesized()).then(|| name.as_str().to_string()) } + + /// The kinds of glyph the face's `GSUB` table gives ([`GlyphCategoryKind`]), in the order of + /// [`GlyphCategoryKind::all`], each with the glyphs that the single, alternate, multiple and + /// ligature substitutions of its features put in place of others (in extension lookups too), + /// each glyph once by id, `.notdef` and ids past the face's glyph count left out. A single, + /// alternate or multiple substitution of a glyph an earlier subtable of its lookup covers is + /// left out, since that substitution is never made. A kind + /// without glyphs is left out. A stylistic set takes its name from the font's `name` table, + /// when the font gives one. Contextual lookups are not followed, nor is the choice of a + /// variable font's instance of `FeatureVariations`. Read once for the face; empty when it has + /// no `GSUB` table or the table cannot be read. + pub fn glyph_categories(&self) -> &[GlyphCategory] { + self.gsub_index().categories.get_or_init(|| read_categories(self)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The test font lists ligatures, stylistic set 2 with its name, small caps and figures, by + /// glyph id; its `cswh` feature has no lookups, so it lists no swashes, and small caps leave out + /// the C of a substitution an earlier subtable shadows. + #[test] + fn categories_list_the_glyphs_each_kind_of_feature_gives() { + use crate::test_fonts::{CATEGORIES_FAMILY, categories_font, source_sans_gid}; + let db = super::super::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(categories_font().expect("the test font builds")), 1); + let face = db.face(CATEGORIES_FAMILY, "Regular").expect("the test face"); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let mut figures = vec![g('7'), g('8')]; + figures.sort_unstable(); + let found: Vec<(String, Option, Vec)> = + face.glyph_categories().iter().map(|c| (c.kind.id(), c.name.clone(), c.glyphs.clone())).collect(); + assert_eq!( + found, + [ + ("ligatures".to_string(), None, vec![g('L')]), + ("ss02".to_string(), Some("Round Dots".to_string()), vec![g('G')]), + ("smallCaps".to_string(), None, vec![g('B')]), + ("figures".to_string(), None, figures), + ] + ); + assert!(std::ptr::eq(face.glyph_categories(), face.glyph_categories()), "read once"); + } + + /// A face whose `GSUB` table has no features has no categories. + #[test] + fn a_face_without_features_has_no_categories() { + use crate::test_fonts::{HALF_FORM_FAMILY, half_form_font}; + let db = super::super::FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(half_form_font(false).expect("the test font builds")), 1); + let face = db.face(HALF_FORM_FAMILY, "Regular").expect("the test face"); + assert!(face.glyph_categories().is_empty()); + } + + #[test] + fn kinds_round_trip_through_their_ids() { + for kind in GlyphCategoryKind::all() { + assert_eq!(GlyphCategoryKind::from_id(&kind.id()), Some(kind)); + } + assert_eq!(GlyphCategoryKind::StylisticSet(7).features(), [*b"ss07"]); + assert_eq!(GlyphCategoryKind::StylisticSet(20).features(), [*b"ss20"]); + assert_eq!(GlyphCategoryKind::from_id("ss21"), None); + assert_eq!(GlyphCategoryKind::from_id("Ligatures"), None); + } } diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..d9b4fb47b5 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -41,10 +41,10 @@ pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; pub use fontdb::{ - CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphOrigin, IcfMargins, JoiningPosition, - LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, system_font_dirs, - user_font_dirs, + CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, GlyphAlternate, GlyphCategory, GlyphCategoryKind, + GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, PlatformFontFiles, StylisticSet, Substitution, SubstitutionKind, WantedFont, + WantedFonts, app_font_dir, is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, + style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d17ce78603..578651672f 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -901,6 +901,66 @@ pub fn capped_candidates_font() -> Option> { Some(builder.build()) } +/// The family of [`categories_font`]. +pub const CATEGORIES_FAMILY: &str = "Categorytest Sans"; + +/// The bundled Source Sans 3 Regular, its `cmap` kept, with a `GSUB` table of a `liga` ligature of +/// f and i into L, an `onum` alternate substitution of 1 by 7 and 8, an `smcp` single substitution +/// of a by B (a second subtable's substitution of a by C is shadowed by it), an `ss02` single substitution of g by G named "Round Dots" (name id 256), and a +/// `cswh` feature without lookups. Family [`CATEGORIES_FAMILY`]. `None` when it can't be built. +pub fn categories_font() -> Option> { + use write_fonts::tables::gsub::{ + AlternateSet, AlternateSubstFormat1, Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SingleSubst, SingleSubstFormat2, SubstitutionLookup, + SubstitutionLookupList, + }; + use write_fonts::tables::layout::{ + CoverageFormat1, Feature, FeatureList, FeatureParams, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord, StylisticSetParams, + }; + use write_fonts::types::GlyphId16; + + let font = skrifa::FontRef::new(SOURCE_SANS).ok()?; + let charmap = font.charmap(); + let name = name_table(&[ + (1, CATEGORIES_FAMILY), + (2, "Regular"), + (4, "Categorytest Sans Regular"), + (6, "CategorytestSans-Regular"), + (256, "Round Dots"), + ])?; + let mut builder = FontBuilder::new(); + builder.add_raw(Tag::new(b"name"), name); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let cover = |c| Some(CoverageFormat1::new(vec![gid(c)?])); + let single = |from, to| Some(SingleSubst::from(SingleSubstFormat2::new(cover(from)?.into(), vec![gid(to)?]))); + let liga = LigatureSubstFormat1::new(cover('f')?.into(), vec![LigatureSet::new(vec![Ligature::new(gid('L')?, vec![gid('i')?])])]); + let onum = AlternateSubstFormat1::new(cover('1')?.into(), vec![AlternateSet::new(vec![gid('7')?, gid('8')?])]); + let lookups = SubstitutionLookupList::new(vec![ + SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![liga])), + SubstitutionLookup::Alternate(Lookup::new(Default::default(), vec![onum])), + // The second subtable's substitution of a is never made: the first one covers a. + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('a', 'B')?, single('a', 'C')?])), + SubstitutionLookup::Single(Lookup::new(Default::default(), vec![single('g', 'G')?])), + ]); + let named = Some(FeatureParams::StylisticSet(StylisticSetParams::new(NameId::new(256)))); + // Features sorted by tag, as OpenType requires. + let records = vec![ + FeatureRecord::new(Tag::new(b"cswh"), Feature::new(None, vec![])), + FeatureRecord::new(Tag::new(b"liga"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"onum"), Feature::new(None, vec![1])), + FeatureRecord::new(Tag::new(b"smcp"), Feature::new(None, vec![2])), + FeatureRecord::new(Tag::new(b"ss02"), Feature::new(named, vec![3])), + ]; + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0, 1, 2, 3, 4])), vec![]))]); + builder.add_table(&Gsub::new(scripts, FeatureList::new(records), lookups)).ok()?; + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`joining_alternates_font`]. pub const JOINING_ALTERNATES_FAMILY: &str = "Jointest Sans"; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a6a69d9100..922e0d854f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3574,6 +3574,9 @@ digits Malayalam Малаялам Show Import Options Показване на опциите за импортиране Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Питане за опциите за импортиране на всеки PDF, DXF или текстов файл преди поставянето му; изключено: използват се последно избраните опции Stylistic Alternates Стилистични алтернативи + Ligatures Лигатури + Ornaments Орнаменти + Figures Цифри Set {n} Набор {n} Swash Декоративен елемент Swatch Conflict Конфликт на образци diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5da48b6cff..db4923e526 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2035,6 +2035,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Odaberite tekst da postavite njegove OpenType mogućnosti. Standard Ligatures Standardne ligature Stylistic Alternates Stilske alternative + Ligatures Ligature + Ornaments Ornamenti + Figures Brojke Set {n} Skup {n} Swash Ukrasni potez Tabular Lining Tabelarne brojke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e861e61fec..aca3d80f3b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4667,6 +4667,9 @@ digits Malayalam Malaiàlam Show Import Options Mostra les opcions d’importació Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demana les opcions d’importació de cada fitxer PDF, DXF o de text abans de col·locar-lo; desactivat: s’usen les últimes opcions triades Stylistic Alternates Alternatives estilístiques + Ligatures Lligadures + Ornaments Ornaments + Figures Xifres Swash Volada Swatch Conflict Conflicte de mostres Swatch Conflicts Conflictes de mostres diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1a4d359b93..bad5c0f127 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2109,6 +2109,9 @@ digits Malayalam Malajálamské Select text to set its OpenType features. Vyberte text, abyste mohli nastavit jeho funkce OpenType. Standard Ligatures Standardní ligatury Stylistic Alternates Stylistické alternativy + Ligatures Ligatury + Ornaments Ornamenty + Figures Číslice Swash Ozdobné tvary Tabular Lining Tabulkové verzálkové Tabular Oldstyle Tabulkové minuskové diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 723766f020..5ff1b8726a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2532,6 +2532,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Markér tekst for at angive dens OpenType-funktioner. Standard Ligatures Standardligaturer Stylistic Alternates Stilistiske alternativer + Ligatures Ligaturer + Ornaments Ornamenter + Figures Cifre Set {n} Sæt {n} Swash Sving Tabular Lining Tabulære versalcifre diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21a07e09e5..ac0c3f4309 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3636,6 +3636,9 @@ effect Points Punkte Show Import Options Importoptionen anzeigen Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Vor dem Platzieren nach den Importoptionen jeder PDF-, DXF- oder Textdatei fragen; aus: die zuletzt gewählten Optionen verwenden Stylistic Alternates Stilistische Varianten + Ligatures Ligaturen + Ornaments Ornamente + Figures Ziffern Swash Schwungschrift Swatch Conflict Farbfeldkonflikt Swatch Conflicts Farbfeldkonflikte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ebd167f397..e117d1b3e7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2209,6 +2209,9 @@ font-technology Variable Μεταβλητές Superscript Εκθέτης Superscript: Εκθέτης: Stylistic Alternates Εναλλακτικοί χαρακτήρες στυλ + Ligatures Συμπλέγματα χαρακτήρων + Ornaments Κοσμήματα + Figures Αριθμοί Swash Διακοσμητικά τελειώματα Swatches Δείγματα χρωμάτων New Group Νέα ομάδα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 27d7d4aaf8..2ca472a528 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3666,6 +3666,9 @@ digits Malayalam Malayálam Show Import Options Mostrar opciones de importación Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Preguntar las opciones de importación de cada archivo PDF, DXF o de texto antes de colocarlo; desactivado: usar las últimas opciones elegidas Stylistic Alternates Alternativas estilísticas + Ligatures Ligaduras + Ornaments Ornamentos + Figures Cifras Swash Decorativa Swatch Conflict Conflicto de muestras Swatch Conflicts Conflictos de muestras diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3f29fd7f7a..7792f5edce 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2070,6 +2070,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Valitse teksti, jonka OpenType-ominaisuudet haluat asettaa. Standard Ligatures Vakioligatuurit Stylistic Alternates Tyylivaihtoehdot + Ligatures Ligatuurit + Ornaments Ornamentit + Figures Numerot Swash Koukerot Tabular Lining Taulukkonumerot Tabular Oldstyle Vanhanaikaiset taulukkonumerot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20e94749c5..33ac258c2d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3658,6 +3658,9 @@ digits Malayalam Malayalam Show Import Options Afficher les options d’importation Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Demander les options d’importation de chaque fichier PDF, DXF ou texte avant de le placer, sinon utiliser les dernières options choisies Stylistic Alternates Variantes stylistiques + Ligatures Ligatures + Ornaments Ornements + Figures Chiffres Swash Lettres ornées Swatch Conflict Conflit de nuances Swatch Conflicts Conflits de nuances diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ff59a464c5..011f73a64c 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3768,6 +3768,9 @@ Styling: સ્ટાઇલિંગ: Stylistic સ્ટાઇલિસ્ટિક Stylistic Alternates સ્ટાઇલિસ્ટિક વિકલ્પી + Ligatures લિગેચર્સ + Ornaments અલંકારો + Figures અંકો Stylistic Sets સ્ટાઇલિસ્ટિક સેટ Stylize સ્ટાઇલાઇઝ Subdivisions ઉપવિભાગો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6fe8f254f4..8cdf86d7ff 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5013,6 +5013,9 @@ antiAlias Sharp शार्प Styling: स्टाइल: Stylistic स्टाइलिस्ट Stylistic Alternates शैलीगत ऑप्शन + Ligatures लिगेचर + Ornaments अलंकरण + Figures अंक Stylistic Sets स्टाइलिस्टिक सेट्स Stylize शैलीबद्ध करें Subdivisions उप-विभाजन diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a93411b47..dd65c65cb4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4361,6 +4361,9 @@ mark-style Japanese Japán Show Import Options Importálási beállítások megjelenítése Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Elhelyezés előtt rákérdez minden PDF-, DXF- vagy szövegfájl importálási beállításaira; kikapcsolva a legutóbb választott beállításokat használja Stylistic Alternates Stilisztikai változatok + Ligatures Ligatúrák + Ornaments Díszek + Figures Számjegyek Swash Cifra változatok Swatch Conflict Színminta-ütközés Swatch Conflicts Színminta-ütközések diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bf029526f7..00012d12fc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1866,6 +1866,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Pilih teks untuk mengatur fitur OpenType-nya. Standard Ligatures Ligatur standar Stylistic Alternates Alternatif gaya + Ligatures Ligatur + Ornaments Ornamen + Figures Angka Set {n} Set {n} Swash Swash Tabular Lining Lining tabular diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 360ec1d5ba..894e502236 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3712,6 +3712,9 @@ digits Malayalam Malayalam Show Import Options Mostra opzioni di importazione Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Chiedi le opzioni di importazione di ogni file PDF, DXF o di testo prima di inserirlo; disattivato: usa le ultime opzioni scelte Stylistic Alternates Alternative stilistiche + Ligatures Legature + Ornaments Ornamenti + Figures Cifre Swash Ornamentale Swatch Conflict Conflitto campioni Swatch Conflicts Conflitti campioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37089bb835..9b42649b67 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3412,6 +3412,9 @@ mark-style Japanese 日本式 Swap Fill and Stroke 塗りと線を入れ替え Swap start and end arrowheads 始点と終点の矢印を入れ替え Stylistic Alternates スタイル代替字 + Ligatures 合字 + Ornaments 装飾 + Figures 数字 Swash スワッシュ Swatch Conflict スウォッチの競合 Swatch Conflicts スウォッチの競合 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25fb4f87ed..b6eeb283db 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3923,6 +3923,9 @@ digits Malayalam მალაიალამური Select text to set its OpenType features. OpenType შესაძლებლობების დასაყენებლად მონიშნეთ ტექსტი. Standard Ligatures სტანდარტული ლიგატურები Stylistic Alternates სტილისტური ალტერნატივები + Ligatures ლიგატურები + Ornaments ორნამენტები + Figures ციფრები Swash მოხატული ასოები (swash) Tabular Lining ცხრილური ხაზოვანი Tabular Oldstyle ცხრილური ძველებური diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0787180a1c..69e7fde641 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3401,6 +3401,9 @@ mark-style Japanese 일본식 Swap Fill and Stroke 칠과 선 바꾸기 Swap start and end arrowheads 시작과 끝 화살촉 바꾸기 Stylistic Alternates 스타일 대체 글자 + Ligatures 합자 + Ornaments 장식 + Figures 숫자 Swash 스워시 Swatch Conflict 견본 충돌 Swatch Conflicts 견본 충돌 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ab30a3639f..793363b741 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2428,6 +2428,9 @@ digits Malayalam Malayalam Select text to set its OpenType features. Selecteer tekst om de OpenType-functies in te stellen. Standard Ligatures Standaardligaturen Stylistic Alternates Stilistische alternatieven + Ligatures Ligaturen + Ornaments Ornamenten + Figures Cijfers Set {n} Set {n} Swash Swash Tabular Lining Tabulaire lining diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 085935a9bd..b0cb52b855 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2027,6 +2027,9 @@ digits Malayalam Malajalam Select text to set its OpenType features. Zaznacz tekst, aby ustawić jego funkcje OpenType. Standard Ligatures Ligatury standardowe Stylistic Alternates Alternatywy stylistyczne + Ligatures Ligatury + Ornaments Ornamenty + Figures Cyfry Swash Ozdobniki Tabular Lining Tabelaryczne nowoczesne Tabular Oldstyle Tabelaryczne nautyczne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0289161fe4..4b8043cb30 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3050,6 +3050,9 @@ digits Malayalam Malaiala Swap Fill and Stroke Trocar Preenchimento e Traçado Swap start and end arrowheads Trocar pontas de seta inicial e final Stylistic Alternates Variantes Estilísticas + Ligatures Ligações + Ornaments Ornamentos + Figures Algarismos Swash Ornamento Swatch Conflict Conflito de Amostra Swatch Conflicts Conflitos de Amostra diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e45ac9423a..729d308aa4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3698,6 +3698,9 @@ digits Malayalam Малаялам Show Import Options Показывать параметры импорта Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запрашивать параметры импорта каждого файла PDF, DXF или текстового файла перед помещением; если выключено, используются последние выбранные параметры Stylistic Alternates Стилистические альтернативы + Ligatures Лигатуры + Ornaments Орнаменты + Figures Цифры Swash Росчерк Swatch Conflict Конфликт образцов Swatch Conflicts Конфликты образцов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 95e7c34b47..4c8c718a61 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3588,6 +3588,9 @@ digits Malayalam Malayalam Show Import Options Visa importalternativ Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Fråga efter importalternativ för varje PDF-, DXF- eller textfil innan den placeras; av: använd de senast valda alternativen Stylistic Alternates Stilistiska alternativ + Ligatures Ligaturer + Ornaments Ornament + Figures Siffror Swash Swash Swatch Conflict Färgrutekonflikt Swatch Conflicts Färgrutekonflikter diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d8249b1c79..c0a5ece8c4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3444,6 +3444,9 @@ digits Malayalam Malayalam Show Import Options İçe Aktarma Seçeneklerini Göster Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Her PDF, DXF veya metin dosyasını yerleştirmeden önce içe aktarma seçeneklerini sor; kapalıyken son seçilen seçenekleri kullan Stylistic Alternates Stilistik Alternatifler + Ligatures Bitişik Harfler + Ornaments Süslemeler + Figures Rakamlar Swash çalkalama Swatch Conflict Renk Örneği Çatışması Swatch Conflicts Renk Örneği Çatışmaları diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8ebb97a5be..3f7148382d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3705,6 +3705,9 @@ effect Points Точки Show Import Options Показувати параметри імпорту Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Запитувати параметри імпорту кожного файлу PDF, DXF чи текстового файлу перед розміщенням; якщо вимкнено, використовуються останні вибрані параметри Stylistic Alternates Стилістичні альтернативи + Ligatures Лігатури + Ornaments Орнаменти + Figures Цифри Swash Розчерк Swatch Conflict Конфлікт зразків Swatch Conflicts Конфлікти зразків diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a9a9cb140a..49af3b033f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4086,6 +4086,9 @@ mark-style Japanese Kiểu Nhật Show Import Options Hiện tùy chọn nhập Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last Hỏi tùy chọn nhập của từng tệp PDF, DXF hoặc văn bản trước khi đặt; khi tắt, dùng các tùy chọn đã chọn gần nhất Stylistic Alternates Ký tự thay thế theo phong cách + Ligatures Chữ ghép + Ornaments Hoa văn + Figures Chữ số Swash Swash Swatch Conflict Xung đột mẫu màu Swatch Conflicts Xung đột mẫu màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3a87e6b84..a2a371e4b5 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3525,6 +3525,9 @@ digits Malayalam 马拉雅拉姆数字 Show Import Options 显示导入选项 Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前询问每个 PDF、DXF 或文本文件的导入选项;关闭时使用上次选择的选项 Stylistic Alternates 风格替代字 + Ligatures 连字 + Ornaments 装饰字 + Figures 数字 Swash 花饰字 Swatch Conflict 色板冲突 Swatch Conflicts 色板冲突 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52715f8360..9edc6c105b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4788,6 +4788,9 @@ digits Malayalam 馬來亞拉姆數字 Show Import Options 顯示讀入選項 Ask for each PDF, DXF or text file's import options before placing it; off, use the options chosen last 置入前詢問每個 PDF、DXF 或文字檔案的讀入選項;關閉時使用上次選擇的選項 Stylistic Alternates 風格替代字 + Ligatures 連字 + Ornaments 裝飾字 + Figures 數字 Swash 花體字 Swatch Conflict 色票衝突 Swatch Conflicts 色票衝突 diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index cac85259f3..d99d4ad068 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -11,8 +11,11 @@ //! are drawn dimmed, and their tooltips say why they cannot be applied to the selection. //! With Show East Asian Options, the panel menu sets the selected characters' East Asian glyph //! form ([`glyph_form_items`]). +//! After its Unicode ranges and Alternates for Current Selection, the Show menu lists the OpenType +//! categories the browsed font has ([`vectorcraft_text::FontFace::glyph_categories`]): each shows +//! the glyphs its features give, as Entire Font shows them. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2}; use serde_json::json; @@ -72,6 +75,75 @@ const SUBSETS: [(&str, u32, u32); 7] = [ /// double-click the glyph to replace it). const ALTERNATES: &str = "Alternates for Current Selection"; +/// The Show menu's choice of an OpenType category of the browsed font, after [`ALTERNATES`]; the +/// panel state `gl-category` holds the category's id ([`vectorcraft_text::GlyphCategoryKind::id`]). +/// Public behavior: [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) +/// (with an OpenType font, a category chosen from the Show menu restricts the kinds of glyphs the +/// panel displays). Which categories are offered, their names and their order are ours. +const CATEGORY: usize = SUBSETS.len() + 1; + +/// The Show menu label of `category`: a stylistic set by the font's name for it, else `Set N`, as +/// the OpenType panel names it. +fn category_label(category: &vectorcraft_text::GlyphCategory) -> String { + use vectorcraft_text::GlyphCategoryKind as K; + match category.kind { + K::Ligatures => tl!("Ligatures").to_string(), + K::Swashes => tl!("Swash").to_string(), + K::StylisticAlternates => tl!("Stylistic Alternates").to_string(), + K::StylisticSet(number) => super::opentype::set_label(&vectorcraft_text::StylisticSet { number, name: category.name.clone() }), + K::SmallCaps => tl!("Small Caps").to_string(), + K::Ornaments => tl!("Ornaments").to_string(), + K::Fractions => tl!("Fractions").to_string(), + K::Figures => tl!("Figures").to_string(), + } +} + +/// The ids and Show menu labels of `face`'s OpenType categories, in the menu's order. +fn categories(face: Option<&vectorcraft_text::FontFace>) -> Vec<(String, String)> { + face.map(|f| f.glyph_categories().iter().map(|c| (c.kind.id(), category_label(c))).collect()).unwrap_or_default() +} + +/// The Show menu's choice: the entry index (a Unicode range, [`ALTERNATES`] or [`CATEGORY`]) and, +/// for a category, its place in `cats`. A category the browsed font does not have is Entire Font, +/// and so is an index past the entries. +fn shown(ctx: &egui::Context, cats: &[(String, String)]) -> (usize, Option) { + let subset: usize = pstate(ctx, "gl-subset"); + match subset { + CATEGORY => { + let id: String = pstate(ctx, "gl-category"); + match cats.iter().position(|c| c.0 == id) { + Some(i) => (CATEGORY, Some(i)), + None => (0, None), + } + } + s if s > CATEGORY => (0, None), + s => (s, None), + } +} + +/// Show category `id` of the browsed font. +fn show_category(ctx: &egui::Context, id: &str) { + set_pstate(ctx, "gl-category", id.to_string()); + set_pstate(ctx, "gl-subset", CATEGORY); +} + +/// The face the panel browses: the font picked in the panel, else the current text's font, else +/// the fallback family, with that family and style. The same family and style can have a different +/// face id at the selection's version or axes; that instance is used when the Type tool's selected +/// character is set in the font. +fn browsed_face(app: &VectorcraftApp, ctx: &egui::Context) -> (String, String, Option>) { + let db = FontDb::global(); + let current = super::character::text_style(app).map(|(s, _)| (s.font_family, s.font_style)); + // The panel browses the current text's font unless another font was picked here. + let picked: Option<(String, String)> = pstate(ctx, "gl-font"); + let (family, style) = picked.or(current).unwrap_or_else(|| (vectorcraft_text::FALLBACK_FAMILY.to_string(), "Regular".to_string())); + let face = selected_target(app) + .filter(|t| t.style.font_family.eq_ignore_ascii_case(&family) && t.style.font_style.eq_ignore_ascii_case(&style)) + .and_then(|t| db.style_face(t.style)) + .or_else(|| db.face(&family, &style)); + (family, style, face) +} + thread_local! { static TEX: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } @@ -226,41 +298,58 @@ fn insert(app: &mut VectorcraftApp, ctx: &egui::Context, ch: char) -> bool { /// Browse and insert glyphs from the chosen font, with font controls below the glyph grid. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - let db = FontDb::global(); - let current = super::character::text_style(app).map(|(s, _)| (s.font_family, s.font_style)); - // The panel browses the current text's font unless another font was picked here. - let picked: Option<(String, String)> = pstate(ui.ctx(), "gl-font"); - let (family, style) = picked.or(current).unwrap_or_else(|| (vectorcraft_text::FALLBACK_FAMILY.to_string(), "Regular".to_string())); - let subset: usize = pstate(ui.ctx(), "gl-subset"); + // The same family and style can have a different face id at the selection's version or axes. + // That instance is used for both the previews and Fit's applicability check. + let (family, style, face) = browsed_face(app, ui.ctx()); + let cats = categories(face.as_deref()); + let (subset, category) = shown(ui.ctx(), &cats); let (_, lo, hi) = SUBSETS[subset.min(SUBSETS.len() - 1)]; let w = ui.available_width(); - let names: Vec<&str> = SUBSETS.iter().map(|s| s.0).chain([ALTERNATES]).collect(); + // A stylistic set's name is the font's, shown as it is: the built-in labels are translated here. + let labels: Vec = + SUBSETS.iter().map(|s| tl!(s.0).to_string()).chain([tl!(ALTERNATES).to_string()]).chain(cats.iter().map(|c| c.1.clone())).collect(); + let names: Vec<&str> = labels.iter().map(String::as_str).collect(); + let current = match category { + Some(i) => CATEGORY + i, + None => subset, + }; ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Show:")).color(t.text_dim)); - if let Some(i) = widgets::dropdown(ui, "gl-subset", names[subset.min(names.len() - 1)], &names, (w - 50.0).max(80.0)) { - set_pstate(ui.ctx(), "gl-subset", i); + if let Some(i) = widgets::dropdown_names(ui, "gl-subset", names[current.min(names.len() - 1)], &names, (w - 50.0).max(80.0)) { + match i.checked_sub(CATEGORY).and_then(|k| cats.get(k)) { + Some((id, _)) => show_category(ui.ctx(), id), + None => set_pstate(ui.ctx(), "gl-subset", i), + } } }); - if subset >= SUBSETS.len() { + if subset == SUBSETS.len() { alternates(app, ui, w); font_row(app, ui, &family, &style, w); return; } - // The same family and style can have a different face id at the selection's version or axes. - // Use that instance for both the previews and Fit's applicability check. - let face = selected_target(app) - .filter(|t| t.style.font_family.eq_ignore_ascii_case(&family) && t.style.font_style.eq_ignore_ascii_case(&style)) - .and_then(|t| db.style_face(t.style)) - .or_else(|| db.face(&family, &style)); let Some(face) = face else { ui.label(egui::RichText::new(tl!("No fonts are available.")).color(t.text_dim)); return; }; - let chars: Vec<(char, u32)> = - face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect(); - // Entire Font also lists the glyphs no character maps (positional forms, alternates, - // ligatures) by glyph id, after the characters. - let unencoded = if subset == 0 { face.unencoded_glyphs() } else { Default::default() }; + let (chars, unencoded): (Vec<(char, u32)>, Vec) = match category.and_then(|i| face.glyph_categories().get(i)) { + // A category lists its glyphs that a character maps by that character, and the others by + // glyph id after them. + Some(c) => { + let wanted: HashSet = c.glyphs.iter().copied().collect(); + // A glyph several characters map is listed once, by the first of them; a glyph only a + // space or control character maps is listed by glyph id, as no character it can insert. + let mut mapped: HashSet = HashSet::new(); + let chars: Vec<(char, u32)> = + face.chars().into_iter().filter(|(c, g)| !c.is_control() && !c.is_whitespace() && wanted.contains(g) && mapped.insert(*g)).collect(); + (chars, c.glyphs.iter().copied().filter(|g| !mapped.contains(g)).collect()) + } + None => { + let chars = face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect(); + // Entire Font also lists the glyphs no character maps (positional forms, alternates, + // ligatures) by glyph id, after the characters. + (chars, if subset == 0 { face.unencoded_glyphs().to_vec() } else { vec![] }) + } + }; let total = chars.len() + unencoded.len(); let cell = CELL_STEPS[cell_index(app)]; let cols = ((w / cell).floor() as usize).max(1); @@ -1046,16 +1135,25 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { glyph_form_items(app, ui); ui.separator(); } + let (_, _, face) = browsed_face(app, ui.ctx()); + let cats = categories(face.as_deref()); + let (cur, category) = shown(ui.ctx(), &cats); for (i, (name, _, _)) in SUBSETS.iter().enumerate() { - let cur: usize = pstate(ui.ctx(), "gl-subset"); if menu_item(ui, tl!(name), true, cur == i) { set_pstate(ui.ctx(), "gl-subset", i); } } - let cur: usize = pstate(ui.ctx(), "gl-subset"); - if menu_item(ui, tl!("Alternates for Current Selection"), true, cur >= SUBSETS.len()) { + if menu_item(ui, tl!("Alternates for Current Selection"), true, cur == SUBSETS.len()) { set_pstate(ui.ctx(), "gl-subset", SUBSETS.len()); } + if !cats.is_empty() { + ui.separator(); + } + for (i, (id, label)) in cats.iter().enumerate() { + if menu_item(ui, label, true, category == Some(i)) { + show_category(ui.ctx(), id); + } + } } #[cfg(test)] @@ -1628,6 +1726,34 @@ mod tests { assert!(face.glyph_name(unencoded[0]).is_some(), "the font names its glyphs"); } + /// The panel menu lists the browsed font's OpenType categories after Alternates for Current + /// Selection, a stylistic set by the font's name for it; choosing one shows the glyphs its + /// features give and names it in Show. A font without that category shows Entire Font. + #[test] + fn the_show_menu_lists_the_fonts_opentype_categories() { + use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, HALF_FORM_FAMILY, categories_font, half_form_font}; + FontDb::global().add_font(categories_font().expect("the test font builds")); + FontDb::global().add_font(half_form_font(false).expect("the test font builds")); + let (mut app, _) = editing("a"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-font", Some((CATEGORIES_FAMILY.to_string(), "Regular".to_string()))); + let items: Vec = menu_texts(&ctx, &mut app, vec![]).into_iter().map(|(t, _)| t.trim_start_matches(['✓', ' ']).to_string()).collect(); + let at = items.iter().position(|t| t == "Alternates for Current Selection").expect("the alternates item"); + assert_eq!(items[at + 1..], ["Ligatures", "Round Dots", "Small Caps", "Figures"]); + choose(&ctx, &mut app, "Figures"); + assert_eq!(pstate::(&ctx, "gl-category"), "figures"); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "2 glyphs") && all.iter().any(|s| s == "Figures"), "{all:?}"); + choose(&ctx, &mut app, "Round Dots"); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "1 glyph") && all.iter().any(|s| s == "Round Dots"), "{all:?}"); + set_pstate(&ctx, "gl-font", Some((HALF_FORM_FAMILY.to_string(), "Regular".to_string()))); + let all = texts(&ctx, &mut app); + assert!(all.iter().any(|s| s == "Entire Font") && !all.iter().any(|s| s == "Round Dots"), "{all:?}"); + let items: Vec = menu_texts(&ctx, &mut app, vec![]).into_iter().map(|(t, _)| t.trim_start_matches(['✓', ' ']).to_string()).collect(); + assert_eq!(items.last().map(String::as_str), Some("Alternates for Current Selection"), "{items:?}"); + } + #[test] fn zoom_stops_at_the_ends() { assert_eq!(nudge_cell(CELL_DEFAULT, 1), CELL_DEFAULT + 1); diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 5db4cfbd17..fe144edbf9 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -312,8 +312,9 @@ fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { } /// A Stylistic Sets menu entry: the font's own name for the set, shown as the font gives it, or -/// `Set 1` through `Set 20` in the UI language. -fn set_label(set: &StylisticSet) -> String { +/// `Set 1` through `Set 20` in the UI language. The Glyphs panel's Show menu names its stylistic +/// set entries the same way. +pub(super) fn set_label(set: &StylisticSet) -> String { match &set.name { Some(name) => name.clone(), None => crate::i18n::fmt(tl!("Set {n}"), &[("n", &set.number.to_string())]), diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..9b98451ce2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10213,6 +10213,24 @@ off. {"name":"run_command","arguments":{"command":"text.setGlyphAlternate","params":{"id":7,"start":2,"gid":1043}}} ``` +After Alternates for Current Selection, the Glyphs panel's Show menu and panel menu list the OpenType categories the +browsed font has, and choosing one shows the glyphs its features give: characters first, then glyphs no character maps, +which a double-click applies to the selected character as Entire Font does. `text.glyphCategories {family, style?}` +lists them: `{family, style, categories: [{id, name?, glyphs: [glyph id]}]}`, from the single, alternate, multiple and +ligature substitutions of the font's `GSUB` features, each glyph once, in this order: `ligatures` (`liga`, `dlig`, +`hlig`), `swashes` (`swsh`, `cswh`), `stylisticAlternates` (`salt`), `ss01` to `ss20`, `smallCaps` (`smcp`, `c2sc`), +`ornaments` (`ornm`), `fractions` (`frac`, `afrc`, `numr`, `dnom`) and `figures` (`lnum`, `onum`, `pnum`, `tnum`). A +category without glyphs is left out, a stylistic set carries the font's name for it as `name` when the font gives one +(the menu shows that name, else Set N), and contextual lookups are not followed. Without `style` the family's first +style is used. The command refuses a family or style that is not available and a `family` or `style` that is not a +string. The categories, their features, their names and their order are VectorCraft's own; the panel restricting its +glyphs to a category chosen from the Show menu is described in [Glyphs panel +overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html). + +```json +{"name":"run_command","arguments":{"command":"text.glyphCategories","params":{"family":"Source Sans 3","style":"Regular"}}} +``` + ### Alternates as OpenType feature values `text.setGlyphAlternate`'s choice swaps a glyph id into one character and shapes that character apart from its neighbours. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..14d8c0e5f9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1428,6 +1428,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Glyphs panel's Show menu and panel menu have Alternates for Current Selection, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes. The grid lists the selected character's alternate glyphs from `GSUB` single and alternate substitutions of `aalt`, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99` and a few other alternate features, each glyph once. A double-click applies the feature that draws the variant, or a glyph choice if no supported feature draws it, as detailed below. The list uses the font of the character's text even when the panel browses another font, and the panel shows a note when the character has no alternates, its font is missing or no character is selected; these rules are VectorCraft's own. Native files keep a glyph choice with the face it was made in; another font or version draws the default glyph. Tests: `panels::glyphs::tests`, `tests::alternates`, `tests::textedit::a_glyph_alternate_replaces_one_character_through_undo_and_reopen`. The Glyphs panel's Alternates for Current Selection (#5514) applies the OpenType feature that draws the glyph to the selected character alone, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Alternates For Current Selection in the Show menu; double-click the glyph to replace the selected character). One deliberate difference from a literal reading: the text keeps the Unicode character and gains a character-style feature with a value (`salt=2`, `ss03`; `text.setRangeStyle {featureChanges}`) instead of taking an unencoded glyph in its place. The grid lists the alternates of the glyph the shaper makes for the character in its word (a medial letter shows its medial variants; the default glyph comes first and the current glyph is highlighted); a variant no supported feature draws there stays enabled as a replacement glyph (`text.setGlyphAlternate`, including positional alternates), and its tooltip says it may not join its neighbors; the default glyph takes the character's alternate features off again. Runs that differ only in their OpenType features are shaped as one piece of text, each run's features over its own characters, so the letters of an Arabic word keep their joining forms. Show › Entire Font also lists the glyphs no character maps, with the font's name for them (or `gid N`) and the feature that gives them. It applies the selected letter's contextual alternates the same way, and applies a glyph no feature reaches whose name does not belong to another letter as a glyph choice; other glyphs are dimmed with the reason. An Arabic presentation form picked there inserts its base letter. These rules are VectorCraft's own. Tests: `tests::glyph_alternates` in the text crate (a fixture font; Kufi Murabba PIIIX when it is installed), `panels::glyphs::tests` (including positional glyph choices, unlisted glyph name ownership, apply and Undo), `tests::textedit::feature_values_are_set_replaced_and_saved`. With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. + With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. From ec9c558456e07fabd4f80992b9445c98e4f9b818 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:40:31 -0800 Subject: [PATCH 37/41] .ai save: area type wrapped by plain paths, compound paths or groups stays type Area type with wrap shapes was always written as outlines in the editing data for other apps. It is now written as type when the reader works the same wrap out again from the objects above it: each wrap object is a path of one subpath, a compound path of visible members, or an unclipped group of such objects, with no paint, or a solid fill, a plain solid stroke or both, without effects, art style, opacity mask or clipping, with an offset within -1000 to 1000 pt; the type's stored shapes match the ones those objects give it; and the shapes of all area type stay within the 2,000,000 anchors the reader copies. Each frame of a thread is checked on its own. When art is left out at the object limit, such type is written as outlines again. Other wrapped area type stays outlines. The reader recomputes the wrap with resolve_wrap after reading (resolve_text_wrap in crates/eps/src/import/native/build.rs) and reads the options with text_wrap in crates/eps/src/import/ai/read/document.rs; the round-trip tests check the reopened characters, frame, wrap shapes and wrap objects. resolve_wrap's layer walk is shared through a new wrap_sources so the check follows the same traversal. --- crates/doc/src/text.rs | 2 +- crates/doc/src/text/wrap.rs | 92 +++--- crates/eps/src/ai_editing.rs | 15 + crates/eps/src/ai_editing/tests.rs | 343 ++++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 24 +- crates/eps/src/ai_editing/writer/texts.rs | 122 +++++++- crates/eps/src/import.rs | 2 +- crates/eps/src/import/native.rs | 2 +- crates/eps/src/import/native/build.rs | 2 +- docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 1 + 11 files changed, 558 insertions(+), 49 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 3964542939..2b44af5c8d 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -35,7 +35,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_work}; +pub use wrap::{resolve_wrap, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 0b5fe45dc2..29313ccb22 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use vectorcraft_geom::{PathData, shapes}; -use super::{TextKind, WrapShape}; +use super::{TextKind, TextObject, WrapShape}; use crate::{Document, Node, NodeId, NodeKind}; /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. @@ -82,6 +82,57 @@ pub fn wrap_work(doc: &Document) -> usize { total } +/// Each area text object of `layer`, from the top down, with the wrap objects above it in the +/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in +/// document coordinates. Each wrap object's outline is made once. +fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) { + let mut items = vec![]; + collect(layer, &mut items); + let mut above: Vec<(&Node, WrapShape)> = vec![]; + for it in items.iter().rev() { + match it { + Item::Wrap(n) => { + let mut pd = PathData::default(); + outline(n, &mut pd); + if !pd.is_empty() { + above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() })); + } + } + Item::Text(n) => f(n, &above), + } + } +} + +/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as +/// [`each_text`] gives them: bottom first. +fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec { + let inv = t.xf.inverse(); + above + .iter() + .rev() + .map(|(_, s)| { + let mut path = s.path.clone(); + path.transform(inv); + WrapShape { path, wrap: s.wrap } + }) + .collect() +} + +/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap +/// objects whose outlines make them, bottom first, and those shapes (text space), as +/// [`resolve_wrap`] works them out. The copying is [`wrap_work`]. +pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec)) { + for layer in &doc.layers { + each_text(layer, |n, above| { + if let NodeKind::Text(t) = &n.kind + && !above.is_empty() + { + f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above)); + } + }); + } +} + /// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the /// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged /// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes @@ -95,41 +146,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec = vec![]; - for it in items.iter().rev() { - match it { - Item::Wrap(n) => { - let mut pd = PathData::default(); - outline(n, &mut pd); - if !pd.is_empty() { - above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }); - } - } - Item::Text(n) => { - let NodeKind::Text(t) = &n.kind else { continue }; - let inv = t.xf.inverse(); - let shapes: Vec = above - .iter() - .rev() - .map(|s| { - let mut path = s.path.clone(); - path.transform(inv); - WrapShape { path, wrap: s.wrap } - }) - .collect(); - if shapes != t.wrap { - updates.push((n.id, shapes)); - } + each_text(layer, |n, above| { + if let NodeKind::Text(t) = &n.kind { + let shapes = shapes_of(t, above); + if shapes != t.wrap { + updates.push((n.id, shapes)); } } - } + }); } let mut changed = Vec::with_capacity(updates.len()); for (id, shapes) in updates { diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index f27e646791..b6ddb245c2 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -265,6 +265,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result Result { + export_held(doc, o, max_objects, true) +} + +/// [`export_within`]; with `keep_wraps`, wrapped area type the reader wraps the same is written as +/// type ([`writer::wraps_held`]). When such type is written and art is left out at the object +/// limit, the wrap objects above it may be among what is left out, and the document is written +/// again with that type as its outlines. +fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep_wraps: bool) -> Result { + let doc = source; let board = doc.artboards.first().ok_or("the document has no artboard")?.rect; if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) { return Err("the document has no artboard".into()); @@ -277,6 +286,8 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re let (symbol_styled, pattern_styled) = writer::styled_definitions(doc); let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles; let links = writer::style_links(doc); + // Before baking, which leaves the wrap objects that may be written as they are unchanged. + let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() }; // Live geometry effects as their result, as the PDF part draws them. let baked = baked(doc); let doc = baked.as_ref().unwrap_or(doc); @@ -309,6 +320,7 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re w.brushes_live = scale == 1.0; w.symbol_doc = symbol_doc; w.max_objects = max_objects; + w.wraps_held = wraps_held; w.reserve_swatch_gradients(); if scale == 1.0 { w.styled = styled; @@ -320,6 +332,9 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re for layer in &doc.layers { w.layer(layer); } + if w.wrapped_type_cut() { + return export_held(source, o, max_objects, false); + } // The symbols no instance uses too; their art adds definitions. w.symbols(); // The brushes, once the layers have said whether an object is written with one. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index c1e1d664df..61eb9d8ca3 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -11508,6 +11508,349 @@ fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f before.len() == after.len() && before.iter().zip(after).all(|(b, a)| close(&b.0, &a.0) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2) } +/// A `w` × `h` document of area type "Body" in the frame `frame`, with `over` above it (bottom +/// first), its wrap shapes resolved as the canvas resolves them. +fn wrapped_body(w: f64, h: f64, frame: Rect, over: impl FnOnce(&mut Document) -> Vec) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let mut doc = Document::new(w, h); + let layer = doc.layers[0].id; + let size = frame.height() / 20.0; + let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(size, Color::BLACK)); + body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(size, Color::BLACK))]; + body.kind = TextKind::Area { frame: shapes::rectangle(frame) }; + body.xf = Affine::IDENTITY; + let body = named(text_node(&mut doc, body), "Body"); + let over = over(&mut doc); + for n in std::iter::once(body).chain(over) { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + doc +} + +/// The characters, frame and wrap shapes of the area type on `doc`'s first layer, as it is (its +/// shapes not resolved again). +fn area_type(doc: &Document) -> Option<(String, Option, usize)> { + use vectorcraft_doc::TextKind; + doc.layers[0].children().unwrap().iter().find_map(|n| match &n.kind { + NodeKind::Text(t) if matches!(&t.kind, TextKind::Area { .. }) => { + let TextKind::Area { frame } = &t.kind else { return None }; + Some((t.runs.iter().map(|r| r.text.as_str()).collect(), frame.transformed(t.xf).bounds(), t.wrap.len())) + } + _ => None, + }) +} + +/// Area type wrapped only by plain paths, compound paths and groups that don't clip is written as +/// type and reopens as area type with its characters, its frame and the same wrap shapes, which +/// the reader works out again from the objects above it ([`crate::import`]'s +/// `resolve_text_wrap`): a filled path with a negative offset and Invert Wrap, a locked path with +/// only a stroke, a compound path, a group of two squares with a hidden member, an offset of +/// -1000 pt, and an empty group and an open line with options, which wrap nothing. +#[test] +fn area_type_wrapped_by_plain_objects_stays_type() { + type Make = fn(&mut Document) -> Vec; + fn ring(doc: &mut Document, r: Rect) -> Node { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(r), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(r.inset(-10.0)), Appearance::default()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + ring + } + let cases: [(&str, Make); 6] = [ + ("a path, a negative offset, Invert Wrap", |doc| { + vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -4.25, true)] + }), + ("a locked stroked path", |doc| { + let mut n = Node::path( + doc.alloc_id(), + shapes::ellipse(Rect::new(80.0, 30.0, 180.0, 130.0)), + Appearance::basic(Paint::None, solid(Color::BLACK), 2.0), + ); + n.locked = true; + vec![wrapped(n, 6.0, false)] + }), + ("a compound path", |doc| vec![wrapped(ring(doc, Rect::new(80.0, 30.0, 200.0, 150.0)), 7.0, true)]), + ("a group", |doc| { + let a = square(doc, Rect::new(40.0, 40.0, 80.0, 80.0), Color::gray(0.5)); + let mut hidden = square(doc, Rect::new(120.0, 40.0, 160.0, 80.0), Color::gray(0.5)); + hidden.visible = false; + let b = square(doc, Rect::new(200.0, 100.0, 240.0, 140.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![a, hidden, b], false), -2.0, false)] + }), + ("an offset of -1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), -1000.0, false)]), + ("an empty group and an open line", |doc| { + let line = Node::path( + doc.alloc_id(), + shapes::line((20.0, 20.0).into(), (280.0, 180.0).into()), + Appearance::basic(Paint::None, solid(Color::BLACK), 1.0), + ); + let empty = group(doc, vec![], false); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(n, 3.0, false), wrapped(empty, 5.0, false), wrapped(line, 5.0, false)] + }), + ]; + for (name, make) in cases { + let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make); + let before = area_type(&doc).unwrap(); + assert_ne!(before.2, 0, "{name}: the type is wrapped"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{name}: {:?}", out.warnings); + assert!(text_out.contains("/AI11Text"), "{name}"); + let back = read_back(&doc); + let after = area_type(&back).unwrap_or_else(|| panic!("{name}: no area type\n{text_out}")); + assert_eq!(after.0, before.0, "{name}"); + let (b, a) = (before.1.unwrap(), after.1.unwrap()); + assert!([b.x0 - a.x0, b.y0 - a.y0, b.x1 - a.x1, b.y1 - a.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {a:?}"); + assert_eq!(after.2, before.2, "{name}: the reader wrapped it"); + assert!(same_region(&area_wrap_region(&doc), &area_wrap_region(&back)), "{name}\n{text_out}"); + // The object that wraps it comes back as the same kind, lock and options. + let source = |d: &Document| { + let n = d.layers[0].children().unwrap()[1].clone(); + (std::mem::discriminant(&n.kind), n.locked, n.visible, n.extras().wrap) + }; + assert_eq!(source(&back), source(&doc), "{name}\n{text_out}"); + } +} + +/// Area type stays outlines when a wrap object above it is not written as itself, or its shapes +/// are not the ones the objects above it give it: an object with an effect, a blend, a symbol +/// instance, a path with a gradient, a compound path with a hidden member, a group holding type, +/// a compound path of one subpath (read back as a path), an offset past 1000 pt, a clipping group, and shapes of an object that has moved since. +#[test] +fn area_type_wrapped_by_other_objects_stays_outlines() { + type Make = fn(&mut Document) -> Vec; + let cases: [(&str, Make); 10] = [ + ("an effect", |doc| { + let n = styled_rect(doc, "Shadowed", Rect::new(100.0, 40.0, 160.0, 120.0), solid(Color::gray(0.5)), Paint::None, vec![drop_shadow()]); + vec![wrapped(n, 4.0, false)] + }), + ("a blend", |doc| { + let keys = vec![ + Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + vec![wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 4.5, false)] + }), + ("a symbol instance", |doc| { + two_leaves(doc); + vec![wrapped(instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0])), 4.5, false)] + }), + ("a gradient", |doc| { + let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]); + let ap = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None, 0.0); + vec![wrapped(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 40.0, 160.0, 120.0)), ap), 4.0, false)] + }), + ("a compound path with a hidden member", |doc| { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default()); + let mut inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 50.0, 180.0, 130.0)), Appearance::default()); + inner.visible = false; + let mut ring = + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + vec![wrapped(ring, 4.0, false)] + }), + ("a group holding type", |doc| { + let label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(100.0, 100.0), "Label", style(20.0, Color::BLACK)); + let label = text_node(doc, label); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![n, label], false), 4.0, false)] + }), + ("a compound path of one subpath", |doc| { + let only = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0)), Appearance::default()); + let mut one = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(only)], rule: FillRule::NonZero }); + one.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + vec![wrapped(one, 4.0, false)] + }), + ("an offset past 1000 pt", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 1000.5, false)]), + ("a clipping group", |doc| { + let clip = clipping(doc, shapes::rectangle(Rect::new(80.0, 30.0, 200.0, 150.0))); + let n = square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)); + vec![wrapped(group(doc, vec![clip, n], true), 4.0, false)] + }), + ("a path moved since", |doc| vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)]), + ]; + let mut typed = vec![]; + for (name, make) in cases { + let mut doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), make); + assert_ne!(area_type(&doc).unwrap().2, 0, "{name}: the type is wrapped"); + if name == "a path moved since" { + let id = doc.layers[0].children().unwrap()[1].id; + doc.node_mut(id).unwrap().transform(Affine::translate((30.0, 0.0)), false); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + if !out.warnings.iter().any(|w| w == writer::TYPE) || area_type(&read_back(&doc)).is_some() { + typed.push(name); + } + } + assert!(typed.is_empty(), "written as type: {typed:?}"); +} + +/// Each frame of threaded area type is checked on its own: a thread whose first frame is wrapped +/// by a path and a group and whose second by the group alone is written as type and reopens as the +/// same thread with the same shapes in each frame; with a blend over the second frame, the whole +/// thread is written as outlines. +#[test] +fn threaded_area_type_wrapped_by_plain_objects_stays_type() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + for blend in [false, true] { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let st = style(10.0, Color::BLACK); + let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone()); + first.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve thirteen fourteen ", st.clone())]; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 190.0, 90.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("fifteen sixteen seventeen eighteen nineteen twenty", st.clone())]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(210.0, 10.0, 390.0, 90.0)) }; + let (first, second) = (named(text_node(&mut doc, first), "First"), named(text_node(&mut doc, second), "Second")); + doc.text_threads.push(vec![first.id, second.id]); + let path = wrapped(square(&mut doc, Rect::new(60.0, 20.0, 100.0, 60.0), Color::gray(0.5)), -3.0, true); + let over_second = if blend { + let keys = vec![ + Arc::new(square(&mut doc, Rect::new(250.0, 20.0, 260.0, 30.0), Color::gray(0.5))), + Arc::new(square(&mut doc, Rect::new(340.0, 60.0, 350.0, 70.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(30.0), ..Default::default() }; + wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 2.0, false) + } else { + let a = square(&mut doc, Rect::new(250.0, 20.0, 290.0, 60.0), Color::gray(0.5)); + let b = square(&mut doc, Rect::new(120.0, 50.0, 300.0, 80.0), Color::gray(0.5)); + wrapped(group(&mut doc, vec![a, b], false), 2.0, false) + }; + // Bottom first: the first frame, the path, the second frame, the group or blend. + for n in [first, path, second, over_second] { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + type Region = Vec<(Vec<[f64; 4]>, f64, bool)>; + let shapes = |d: &Document| -> Vec { + d.layers[0] + .children() + .unwrap() + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some( + t.wrap + .iter() + .map(|s| { + let parts = s + .path + .subpaths + .iter() + .map(|sp| { + let b = PathData::new(vec![sp.clone()]).bounds().unwrap_or_default(); + [b.x0, b.y0, b.x1, b.y1] + }) + .collect(); + (parts, s.wrap.offset, s.wrap.invert) + }) + .collect(), + ), + _ => None, + }) + .collect() + }; + let before = shapes(&doc); + assert_eq!(before.iter().map(Vec::len).collect::>(), [2, 1], "blend: {blend}"); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let back = read_back(&doc); + if blend { + assert!(out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + assert!(back.text_threads.is_empty()); + continue; + } + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + assert_eq!(back.text_threads.len(), 1); + let names: Vec<_> = back.text_threads[0].iter().map(|id| back.node(*id).and_then(|n| n.name.clone())).collect(); + assert_eq!(names, [Some("First".to_string()), Some("Second".to_string())]); + let after = shapes(&back); + assert_eq!(after.len(), 2); + for (b, a) in before.iter().zip(&after) { + assert!(same_region(b, a), "{before:?}\n{after:?}"); + } + } +} + +/// Wrapped area type is written as type only while the wrap shapes of all the area type the reader +/// reads stay within what it copies: 150 frames under a wrap object of 10,000 anchors are, and +/// with 100 more frames under it, none are. +#[test] +fn area_type_wrapped_past_the_reader_limit_stays_outlines() { + use vectorcraft_doc::{TextKind, TextObject}; + let area = |doc: &mut Document| { + let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Wrapped", style(10.0, Color::BLACK)); + t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)) }; + t.xf = Affine::IDENTITY; + let n = text_node(doc, t); + doc.insert(Some(doc.layers[0].id), 0, n).unwrap() + }; + let mut doc = Document::new(100.0, 100.0); + let ids: Vec<_> = (0..150).map(|_| area(&mut doc)).collect(); + let mut zigzag = vec![(40.0, 0.0).into()]; + zigzag.extend((1..10_000).map(|i| vectorcraft_geom::Point::new(40.0 + 20.0 * f64::from(i) / 10_000.0, if i % 2 == 0 { 0.0 } else { 100.0 }))); + let n = wrapped( + Node::path(doc.alloc_id(), PathData::new(vec![vectorcraft_geom::SubPath::polyline(&zigzag, true)]), Appearance::default()), + 6.0, + false, + ); + doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap(); + vectorcraft_doc::text::resolve_wrap(None, &mut doc); + let held = writer::wraps_held(&doc, &std::collections::HashMap::new()); + assert!(ids.iter().all(|id| held.contains(id)), "{} of {}", held.len(), ids.len()); + for _ in 0..100 { + area(&mut doc); + } + assert!(vectorcraft_doc::text::wrap_work(&doc) > crate::import::MAX_WRAP_WORK); + assert!(writer::wraps_held(&doc, &std::collections::HashMap::new()).is_empty()); +} + +/// Wrapped area type stays type with room for every object, and is written as outlines when art is +/// left out at the object limit: one object short, the wrap object above it would be left out and +/// the reader would not wrap the type. +#[test] +fn area_type_wrapped_past_the_object_limit_is_written_as_outlines() { + let doc = wrapped_body(300.0, 200.0, Rect::new(10.0, 10.0, 290.0, 190.0), |doc| { + vec![wrapped(square(doc, Rect::new(100.0, 40.0, 160.0, 120.0), Color::gray(0.5)), 4.0, false)] + }); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let all = export_within(&doc, &opts(), read).unwrap(); + assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT || w == writer::TYPE), "{:?}", all.warnings); + let short = export_within(&doc, &opts(), read - 1).unwrap(); + assert!(short.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", short.warnings); + assert!(short.warnings.iter().any(|w| w == writer::TYPE), "{:?}", short.warnings); + let (back, _) = crate::ai_alone(&short.program).unwrap(); + assert!(area_type(&back).is_none(), "{}", String::from_utf8_lossy(&short.program)); +} + +/// On a large canvas, area type wrapped by a plain path is written as type and reopens with the +/// same wrap shapes, the offset at its size. +#[test] +fn area_type_wrapped_on_a_large_canvas_stays_type() { + let doc = wrapped_body(20_000.0, 20_000.0, Rect::new(1000.0, 1000.0, 9000.0, 9000.0), |doc| { + vec![wrapped(square(doc, Rect::new(3000.0, 3000.0, 5000.0, 6000.0), Color::gray(0.5)), -12.5, true)] + }); + let before = area_type(&doc).unwrap(); + assert_ne!(before.2, 0); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::TYPE), "{:?}", out.warnings); + let back = read_back(&doc); + let after = area_type(&back).expect("area type"); + assert_eq!((after.0.as_str(), after.2), (before.0.as_str(), before.2)); + let (b, a) = (area_wrap_region(&doc), area_wrap_region(&back)); + let close = b.len() == a.len() + && b.iter().zip(&a).all(|(b, a)| { + b.0.len() == a.0.len() + && b.0.iter().zip(&a.0).all(|(x, y)| x.iter().zip(y).all(|(x, y)| (x - y).abs() < 1e-2)) + && (b.1 - a.1).abs() < 1e-3 + && b.2 == a.2 + }); + assert!(close, "{b:?}\n{a:?}"); +} + /// Type written as its outlines wraps area type below it by its bounds, as it did before saving, /// not by its glyphs: its text wrap options go on an unpainted rectangle of its bounds, the last /// member of the outlines' group, which keeps the type's name and has no options of its own. diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 1b48697e32..7c211add4d 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -31,6 +31,7 @@ pub(super) use envelopes::ENVELOPES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; +pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; #[cfg(test)] @@ -49,7 +50,7 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; /// [`vectorcraft_doc::MAX_DEPTH`]. pub(super) const MAX_NEST: u32 = 8; -pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; +pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps"; pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps"; pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps"; pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; @@ -228,6 +229,10 @@ pub(super) struct Writer<'a> { bound: Vec<(vectorcraft_doc::NodeId, String, Vec)>, /// The text document: the stories of the type written as text. pub(super) texts: texts::TextDoc, + /// The area type with wrap shapes that may be written as type ([`texts::wraps_held`]). + pub(super) wraps_held: HashSet, + /// Area type with wrap shapes was written as type. + wrapped_typed: bool, /// Symbol instances on the layers may be written as instances ([`Self::live_instance`]); false /// on a large canvas, where they are written as their art. pub(super) symbols_live: bool, @@ -348,6 +353,8 @@ impl<'a> Writer<'a> { typed: false, bound: vec![], texts: texts::TextDoc::default(), + wraps_held: HashSet::new(), + wrapped_typed: false, cms: vectorcraft_color::cms::active(), body: String::new(), warnings: vec![], @@ -404,6 +411,12 @@ impl<'a> Writer<'a> { } } + /// Was area type with wrap shapes written as type, and art left out at the object limit + /// ([`Self::take_objects`])? The reader may then wrap that type by fewer objects than it had. + pub(super) fn wrapped_type_cut(&self) -> bool { + self.wrapped_typed && self.left_out > 0 + } + /// Whether `count` more objects may be written: the objects written so far, counted as the /// reader counts them ([`object_count`]), stay within [`Self::max_objects`]. Past it the art is /// left out, with a warning. @@ -1482,7 +1495,11 @@ impl<'a> Writer<'a> { let thread = doc.text_threads.iter().find(|th| th.contains(&n.id)); let contents = self.contents_level.filter(|(hidden, nest, _)| (*hidden, *nest) == (self.hidden, self.nest)); // Type that can't be a stub is written as its outlines, which count their own objects. - if (self.hidden > 0 && contents.is_none()) || self.clip.is_some() || self.in_symbol || (thread.is_none() && !texts::holds(n, t)) { + if (self.hidden > 0 && contents.is_none()) + || self.clip.is_some() + || self.in_symbol + || (thread.is_none() && !texts::holds(n, t, self.wraps_held.contains(&n.id))) + { self.outlined += 1; return self.outlined_text(n, xy); } @@ -1495,7 +1512,7 @@ impl<'a> Writer<'a> { } let placed = if let Some(thread) = thread { // A thread is checked for what it loses, in every frame, when its story is written. - let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id)); + let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); placed.map(|p| (p, self.texts.take_lost())) } else { self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) @@ -1507,6 +1524,7 @@ impl<'a> Writer<'a> { return self.outlined_text(n, xy); }; self.typed = true; + self.wrapped_typed |= !t.wrap.is_empty(); if lost { self.warn(texts::TYPE_ATTRIBUTES); } diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 9bc831e537..506d13d9fc 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -17,6 +17,7 @@ use std::collections::{HashMap, HashSet}; use std::fmt::Write; +use std::sync::Arc; use kurbo::{ParamCurveArclen, PathSeg}; use vectorcraft_color::{Color, Paint}; @@ -197,8 +198,8 @@ fn solid(p: &Paint) -> Option> { /// Can the text document hold type `t` of object `n` as it is: point type that isn't mirrored, or /// area type or type on a path that is only moved ([`shape`]); characters other than inline graphics /// and ruby; solid fills and strokes; no fills, strokes, effects or opacity mask of the object's -/// own; some text. -pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { +/// own; some text. Area type with wrap shapes only when `wrap_held` ([`wraps_held`]). +pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject, wrap_held: bool) -> bool { let xf = t.xf.as_coeffs(); let shape_ok = match &t.kind { TextKind::Point => xf.iter().all(|v| v.is_finite()) && t.xf.determinant() > 1e-12, @@ -210,10 +211,9 @@ pub(in crate::ai_editing) fn holds(n: &Node, t: &TextObject) -> bool { } }; // Area type with wrap shapes: the text document doesn't hold them. The reader works them out - // again from the art above the type, which can wrap it differently (a live object written as - // its drawn pieces) or not at all. + // again from the art above the type, which wraps it the same only where `wraps_held` says so. shape_ok - && t.wrap.is_empty() + && (t.wrap.is_empty() || wrap_held) && t.ruby.is_empty() && !t.stacks_warichu() && t.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) @@ -324,6 +324,112 @@ fn plain(n: &Node) -> bool { && n.extras().mask.is_none() } +/// The area type of `doc` whose wrap shapes the reader of the editing data works out again as they +/// are ([`vectorcraft_doc::text::resolve_wrap`], which the reader runs on what it reads): the +/// shapes are the ones the wrap objects above it give it now, and each of those objects is written +/// as itself and read back with the same outline and options ([`wrap_source_held`]), in layers +/// and groups written as they are ([`plain_containers`]). `styled`: the objects written with an +/// art style. Empty when the shapes of the document's area type would hold more anchors than the +/// reader copies into them ([`crate::import::MAX_WRAP_WORK`]). +pub(in crate::ai_editing) fn wraps_held(doc: &Document, styled: &HashMap>) -> HashSet { + let mut held = HashSet::new(); + if vectorcraft_doc::text::wrap_work(doc) > crate::import::MAX_WRAP_WORK { + return held; + } + let mut plain_in = HashSet::new(); + for layer in &doc.layers { + plain_containers(layer, true, styled, &mut plain_in); + } + let mut checked: HashMap = HashMap::new(); + vectorcraft_doc::text::wrap_sources(doc, |n, sources, shapes| { + let NodeKind::Text(t) = &n.kind else { return }; + if t.wrap.is_empty() || shapes != t.wrap || !plain_in.contains(&n.id) { + return; + } + let ok = sources.iter().all(|s| *checked.entry(s.id).or_insert_with(|| plain_in.contains(&s.id) && wrap_source_held(s, styled))); + if ok { + held.insert(n.id); + } + }); + held +} + +/// Adds to `out` the objects with text wrap options and the text objects in `n` (a top-level layer +/// when `top`) that sit only in layers and groups written as they are: layers and sublayers that +/// don't clip and have no effects, and groups that don't clip, have no fills, strokes, effects, +/// art style, opacity mask or graph and aren't written with an art style (`styled`). +fn plain_containers(n: &Node, top: bool, styled: &HashMap>, out: &mut HashSet) { + let plain = match &n.kind { + NodeKind::Layer { clip, .. } => !clip && n.appearance.effects.is_empty(), + NodeKind::Group { clip, .. } => !top && !clip && n.appearance.items.is_empty() && own_plain(n, styled), + _ => false, + }; + if !plain { + return; + } + for c in n.children().map(Vec::as_slice).unwrap_or_default() { + if c.extras().wrap.is_some() || matches!(c.kind, NodeKind::Text(_)) { + out.insert(c.id); + } + plain_containers(c, false, styled, out); + } +} + +/// Has object `n` no effects, art style, opacity mask or graph, and isn't it a ruler guide or +/// written with an art style (`styled`)? +fn own_plain(n: &Node, styled: &HashMap>) -> bool { + !styled.contains_key(&n.id) + && n.appearance.effects.is_empty() + && n.appearance.items.iter().all(|i| i.effects().is_empty()) + && n.extras().graphic_style.is_none() + && n.extras().mask.is_none() + && n.extras().graph.is_none() + && !n.is_ruler_guide() +} + +/// Is wrap object `n` written as itself and read back with the same outline and text wrap options: +/// an offset the writer and the reader keep as it is (-1000 to 1000 pt) and a plain object +/// ([`plain_wrap_art`])? +fn wrap_source_held(n: &Node, styled: &HashMap>) -> bool { + n.extras().wrap.is_some_and(|w| w.offset.is_finite() && w.offset.abs() <= 1000.0) && plain_wrap_art(n, styled) +} + +/// Is `n` written as one object of its own kind that the reader reads back with the same outline +/// ([`vectorcraft_doc::text::resolve_wrap`]): a path of one subpath, a compound path of visible +/// paths with two subpaths or more in all, each painted with no paint, a solid fill, a plain line of a solid color or both, or a +/// group that doesn't clip of such paths, compound paths and groups (hidden ones too) without text +/// wrap options of their own; each without effects, art style, opacity mask or graph +/// ([`own_plain`]). Each subpath has two anchors or more. +fn plain_wrap_art(n: &Node, styled: &HashMap>) -> bool { + use vectorcraft_doc::AppearanceItem; + let solid = |p: &Paint| matches!(p, Paint::Solid { .. }); + let painted = || match super::visible_items(n).as_slice() { + [] => true, + [AppearanceItem::Fill(f)] => solid(&f.paint), + [AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + [AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s), + _ => false, + }; + let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2); + own_plain(n, styled) + && match &n.kind { + NodeKind::Path { path, clipping: false, guide: false, .. } => path.subpaths.len() == 1 && whole(path) && painted(), + // One subpath in all would be written, and read back, as a path. + NodeKind::Compound { children, .. } => { + let subpaths: usize = children.iter().filter_map(|c| c.path_data()).map(|p| p.subpaths.len()).sum(); + let members = children.iter().all(|c| { + c.visible + && matches!(&c.kind, NodeKind::Path { path, clipping: false, guide: false, .. } if !path.subpaths.is_empty() && whole(path)) + }); + painted() && subpaths > 1 && members + } + NodeKind::Group { children, clip: false } => { + n.appearance.items.is_empty() && children.iter().all(|c| c.extras().wrap.is_none() && plain_wrap_art(c, styled)) + } + _ => false, + } +} + /// Is the end bracket of type on an open path so near the path's end that the reader reads it as /// no bracket (`Story::node`: within 0.02 of a segment)? fn end_read_as_none(t: &TextObject) -> bool { @@ -1000,7 +1106,8 @@ impl TextDoc { /// `thread` (its frames in order, all area type the document holds, the first holding the /// story) the first time one of its frames is written. `None` when the thread can't be written /// as one story: `writable` says which frames are written where type can be text (every frame - /// of the thread must be). + /// of the thread must be), and `wraps_held` which frames with wrap shapes the reader wraps the + /// same ([`wraps_held`]; every frame with wrap shapes must be one). pub(in crate::ai_editing) fn thread( &mut self, doc: &Document, @@ -1008,6 +1115,7 @@ impl TextDoc { id: NodeId, canvas: Affine, writable: &dyn Fn(NodeId) -> bool, + wraps_held: &HashSet, ) -> Option<(usize, usize)> { let first = *thread.first()?; if self.planned.insert(first) { @@ -1026,7 +1134,7 @@ impl TextDoc { && t.vertical == vertical && writable(n.id) // The text document doesn't hold wrap shapes (see `holds`). - && t.wrap.is_empty() + && (t.wrap.is_empty() || wraps_held.contains(&n.id)) && plain(n) && t.ruby.is_empty() && !t.stacks_warichu() diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6f77c141ac..4e9fcc58ae 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -96,7 +96,7 @@ pub(crate) use ai::{ pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; -pub(crate) use native::{MAX_TEXT, scale_document, scale_symbols}; +pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; pub use text::family_style; pub(crate) use text::{document_font, postscript_face}; diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 5acaba34a4..3a6347fea9 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -49,7 +49,7 @@ mod slots; #[cfg(test)] use build::{Frame, MADE, prune_unseen}; -pub(crate) use build::{scale_document, scale_symbols}; +pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; #[cfg(test)] use compare::{ MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 09368870e8..bb970debe3 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -773,7 +773,7 @@ fn settle_warped_type( } /// Most anchors copied into the wrap shapes of a file's area type ([`vectorcraft_doc::text::wrap_work`]). -const MAX_WRAP_WORK: usize = 2_000_000; +pub(crate) const MAX_WRAP_WORK: usize = 2_000_000; /// [`relayout_wrapped`], or an error when the wrap shapes would hold more than [`MAX_WRAP_WORK`] /// anchors. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7a73bdc4c1..4278489b61 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -140,7 +140,7 @@ private editing data. VectorCraft: document's defaults and the normal character style carry 1. A run with both Tate-chu-yoko and Standard Vertical Roman Alignment is written as Tate-chu-yoko, with the type attributes warning. Type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, turned or unevenly scaled area type and type on a path, area type in an open frame, - type on an open path whose ends meet, area type that flows around a text wrap, type of only white space, threads of + type on an open path whose ends meet, area type whose wrap cannot be reconstructed from plain saved paths, compound paths or groups, type of only white space, threads of type on a path, threads whose frames differ in orientation, type and stories past the sizes VectorCraft's reader reads, and type with inline graphics, ruby, gradient or pattern paint or an appearance or opacity mask of its own, other patterns, other clipping objects and live objects (placed documents included) are written as plain filled and stroked paths, and freeform gradients, gradients along diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..5514382d9d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1812,6 +1812,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes point type, area type and type on a path as type in its editing copy, and objects next to it keep their own transparency (`crates/eps/src/ai_editing/tests.rs`, `cmd::fileio::tests_pdfedit::type_comes_back_from_the_editing_copy`; [file-format-parity.md](file-format-parity.md) lists what is written as outlines). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps the document's variables, data sets and the bindings of objects to variables in its editing copy, in the form the variable library reader above reads, so they come back when the file is opened. Bindings to layers, to type written as outlines, to graphs and to linked images written as other objects, data set values of graphs, and variables, data sets, bindings and values past the writer's limits are left out with a warning (#6024; `crates/eps/src/ai_editing/tests.rs` `variables_data_sets_and_bindings_are_read_back`; `crates/eps/src/ai_editing/writer/variables.rs` lists what is left out). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps each wrap object's Text Wrap Options in its editing copy: the Offset, positive or negative, and Invert Wrap ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/wrap-or-unwrap-text-around-objects.html)), in the form the `.ai` reader reads them (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so they come back when the file is opened. An offset past the -1000 to 1000 pt the reader keeps is written as the nearer end of that range. On a large canvas the offset is written at the art's scale and comes back at its size. Art the writer draws for an object, such as a blend's steps or a symbol instance written as its art, has only that object's options, and a clipping path written as its fills and its strokes has its options once (`crates/eps/src/ai_editing/tests.rs` `text_wrap_options_are_written_and_read_back`, `drawn_art_keeps_only_its_objects_text_wrap`, `text_wrap_offsets_on_a_large_canvas_come_back_at_their_size`, `text_wrap_options_of_type_and_envelopes_are_read_back`, `a_clipping_path_written_as_its_paint_keeps_one_text_wrap`). + Area type wrapped only by plain saved paths, compound paths or groups remains editable in the `.ai` editing copy when each frame's wrap recomputes unchanged; other wrapped area type remains outlines. The `.ai` reader works the wrap out again from the objects above the type (`resolve_text_wrap` in `crates/eps/src/import/native/build.rs`), so the writer keeps type only where each wrap object is written as itself (one path with no paint, a solid fill or a plain solid stroke, a compound path of visible members, or a group of such objects, without effects, an opacity mask or clipping), its offset is within -1000 to 1000 pt, and the shapes of every area type in the file stay within the 2,000,000 anchors the reader copies; when art is left out at the object limit, such type is written as outlines. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `area_type_wrapped_by_plain_objects_stays_type`, `area_type_wrapped_by_other_objects_stays_outlines`, `threaded_area_type_wrapped_by_plain_objects_stays_type`, `area_type_wrapped_on_a_large_canvas_stays_type`, `area_type_wrapped_past_the_reader_limit_stays_outlines`, `area_type_wrapped_past_the_object_limit_is_written_as_outlines`). Type written as its outlines in the editing copy still wraps area type by its bounds, not by its glyphs, when the file is opened: the outlines' group ends with an unpainted rectangle at the type's bounds that carries its Text Wrap Options, in the form the `.ai` reader reads a path's options (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), and the group keeps the type's name (`crates/eps/src/ai_editing/tests.rs` `type_written_as_outlines_keeps_wrapping_by_its_bounds`). A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. From 05124f65d800b399ed44bd5d8f643be887b8da9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:05:16 -0800 Subject: [PATCH 38/41] File Info: a template saved without .xmp gets it, and OK waits for the merge choice Save Metadata Template adds .xmp to a name typed without it, so the templates list shows the file, and asks before replacing a file already there under the completed name. File Info's OK and Enter wait while a template being imported shows its merge choice, so the template is not dropped. docs/mcp.md now says the title is left out of a template only when it is blank or a new document's Untitled-N name. --- crates/ui-egui/src/dialogs/file_info.rs | 65 +++++++++++++++++++++++-- docs/mcp.md | 4 +- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index b9c12777a9..29ada4d271 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -37,8 +37,16 @@ const XMP_EXT: &str = "xmp"; /// Width of the text fields. const FIELD: f32 = 320.0; -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("File Info").into(), body, confirm, min_width: 500.0, max_width: Some(500.0), ..DialogSpec::FORM }; +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("File Info").into(), + body, + confirm, + // OK and Enter wait while a template being imported waits for its merge choice. + ok_enabled: Some(|_, d| !d.fields.get(IMPORT).is_some_and(Value::is_object)), + min_width: 500.0, + max_width: Some(500.0), + ..DialogSpec::FORM +}; /// Open File Info on the active document's. pub fn open(app: &mut VectorcraftApp) -> Result { @@ -168,7 +176,9 @@ fn templates_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } /// Save Metadata Template…: the fields as they are in the dialog, to a file picked in a save -/// dialog that starts in the metadata templates folder. +/// dialog that starts in the metadata templates folder. A name typed without `.xmp` takes it, so +/// the templates list shows the file; a file already there under that name is replaced only after +/// a question. fn save_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { let mut d2 = d.clone(); add_keywords(&mut d2); @@ -176,7 +186,12 @@ fn save_template(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> let name = format!("{}.{XMP_EXT}", d2.str("title").trim()); let pick = FilePick { name, folder, ..xmp_pick() }; // None: canceled, or the dialog is still open off the UI thread and runs this again. - let Some(path) = crate::picks::save(app, &pick) else { return Ok(()) }; + let Some(picked) = crate::picks::save(app, &pick) else { return Ok(()) }; + let path = if picked.to_ascii_lowercase().ends_with(&format!(".{XMP_EXT}")) { picked.clone() } else { format!("{picked}.{XMP_EXT}") }; + // The save dialog did not ask about the completed name: ask here, and the answer runs this again. + if path != picked && crate::picks::ask_to_replace(app, PickRequest::Save(pick), &picked, None, &path) { + return Ok(()); + } app.run("file.info.saveTemplate", json!({ "path": path, "fields": form::params(&d2) })).map(|_| ()) } @@ -449,4 +464,46 @@ mod tests { assert_eq!((st.doc.metadata.author.as_str(), st.doc.metadata.rating), ("Ada", 3)); assert_eq!(st.history.undo.len(), 1); } + + #[test] + fn ok_waits_for_the_merge_choice_of_a_template_being_imported() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let ok = |app: &VectorcraftApp, d: &crate::state::Dialog| super::SPEC.ok_enabled.is_none_or(|f| f(app, d)); + assert!(ok(&app, &d)); + d.fields.insert(super::IMPORT.into(), json!({"name": "Studio"})); + assert!(!ok(&app, &d), "OK and Enter wait while the merge choice is shown"); + d.fields.remove(super::IMPORT); + assert!(ok(&app, &d)); + } + + #[test] + fn a_template_saved_without_an_extension_gets_xmp_and_is_listed() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-save-ext"); + let folder = dir.join("Metadata Templates"); + let typed = folder.join("Studio").to_string_lossy().into_owned(); + let services = crate::Services { + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())), + pick_save: Some(Box::new(move |_: &crate::FilePick| Some(typed.clone()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.session.attach_metadata_templates_dir(folder.clone()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("author".into(), json!("Ada")); + crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap(); + assert!(folder.join("Studio.xmp").is_file() && !folder.join("Studio").exists(), "the typed name takes .xmp"); + let listed = app.session.execute("file.info.templates", &json!({})).unwrap(); + assert!(listed.to_string().contains("Studio"), "{listed}"); + // A file already there under the completed name is not replaced without asking. + std::fs::write(folder.join("Studio.xmp"), b"kept").unwrap(); + crate::picks::in_dialog(&mut app, &mut d, super::save_template).unwrap(); + assert_eq!(std::fs::read(folder.join("Studio.xmp")).unwrap(), b"kept"); + assert_eq!(d.kind, crate::dialogs::confirm::REPLACE, "the dialog asks before replacing it"); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 549797968f..2fc50fdba7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7609,8 +7609,8 @@ A PDF, `.ai` or `.ait` also opens with the `authorTitle` and `rating` its XMP pa Metadata templates (the menu at the top of File Info: Save Metadata Template…, Import…, the saved templates and Templates Folder; https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=278) keep File -Info fields in an XMP file. `file.info.saveTemplate {name?, path?, fields?}` writes the `title` (when it is not the -document's name), `author`, `authorTitle`, `description`, `keywords`, `rating` (from 1), `copyrightStatus`, +Info fields in an XMP file. `file.info.saveTemplate {name?, path?, fields?}` writes the `title` (when it is not blank +or the `Untitled-N` name a new document gets), `author`, `authorTitle`, `description`, `keywords`, `rating` (from 1), `copyrightStatus`, `copyrightNotice` and `copyrightUrl` that have a value as an XMP packet, using the properties listed above; the dates are left out. `fields` takes `file.info`'s editable keys in place of the document's values. `name` saves into the metadata templates folder as `.xmp` (the folder is made when it is missing; a name with characters file systems reject, a dot at either end, or a From 6aa8cb4b5eab3fcdfc3834fe031e6f5d67c5e40d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:17:05 -0800 Subject: [PATCH 39/41] File Info: Templates Folder is offered only where there is a folder The templates menu leaves out Templates Folder when the session has no metadata templates folder, as in the web build, instead of offering an item that only reports that there is none. --- crates/ui-egui/src/dialogs/file_info.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 29ada4d271..77f3218da6 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -97,11 +97,18 @@ fn xmp_pick() -> FilePick { FilePick { filters: vec![FilePick::filter("XMP metadata templates", &[XMP_EXT])], ..Default::default() } } +/// Whether the session has a metadata templates folder for Templates Folder to show (the web build +/// has none). +fn has_templates_folder(app: &VectorcraftApp) -> bool { + app.session.metadata_templates_dir().is_some() +} + /// The ≡ templates menu at the top right, and the merge choice for a template it picked. fn templates_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let can_save = crate::picks::can(app, &PickRequest::Save(xmp_pick())); let can_open = crate::picks::can(app, &PickRequest::Open(xmp_pick())); + let has_folder = has_templates_folder(app); let mut act = None; ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -150,9 +157,11 @@ fn templates_menu(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } }); } - ui.separator(); - if widgets::menu_item(ui, tl!("Templates Folder"), true, false) { - act = Some(Act::Folder); + if has_folder { + ui.separator(); + if widgets::menu_item(ui, tl!("Templates Folder"), true, false) { + act = Some(Act::Folder); + } } }); }) @@ -465,6 +474,15 @@ mod tests { assert_eq!(st.history.undo.len(), 1); } + #[test] + fn templates_folder_is_offered_only_where_there_is_one() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-folder"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert!(!super::has_templates_folder(&app), "a session without a folder, as on the web, offers no Templates Folder"); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + assert!(super::has_templates_folder(&app)); + } + #[test] fn ok_waits_for_the_merge_choice_of_a_template_being_imported() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); From 32fe097db56a9c2a474944e961e31146e7f67f0f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:36:30 -0800 Subject: [PATCH 40/41] Recolor Artwork: recolor.randomize params text parses as a params object The note on which rows keep their new color now sits in the map key's description, so tests::params::every_description_parses reads the text. --- crates/engine/src/cmd/recolor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 47e11f9e81..e85117b4ac 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Randomize Colors", [], None, - "{map: rows as recolor.apply, order?: true (shuffle the new colours among the rows that aren't excluded and hold current colours), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0; an excluded row, and a row whose from is empty, keeps its new colour} → {map: the rows with their new colours as keys}", + "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", always, randomize ), From 403ac6b7947762306f620b6f27cb7a454bb99411 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:56:47 -0800 Subject: [PATCH 41/41] Fix #7944: New Document opens in the General units and keeps units chosen in its menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New Document opened on the most recent entry in the units that entry was made in, so with Preferences › Units › General in millimeters, File › New and New Without Dialog still made documents in points, and the rulers and the Measure tool, which follow the document's units, read points. The dialog now opens in the General units on a Recent entry too. An entry made in pixels, and an entry that is a saved preset in the units it was saved in, keep their units. Before, the dialog opened in the entry's own units. Units chosen in the Units menu were also replaced by the next tab, card or preset chosen, for example the Web tab's pixels, or a Recent or Saved card's units on a click or on the double-click that creates the document. A choice made in the menu, or with ui.dialog.set (also while More Settings or Manage Profiles is open), now stays until Create. Without such a choice, clicking another Recent or Saved card still brings back that card's own units. Docs: docs/mcp.md (New Document), docs/target-app-parity.md evidence. --- crates/ui-egui/src/dialogs.rs | 3 + crates/ui-egui/src/dialogs/new_document.rs | 153 ++++++++++++++++++++- crates/ui-egui/src/panels/tests_units.rs | 56 +++++++- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 5 files changed, 209 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index fe48f28952..20955c7e96 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -605,6 +605,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &value); } + if d.kind == new_document::KIND || new_document::popup_open(d) { + new_document::note_set(d, &field); + } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); d.fields.insert(field, value); if let Some(field) = dxf { diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cfd6c3b0d3..4f48d4ad2f 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -12,7 +12,10 @@ //! `artboardLayout`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`, //! `previewMode`, `alignNewObjectsToPixelGrid`, `profile`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and //! `presetName` (Save Preset's name). Setting `preset` fills the fields from that preset; changing -//! any of them afterwards makes the settings custom. +//! any of them afterwards makes the settings custom. The dialog opens in Preferences › Units › +//! General, also on a Recent entry made in other units (one in pixels, or a saved preset in the +//! units it was saved in, keeps its units); units chosen +//! in the Units menu or set with `ui.dialog.set` stay when another tab or preset is chosen. use serde_json::{Map, Value, json}; use vectorcraft_doc::Unit; @@ -57,6 +60,9 @@ const SAVING: &str = "__saving"; /// Preset Details has drawn the saving top: set from the mode's second frame, so the first one fills /// in the default name and focuses it. const SAVING_SHOWN: &str = "__savingShown"; +/// The units were chosen in the Units menu (or set with `ui.dialog.set`): presets chosen after that +/// keep the chosen units. +const UNITS_CHOSEN: &str = "__unitsChosen"; /// The units New Document offers (all ten). const UNITS: [Unit; 10] = [ Unit::Pixels, @@ -82,17 +88,49 @@ const HEADER: f32 = 100.0; const MORE_WIDTH: f32 = 310.0; /// Open New Document on the most recent settings (or Letter), named after the next untitled -/// document. +/// document, in Preferences › Units › General. pub fn open(app: &mut VectorcraftApp) { let category = if app.session.prefs.recent_new_docs.is_empty() { "Print" } else { "Recent" }; - let first = newdoc::category(&app.session, category).and_then(|v| v.into_iter().next()).unwrap_or_default(); let mut d = Dialog::new(KIND, json!({ "category": category, "name": app.session.peek_untitled(), "advanced": false })); - apply(&mut d, &first); + if !apply_first(app, &mut d, category) { + apply(&mut d, &DocSettings { units: app.session.default_units(), ..DocSettings::default() }); + } app.ui.dialog = Some(d); } -/// Fill the fields from a preset. +/// Fill the fields from the first preset of `category`, as opening the dialog and choosing a tab +/// do; false when the category has none. The most recent entry keeps its size and takes +/// Preferences › Units › General, as the built-in presets do, unless it is in pixels or it is a +/// saved preset in the units it was saved in. Its card stays the chosen one and shows those units; +/// choosing another card brings back that card's own units. +fn apply_first(app: &VectorcraftApp, d: &mut Dialog, category: &str) -> bool { + let Some(first) = newdoc::category(&app.session, category).and_then(|v| v.into_iter().next()) else { return false }; + // `file.new` reads a named preset in its own units, and names the entry Custom in others. + let as_saved = newdoc::find(&app.session, &first.name).is_some_and(|p| p.units == first.units); + if !category.eq_ignore_ascii_case("Recent") || first.units == Unit::Pixels || as_saved { + apply(d, &first); + return true; + } + let own = first.units; + apply(d, &DocSettings { units: app.session.default_units(), ..first }); + // The card is still the entry it was: its own units say which entry it is. + if let Some(Value::Object(a)) = d.fields.get_mut(APPLIED) { + a.insert("units".into(), json!(own.label())); + } + true +} + +/// `field` of New Document `d` is about to be set by `ui.dialog.set`: setting the units is a choice +/// that presets chosen after it keep. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if field == "units" { + d.fields.insert(UNITS_CHOSEN.into(), json!(true)); + } +} + +/// Fill the fields from a preset, keeping the units when they were chosen in the Units menu. fn apply(d: &mut Dialog, s: &DocSettings) { + let chosen = if d.bool(UNITS_CHOSEN) { d.fields.get("units").cloned() } else { None }; let Value::Object(mut v) = s.to_json() else { return }; for k in ["size", "orientation"] { v.remove(k); @@ -105,6 +143,9 @@ fn apply(d: &mut Dialog, s: &DocSettings) { d.fields.insert(k.clone(), val.clone()); } d.fields.insert(APPLIED.into(), Value::Object(v)); + if let Some(u) = chosen { + d.fields.insert("units".into(), u); + } } /// Keep the fields and the chosen preset in step: a new `preset` (also from `ui.dialog.set`) fills @@ -305,8 +346,8 @@ fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if let Some(i) = widgets::tab_bar(ui, &names, cat) { d.fields.insert("category".into(), json!(names[i])); // A tab opens on its first preset, so the details match its cards. - if let Some(first) = names.get(i).and_then(|c| newdoc::category(&app.session, c)).and_then(|v| v.into_iter().next()) { - apply(d, &first); + if let Some(c) = names.get(i) { + apply_first(app, d, c); } } let list = names.get(cat).and_then(|c| newdoc::category(&app.session, c)).unwrap_or_default(); @@ -705,6 +746,7 @@ fn units_dropdown(ui: &mut egui::Ui, d: &mut Dialog, width: f32) { let labels = UNITS.map(Unit::label); if let Some(u) = widgets::dropdown(ui, "newdoc-units", unit(d).label(), &labels, width).and_then(|i| UNITS.get(i)) { d.fields.insert("units".into(), json!(u.label())); + d.fields.insert(UNITS_CHOSEN.into(), json!(true)); } } @@ -1569,6 +1611,103 @@ mod tests { assert!(h.state().session.active().unwrap().doc.setup.align_new_objects_to_pixel_grid); } + /// Create, then the new document's units. + fn create(h: &mut Harness) -> vectorcraft_doc::Unit { + h.get_by_label("Create").click(); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.status); + h.state().session.active().unwrap().doc.units + } + + /// With Preferences › Units › General in millimeters, New Document opens on the most recent + /// entry in millimeters even though that entry was made in points, and New Without Dialog makes + /// the same document. An entry in pixels stays in pixels, as the screen presets do. + #[test] + fn the_dialog_opens_in_the_general_units_over_a_recent_entry() { + use vectorcraft_doc::Unit::{Millimeters as Mm, Pixels as Px}; + let mut h = big(); + h.state_mut().run("file.new", json!({"units": "Points"})).unwrap(); + h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap(); + assert_eq!(h.state().session.prefs.recent_new_docs[0].units, vectorcraft_doc::Unit::Points); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + h.run_steps(3); + assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Recent"), json!("Millimeters"))); + assert_eq!(create(&mut h), Mm, "the dialog's Create"); + h.state_mut().run("file.new", json!({"units": "Points"})).unwrap(); + h.state_mut().run("file.newWithoutDialog", json!({})).unwrap(); + assert_eq!(h.state().session.active().unwrap().doc.units, Mm, "New Without Dialog"); + h.state_mut().run("file.new", json!({"preset": "Web 1920×1080"})).unwrap(); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(field(h.state(), "units"), json!("Pixels")); + assert_eq!(create(&mut h), Px); + } + + /// A Recent entry that is a saved preset in the units it was saved in opens in those units, so + /// Create keeps the preset's name in Recent; the General unit is millimeters. + #[test] + fn a_recent_saved_preset_keeps_its_units_and_name() { + let mut h = big(); + h.state_mut().run("file.newPresets.save", json!({"name": "Zine", "width": "5.5 in", "height": "8.5 in", "units": "Inches"})).unwrap(); + h.state_mut().run("file.new", json!({"preset": "Zine"})).unwrap(); + h.state_mut().run("prefs.set", json!({"key": "unitsGeneral", "value": "Millimeters", "documentUnits": false})).unwrap(); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + h.run_steps(3); + assert_eq!((field(h.state(), "preset"), field(h.state(), "units")), (json!("Zine"), json!("Inches"))); + assert_eq!(create(&mut h), vectorcraft_doc::Unit::Inches); + let recent = &h.state().session.prefs.recent_new_docs; + assert_eq!((recent.len(), recent[0].name.as_str()), (1, "Zine"), "{recent:?}"); + } + + /// Units set with `ui.dialog.set` while More Settings or Manage Profiles is open stay chosen + /// when a preset is chosen after them. + #[test] + fn units_set_over_a_popup_stay_chosen() { + for popup in [super::MORE, super::PROFILES] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.kind = popup.into(); + crate::dialogs::set_field(d, "units".into(), json!("Millimeters")); + crate::dialogs::set_field(d, "preset".into(), json!("A4")); + d.kind = super::KIND.into(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!((field(&app, "preset"), field(&app, "units")), (json!("A4"), json!("Millimeters")), "{popup}"); + } + } + + /// Millimeters chosen in the Units menu stay chosen when another tab or preset is chosen after + /// them, and reach the new document. + #[test] + fn units_chosen_in_the_menu_survive_tabs_and_presets() { + use vectorcraft_doc::Unit::Millimeters as Mm; + let mut h = big(); + assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!("Print"), json!("Points"))); + h.get_by_role_and_label(Role::ComboBox, "Units").click(); + h.run_steps(3); + h.get_by_label("Millimeters").click(); + h.run_steps(3); + assert_eq!(field(h.state(), "units"), json!("Millimeters")); + // A Recent entry made in inches, which the Recent tab opens on. + h.state_mut().run("file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})).unwrap(); + for tab in ["Web", "Recent", "Print"] { + h.get_by_role_and_label(Role::Button, tab).click(); + h.run_steps(3); + assert_eq!((field(h.state(), "category"), field(h.state(), "units")), (json!(tab), json!("Millimeters")), "the {tab} tab"); + } + // A preset chosen by name, as `ui.dialog.set` chooses it. + crate::dialogs::set_field(h.state_mut().ui.dialog.as_mut().unwrap(), "preset".into(), json!("A4")); + h.run_steps(3); + assert_eq!( + (field(h.state(), "width"), field(h.state(), "units")), + (json!(vectorcraft_doc::Unit::Millimeters.to_pt(210.0)), json!("Millimeters")) + ); + assert_eq!(create(&mut h), Mm); + } + /// A long translation of Align New Objects to Pixel Grid wraps inside the Preset Details column. #[test] fn align_new_objects_label_wraps_inside_the_details_column() { diff --git a/crates/ui-egui/src/panels/tests_units.rs b/crates/ui-egui/src/panels/tests_units.rs index 687174e839..ce9900fdf8 100644 --- a/crates/ui-egui/src/panels/tests_units.rs +++ b/crates/ui-egui/src/panels/tests_units.rs @@ -174,15 +174,17 @@ fn new_document_cards_follow_the_chosen_units() { /// Choosing units in Preset Details changes the chosen document, not every recent one: each card /// keeps the units its document was made in, so switching between inches and millimetres leaves the -/// other templates as they were; choosing another card brings its units back. +/// other templates as they were; choosing another card brings its units back while no units were +/// chosen in the Units menu. #[test] fn recent_cards_keep_their_own_units() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - // 8.5 × 11 in, then 210 × 297 mm, which Recent lists first and the dialog opens on. + // 8.5 × 11 in, then 210 × 297 mm, which Recent lists first and the dialog opens on, in + // Preferences › Units › General (points). run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); run(&mut app, "file.new", json!({"width": "210 mm", "height": "297 mm", "units": "Millimeters"})); app.run("file.newDialog", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["units"], json!("Millimeters")); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["units"], json!("Points")); app.ui.dialog.as_mut().unwrap().fields.insert("units".into(), json!("Points")); let t = dialog_texts(&mut app); assert!(shows(&t, "595.276 × 841.89 pt"), "the chosen entry in points: {t:?}"); @@ -200,6 +202,54 @@ fn recent_cards_keep_their_own_units() { assert_eq!((d.fields["width"].clone(), d.fields["height"].clone()), (json!(612.0), json!(792.0))); } +/// Units chosen in the Units menu (here through `ui.dialog.set`) stay chosen when a Recent card made +/// in other units is clicked, and the document is made in them. +#[test] +fn a_recent_card_keeps_the_units_chosen_in_the_menu() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "210 mm", "height": "297 mm", "units": "Millimeters"})); + app.run("file.newDialog", json!({})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "units".into(), json!("Millimeters")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut draw = |app: &mut VectorcraftApp, ui: &mut Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], &mut draw); // the window sizes itself here + let inches = text_rect(&frame_events(&ctx, &mut app, vec![], &mut draw), "8.5 × 11 in").center(); + click(&ctx, &mut app, inches, &mut draw); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["width"].clone(), d.fields["units"].clone()), (json!(612.0), json!("Millimeters"))); + crate::dialogs::confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.units, doc.artboards[0].rect.width()), (Unit::Millimeters, 612.0)); +} + +/// A double-click on a Recent or Saved card made in inches creates the document in the millimeters +/// chosen in the Units menu (here through `ui.dialog.set`) before it. +#[test] +fn a_double_clicked_card_keeps_the_units_chosen_in_the_menu() { + for category in ["Recent", "Saved"] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + run(&mut app, "file.newPresets.save", json!({"name": "Letter in", "width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "210 mm", "height": "297 mm", "units": "Millimeters"})); + app.run("file.newDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("category".into(), json!(category)); + crate::dialogs::set_field(d, "units".into(), json!("Millimeters")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut draw = |app: &mut VectorcraftApp, ui: &mut Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], &mut draw); // the window sizes itself here + let card = text_rect(&frame_events(&ctx, &mut app, vec![], &mut draw), "8.5 × 11 in").center(); + click(&ctx, &mut app, card, &mut draw); + click(&ctx, &mut app, card, &mut draw); + assert!(app.ui.dialog.is_none(), "the {category} card's double-click creates: {:?}", app.ui.status); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.units, doc.artboards[0].rect.width()), (Unit::Millimeters, 612.0), "the {category} card"); + } +} + /// A saved preset keeps the units it was saved in too, whichever units the dialog is showing. #[test] fn saved_cards_keep_their_own_units() { diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..ecd2a906eb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7011,8 +7011,12 @@ A saved or Recent preset whose size (up to 3,999,856 pt), `artboards` (1 to 1,000), spacing (0 to 100,000 pt) or bleed (0 to 72 pt a side) lies outside those ranges is read with the nearer end of each range, and a size of 0 or less is read as 1 pt. The desktop app's `file.newDialog` (Cmd/Ctrl+N) opens the New Document dialog on the first Recent entry, or on the -Print category's Letter while Recent is empty. `file.newWithoutDialog` (Cmd/Ctrl+Alt+N) runs `file.new` with those -settings and the next untitled name, without opening the dialog, and returns what `file.new` returns. +Print category's Letter while Recent is empty. The dialog opens in Preferences › Units › General (`unitsGeneral`), +also when the Recent entry was made in other units. An entry made in pixels, and an entry that is a saved preset in +the units it was saved in, keep their units. Clicking another Recent or Saved card brings back the units that card was +made in. Units chosen in the dialog's Units menu, or set with `ui.dialog.set` (the `units` field), stay when another +tab or preset is chosen. These are VectorCraft's own rules. `file.newWithoutDialog` (Cmd/Ctrl+Alt+N) runs `file.new` +with those settings and the next untitled name, without opening the dialog, and returns what `file.new` returns. `window.nextDocument` (Cmd/Ctrl+F6) and `window.previousDocument` (Cmd/Ctrl+Shift+F6) make the next and the previous open document in tab order the current one, as a click on its tab does, and return `{index}`. After the last document comes the first, and before the first document comes the last. From the Home screen they go to the first and the last diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..8cf6695765 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -770,6 +770,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. When a document tagged with a profile other than the working space is opened, reverted or opened as a template, the policy keeps the profile, takes it off with the color numbers kept, or converts that model's colors into the working space, with black point compensation as Color Settings set it, and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules; placed images and the Profile Mismatches and Missing Profiles prompts are not covered. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `color/src/cms/tests_icc.rs`. +- **New Document's units:** the dialog opens in Preferences › Units › General, also on a Recent entry made in other units (an entry in pixels, or a saved preset in the units it was saved in, keeps its units), so File › New and New Without Dialog make documents in the General unit. Units chosen in the Units menu stay when another tab or preset is chosen and when a card is clicked or double-clicked; without such a choice, clicking another Recent or Saved card brings back the units that card was made in (#7944). These are VectorCraft's own rules. Tests: `the_dialog_opens_in_the_general_units_over_a_recent_entry`, `a_recent_saved_preset_keeps_its_units_and_name`, `units_chosen_in_the_menu_survive_tabs_and_presets` and `units_set_over_a_popup_stay_chosen` in `dialogs/new_document.rs`; `a_recent_card_keeps_the_units_chosen_in_the_menu` and `a_double_clicked_card_keeps_the_units_chosen_in_the_menu` in `panels/tests_units.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy).