From efd57a4a5de91fb2630df973901bdc3b456dedb1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:31:22 -0800 Subject: [PATCH 01/54] 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 1bbca6efb5d5c21412bc6b3ff8c32a8acff9b1b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:17:16 -0800 Subject: [PATCH 02/54] 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 b3a056b7fdf7d30e31f0f8a6b98cd219311c2262 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:59:36 -0800 Subject: [PATCH 03/54] 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 f9a2abad18eb1891e7ea1c107836138bcb149f16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:01:23 -0800 Subject: [PATCH 04/54] Paragraph: Kurikaeshi Moji Shori draws a line-start repeat mark as the character it repeats MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Paragraph panel menu > Kurikaeshi Moji Shori (text.setFormat {kurikaeshiMojiShori}) is a paragraph attribute, off by default, saved only when on and carried by paragraph styles. On, a repeat mark (々, ゝ, ゞ, ヽ, ヾ) that starts a line of point or area type is drawn as the character it repeats, with the mark's width, and the text keeps the mark. Threaded type looks back into the frames before when a paragraph continues. Live SVG text writes the drawn character and places the text after it. --- crates/doc/src/live/envelope.rs | 1 + crates/doc/src/text.rs | 6 + crates/doc/src/text/object.rs | 1 + crates/doc/src/text/para_style.rs | 9 ++ crates/engine/src/cmd/panelcmds.rs | 6 +- crates/engine/src/cmd/textedit.rs | 2 + crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/threads.rs | 36 +++++- crates/engine/src/cmd/threads/tests.rs | 36 ++++++ crates/engine/src/cmd/typecmd/area_tests.rs | 56 +++++++++ crates/svg/src/export/text.rs | 27 ++++- crates/svg/tests/it/text_layout.rs | 31 +++++ crates/text/src/layout/flow.rs | 45 ++++++- crates/text/src/lib.rs | 7 +- crates/text/src/shape.rs | 59 ++++++++++ crates/text/src/test_fonts.rs | 53 +++++++++ crates/text/src/tests.rs | 117 +++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/paragraph.rs | 17 ++- crates/ui-egui/src/panels/paragraph/tests.rs | 31 +++++ docs/mcp.md | 24 ++++ docs/type-parity.md | 1 + 49 files changed, 583 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 5aa43b0a67..a0ad0eb1e4 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> { let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits))); for h in &mut feed.0 { h.write_u8(u8::from(text.first_para_continues)); + h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from)); for b in inline_bounds.clone() { match b { None => h.write_u8(0), diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index d165a086fb..064f18effe 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -67,6 +67,12 @@ pub struct TextObject { /// it on a frame that leaves its thread and on a copy. Not saved. #[serde(skip)] pub first_para_continues: bool, + /// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the + /// last character of that paragraph in the frames before that a repeat mark could stand for + /// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout + /// reads it only while `first_para_continues` is on. Not saved. + #[serde(skip)] + pub first_para_lead: Option, /// Area Type Options (area type only). #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub area: AreaOptions, diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index b787cebfe0..617d860927 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -94,6 +94,7 @@ impl TextObject { para: ParaStyle::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: AreaOptions::default(), path_effect: PathEffect::default(), path_align: PathAlign::default(), diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index c3db242ed0..62c6b8dd33 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -271,6 +271,9 @@ pub struct ParaStyle { /// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept /// with kinsoku None, where it has no effect. Off by default. pub bunri_kinshi: bool, + /// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts + /// a line is drawn as the character it repeats, and the text keeps the mark. Off by default. + pub kurikaeshi_moji_shori: bool, /// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and /// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses, /// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari. @@ -375,6 +378,8 @@ struct ParaStyleFile { #[serde(default, skip_serializing_if = "crate::skip::is_default")] bunri_kinshi: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] + kurikaeshi_moji_shori: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] roman_hanging: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kashida: Kashida, @@ -412,6 +417,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -439,6 +445,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -470,6 +477,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -496,6 +504,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 20905ffdae..e012257c53 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default),direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away in horizontal type), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -522,6 +522,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "romanHangingPunctuation", "koreanLineBreakAnywhere", "bunriKinshi", + "kurikaeshiMojiShori", ], C, )?; @@ -597,6 +598,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "kinsoku", "kinsokuType", "bunriKinshi", + "kurikaeshiMojiShori", "direction", "leadingModel", "charAlign", @@ -989,6 +991,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = flag("bunriKinshi") { para.bunri_kinshi = v; } + // An omitted or null value keeps the paragraph's own. + para.kurikaeshi_moji_shori = flag("kurikaeshiMojiShori").unwrap_or(para.kurikaeshi_moji_shori); if let Some(v) = direction { para.direction = v; } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 769ca7e6c5..0602e23a9a 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1806,6 +1806,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { para: super::create::new_type_para(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), @@ -2112,6 +2113,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option { para: Default::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 18f87d44f7..a6878032b0 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -253,6 +253,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map { ("kinsoku", json!(v.kinsoku)), ("kinsoku_type", json!(v.kinsoku_type)), ("bunri_kinshi", json!(v.bunri_kinshi)), + ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), ("roman_hanging", json!(v.roman_hanging)), ("kashida", json!(v.kashida)), ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index ad41d1d220..7ccf26d3de 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { .collect(); let refs: Vec<&TextObject> = frames.iter().collect(); let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s); - for (id, part) in live.iter().zip(parts) { + let texts: Vec = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect(); + let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::>()); + for ((id, part), lead) in live.iter().zip(parts).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) { let mut next = (**t).clone(); next.runs = part.runs; @@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { || part.list_count != t.list_count || part.list_level_counts != t.list_level_counts || continues != t.first_para_continues + || lead != t.first_para_lead { t.runs = next.runs; t.para = next.para; @@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { t.list_count = part.list_count; t.list_level_counts = part.list_level_counts; t.first_para_continues = continues; + t.first_para_lead = lead; refresh_bounds(t); } } @@ -384,17 +388,43 @@ pub(crate) fn mark_continued(doc: &mut Document) { let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect(); let marks = vectorcraft_text::thread::continued(&frames); - for (id, on) in live.iter().zip(marks) { + let texts: Vec = frames.iter().map(|t| t.plain_text()).collect(); + let leads = first_para_leads(&texts, &marks); + for ((id, on), lead) in live.iter().zip(marks).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) - && t.first_para_continues != on + && (t.first_para_continues != on || t.first_para_lead != lead) { t.first_para_continues = on; + t.first_para_lead = lead; refresh_bounds(t); } } } } +/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and +/// whether each one's first paragraph `continues` from the frame before: the last character of +/// that paragraph in the frames before that a repeat mark could stand for, or None. +fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec> { + (0..texts.len()) + .map(|k| { + let mut j = k; + while continues.get(j) == Some(&true) && j > 0 { + j -= 1; + let text = texts.get(j)?; + let tail = text.rfind('\n').map_or(Some(text.as_str()), |at| text.get(at + 1..))?; + if let Some(c) = vectorcraft_text::repeat_base(tail) { + return Some(c); + } + if tail.len() != text.len() { + return None; + } + } + None + }) + .collect() +} + #[cfg(test)] thread_local! { /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 2694a61e6c..ba2cbaa1d4 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2226,3 +2226,39 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing() assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0); } + +/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of +/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that +/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph +/// carries none. Flowing the story and opening a file both set it. +#[test] +fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { + let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::>(), continues); + assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]); + assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]); + assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]); + assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]); + assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]); + assert_eq!(leads(&[], &[]), Vec::>::new()); + // Opening a file marks the frames as they were saved. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let mut ids = Vec::new(); + for (x, text) in [(10, "日時"), (200, "々す")] { + let id = + s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + ids.push(NodeId(id)); + } + let mut d = (*s.doc().unwrap().doc).clone(); + d.text_threads = vec![ids.clone()]; + mark_continued(&mut d); + let tb = text_of(&d, ids[1]).unwrap(); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, Some('時')); + // Flowing the story through the frames sets it from the text each frame now holds. + reflow(&d.clone(), &mut d); + let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap()); + assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す"); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); +} diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index a63ebff9c4..6cff9a95a4 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -504,6 +504,62 @@ fn bunri_kinshi_is_set_per_paragraph_and_saved_only_when_on() { assert!(!text(&s).para_at(0).bunri_kinshi && !text(&s).para_at(1).bunri_kinshi); } +/// Paragraph panel menu › Kurikaeshi Moji Shori: off for new type and for a paragraph saved before +/// it, and saved only when on; `text.setFormat {kurikaeshiMojiShori}` sets it per paragraph in one +/// undo step, records nothing when the paragraphs already have the value, refuses a value that is +/// not true or false, and paragraph styles carry it. The text keeps its repeat marks. +#[test] +fn kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "時々\nすゝ"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori, "new type has it off"); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("kurikaeshi_moji_shori").is_none()); + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(!old.kurikaeshi_moji_shori, "saved before the option: off"); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the second paragraph. + let second = "時々\n".len(); + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(text(&s).plain_text(), "時々\nすゝ", "the text keeps its marks"); + // The same value again records nothing. + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let saved = serde_json::to_value(text(&s).para_at(1)).unwrap(); + assert_eq!(saved["kurikaeshi_moji_shori"], true); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(saved).unwrap(); + assert!(back.kurikaeshi_moji_shori); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert!(!back.para_at(0).kurikaeshi_moji_shori && back.para_at(1).kurikaeshi_moji_shori, "the file keeps it per paragraph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(1).kurikaeshi_moji_shori); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"ids": [id], "kurikaeshiMojiShori": bad, "kinsoku": "none"})).is_err(), "{bad}"); + } + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "kurikaeshiMojiShori": false})).is_err()); + assert!( + text(&s).para_at(1).kurikaeshi_moji_shori && text(&s).para_at(1).kinsoku != vectorcraft_doc::Kinsoku::None, + "a refused call changes nothing" + ); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Repeats", "attrs": {"kurikaeshi_moji_shori": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Repeats", "id": id})).unwrap(); + assert!(text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("paraStyle.new", &json!({"name": "Marks", "attrs": {"kurikaeshi_moji_shori": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Marks", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && !text(&s).para_at(1).kurikaeshi_moji_shori); +} + /// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one /// undo step, the paragraph is saved with it only when it is not None and opens with it, an /// unknown value changes nothing, and paragraph styles carry it. diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 2f8e8b8a1b..5a1e811062 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -491,7 +491,11 @@ impl Writer<'_> { }); let Some(chars) = self.fonts.get_mut(at).map(|u| &mut u.chars) else { continue }; // As written: a list marker's characters, a hyphen where a line breaks, capitals for All - // Caps, the style's Digits. + // Caps, the style's Digits, the character a repeat mark is drawn as. + if let Some(c) = shown_repeat(lay, i, g) { + chars.insert(c); + continue; + } let src = lay.marker_text(i).unwrap_or_else(|| if g.len == 0 { "-" } else { plain.get(g.byte..g.byte + g.len).unwrap_or("") }); for c in src.chars().filter(|c| !c.is_control() && *c != '\u{ad}').map(|c| st.digits.map(c)) { if st.all_caps { @@ -716,6 +720,17 @@ struct Segment { /// given its own position (points). const PLACE_TOLERANCE: f64 = 1e-6; +/// Kurikaeshi Moji Shori: the character glyph `i` of `lay` shows when the layout drew a repeat mark +/// as the character it repeats ([`vectorcraft_text::TextLayout::repeat_marks`]), or None. +fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_text::PositionedGlyph) -> Option { + if lay.repeat_marks.is_empty() || g.len == 0 || lay.marker_text(i).is_some() { + return None; + } + // The marks are in text order, one per line. + let at = lay.repeat_marks.binary_search_by_key(&g.byte, |&(byte, _)| byte).ok()?; + lay.repeat_marks.get(at).map(|&(_, c)| c) +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -804,9 +819,15 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - } None => (g.advance, g.origin.x), }; - let src: String = source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(); + let repeat = shown_repeat(lay, line.glyph_start + k, g); + let src: String = match repeat { + Some(c) => c.to_string(), + None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), + }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; - let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)); + // The character a repeat mark is drawn as takes the mark's width on the canvas, which a + // reader does not know: the text after it is placed anew. + let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)) || repeat.is_some(); // A glyph Glyph Scaling widens or narrows is a segment of its own, stretched to its width. let scale = if reader.is_some() && (g.scale - 1.0).abs() > 1e-9 && g.scale.is_finite() { g.scale } else { 1.0 }; let fresh = std::mem::take(&mut after_inline) || scale != 1.0 || segs.last().is_some_and(|last| last.scale != 1.0); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index c53318c358..a190f21dea 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -910,3 +910,34 @@ fn paragraphs_aligned_differently_keep_their_alignment() { assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.01); } } + +/// With Kurikaeshi Moji Shori on, live type writes a repeat mark that starts a line as the +/// character it is drawn as and places the text after it anew, with and without embedded fonts; a +/// mark inside a line stays. +#[test] +fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), ..style(12.0) }; + for on in [false, true] { + let mut t = TextObject::point(Point::new(20.0, 40.0), "龘\u{2028}々龘龘々", st.clone()); + t.para.kurikaeshi_moji_shori = on; + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + for embed_fonts in [false, true] { + let svg = export(&d, &ExportOptions { embed_fonts, ..Default::default() }); + if !on { + assert!(svg.contains(">々龘龘々<"), "{svg}"); + continue; + } + // The drawn character takes the mark's width on the canvas, so the text after it is + // placed where the canvas draws it. + let rest = svg.find(">龘龘々<").unwrap_or_else(|| panic!("{svg}")); + let tag = &svg[svg[..rest].rfind('<').unwrap_or(0)..rest]; + assert!(tag.contains(" x=\""), "{tag}: {svg}"); + assert_eq!(svg.matches('々').count(), 1, "only the mark inside the line stays: {svg}"); + } + } +} diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 0c4e1ae615..f028d47898 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -13,7 +13,7 @@ use super::{ is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words}; +use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeated_char, shape_range}; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? @@ -213,6 +213,9 @@ struct ParagraphData<'a, 'text> { bidi: Option>, rtl: bool, continued: bool, + /// Kurikaeshi Moji Shori: the character before a `continued` paragraph in the frames before + /// ([`TextObject::first_para_lead`]). + lead: Option, sg: Vec, compressed: Vec, wakan: Vec, @@ -331,6 +334,7 @@ fn prepare_paragraph<'a, 'text>( bidi, rtl, continued, + lead: t.first_para_lead.filter(|_| continued), sg, compressed, wakan, @@ -1272,6 +1276,40 @@ fn emit_line_glyph( cx.emit(glyph, Affine::translate(at.to_vec2()), at, 0.0, w.advance, line_index); } +/// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of +/// a line of the paragraph starting at byte `para_start`, when `g` is a repeat mark, and the +/// character it shows: the character [`repeated_char`] gives, shaped in the mark's style with the +/// type's features (so vertical type gets the font's vertical forms), from the same face, with the +/// mark's advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, +/// belongs to a tate-chu-yoko or warichu block, nothing before it in the paragraph fits, or the face +/// draws the character with no glyph or with more than one. `lead` stands before a paragraph that +/// continues from the frame before ([`TextObject::first_para_lead`]). +fn repeat_mark_glyph(cx: &Ctx<'_>, para_start: usize, lead: Option, g: &SGlyph) -> Option<(SGlyph, char)> { + if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() { + return None; + } + let c = repeated_char(lead, cx.text.get(para_start..g.byte)?, g.ch)?; + let mut buf = [0; 4]; + let s: &str = c.encode_utf8(&mut buf); + let mut shaped = Vec::with_capacity(1); + shape_range(cx.db, s, 0..s.len(), &[(0..s.len(), cx.style_at(g.byte))], &[], &cx.opts.features, &[], &mut shaped); + let [one] = shaped.as_slice() else { return None }; + (one.gid != 0 && one.face.id() == g.face.id()).then(|| (SGlyph { gid: one.gid, ..g.clone() }, c)) +} + +/// Kurikaeshi Moji Shori: the glyph drawn in place of glyph `first` of `paragraph`, the first +/// character of a line that ends before glyph `end`, when the paragraph has the setting on and +/// [`repeat_mark_glyph`] gives one; it is recorded in [`crate::TextLayout::repeat_marks`]. +fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: usize, end: usize) -> Option { + if !paragraph.para.kurikaeshi_moji_shori || first >= end { + return None; + } + let g = paragraph.sg.get(first)?; + let (glyph, c) = repeat_mark_glyph(cx, paragraph.pr.start, paragraph.lead, g)?; + cx.out.repeat_marks.push((g.byte, c)); + Some(glyph) +} + /// Lay out `line` of `paragraph` as `justification` aligns it: each glyph placed along the /// baseline (tabs as [`tab_glyph`] sets them), its hyphen, and the line's record, then the pen /// moved on past it. @@ -1306,9 +1344,14 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData let mut marker_tab = 0; // The warichu blocks drawn on the line: the byte that names each and where it starts. let mut wari_blocks: Vec<(usize, f64)> = Vec::new(); + // Kurikaeshi Moji Shori: the line's first character after any list marker, drawn as the + // character it repeats when it is a repeat mark. + let first = index.max(paragraph.marker); + let repeat = line_start_repeat(cx, paragraph, first, position.end); for (order_index, &offset) in order.iter().enumerate() { let glyph_index = index + offset; let Some(glyph) = sg.get(glyph_index) else { continue }; + let glyph = if glyph_index == first { repeat.as_ref().unwrap_or(glyph) } else { glyph }; let mut advance = glyph.adv; if glyph_index + 1 == trimmed { advance -= line.end_trim; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..506b7e5b03 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -54,7 +54,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; -pub use shape::{aki_space, inseparable, line_start_space, spacing_scale}; +pub use shape::{aki_space, inseparable, line_start_space, repeat_base, spacing_scale}; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; @@ -401,6 +401,10 @@ pub struct TextLayout { pub inlines: Vec, /// List markers, in text order. pub markers: Vec, + /// Kurikaeshi Moji Shori: the repeat marks drawn as the character they stand for, as (the + /// mark's byte offset in the plain text, the character drawn), in text order. Writers that put + /// characters in place of glyphs (live SVG text) write that character. + pub repeat_marks: Vec<(usize, char)>, } impl Default for TextLayout { @@ -419,6 +423,7 @@ impl Default for TextLayout { path_fill: None, inlines: Vec::new(), markers: Vec::new(), + repeat_marks: Vec::new(), } } } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 13cd2e06de..9d09ce076e 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -450,6 +450,65 @@ pub fn inseparable(a: char, b: char) -> bool { ) } +/// Kurikaeshi Moji Shori: the last character of `text` that a repeat mark after it could stand for: +/// the last one that is neither a repeat mark, a soft return (U+2028) nor a combining voicing mark +/// (U+3099, U+309A), or None when there is none. The engine gives a threaded frame whose first +/// paragraph continues from the frame before the result for the text before it +/// (`TextObject::first_para_lead`). +pub fn repeat_base(text: &str) -> Option { + text.chars().rev().find(|&c| !matches!(c, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ' | '\u{2028}' | '\u{3099}' | '\u{309A}')) +} + +/// Kurikaeshi Moji Shori: the character the repeat mark `mark` stands for after the text `before` +/// it, or None when `mark` is not a repeat mark or nothing before it fits. `lead` stands before +/// `before` (the text of a threaded paragraph in the frames before). VectorCraft's rules: the +/// repeated character is the last one before the mark that is neither a repeat mark, a soft return +/// (U+2028) nor a combining voicing mark ([`repeat_base`]); 々 repeats a Han ideograph, ゝ and ゞ a +/// hiragana and ヽ and ヾ a katakana. ゝ and ヽ give the kana without its voicing marks, and ゞ and +/// ヾ its voiced form, or the plain kana when it has none. +pub(crate) fn repeated_char(lead: Option, before: &str, mark: char) -> Option { + let script = match mark { + '々' => Script::Han, + 'ゝ' | 'ゞ' => Script::Hiragana, + 'ヽ' | 'ヾ' => Script::Katakana, + _ => return None, + }; + let base = repeat_base(before).or(lead)?; + if base.script() != script || (script != Script::Han && !matches!(base as u32, 0x3041..=0x3096 | 0x30A1..=0x30F6)) { + return None; + } + if script == Script::Han { + return Some(base); + } + // Katakana from U+30A1 to U+30F6 lie 0x60 past their hiragana, so one table serves both. + let shift = if script == Script::Katakana { 0x60 } else { 0 }; + let plain = unvoiced(base as u32 - shift); + let kana = if matches!(mark, 'ゞ' | 'ヾ') { voiced(plain).unwrap_or(plain) } else { plain }; + char::from_u32(kana + shift) +} + +/// The hiragana `h` (a code point) without its dakuten or handakuten. +fn unvoiced(h: u32) -> u32 { + match h { + 0x304C..=0x3062 if h.is_multiple_of(2) => h - 1, + 0x3065 | 0x3067 | 0x3069 => h - 1, + 0x3070..=0x307D => h - (h - 0x306F) % 3, + 0x3094 => 0x3046, + _ => h, + } +} + +/// The voiced form (with dakuten) of the plain hiragana `h`, if it has one. +fn voiced(h: u32) -> Option { + match h { + 0x304B..=0x3061 if !h.is_multiple_of(2) => Some(h + 1), + 0x3064 | 0x3066 | 0x3068 => Some(h + 1), + 0x306F..=0x307B if (h - 0x306F).is_multiple_of(3) => Some(h + 1), + 0x3046 => Some(0x3094), + _ => None, + } +} + /// Is `c` Hangul: a syllable, a jamo or a compatibility jamo (full or half width)? pub(crate) fn is_hangul(c: char) -> bool { c.script() == Script::Hangul diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d17ce78603..4a4297c33a 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -484,6 +484,59 @@ pub fn full_width_font() -> Option> { Some(builder.build()) } +/// The family of [`repeat_mark_font`]. +pub const REPEAT_MARK_FAMILY: &str = "Repeattest Sans"; + +/// The Japanese characters [`repeat_mark_font`] maps, each to the glyph of the Latin capital beside +/// it: an ideograph, the repeat marks, and kana with and without their voicing marks. +pub const REPEAT_MARK_CHARS: [(char, char); 11] = + [('時', 'A'), ('々', 'B'), ('す', 'C'), ('ず', 'D'), ('ゝ', 'E'), ('ゞ', 'F'), ('サ', 'G'), ('ザ', 'H'), ('ヽ', 'I'), ('ヾ', 'J'), ('あ', 'K')]; + +/// A test-only cmap over bundled Source Sans 3: each of [`REPEAT_MARK_CHARS`] uses the glyph of its +/// Latin capital, so the glyph drawn for a repeat mark tells which character was drawn; the space +/// keeps its own glyph. +pub fn repeat_mark_font() -> Option> { + repeat_font(REPEAT_MARK_FAMILY, &REPEAT_MARK_CHARS) +} + +/// The family of [`rare_repeat_mark_font`]. +pub const RARE_REPEAT_MARK_FAMILY: &str = "Raretest Sans"; + +/// [`repeat_mark_font`] for tests that add it to the shared [`crate::FontDb::global`]: it maps +/// only 龘 (to the glyph of A) and 々 (to the glyph of B), characters no other text in those tests +/// uses, so other tests' Japanese text does not fall back to it. +pub fn rare_repeat_mark_font() -> Option> { + repeat_font(RARE_REPEAT_MARK_FAMILY, &[('龘', 'A'), ('々', 'B')]) +} + +/// A font named `family` over bundled Source Sans 3 whose cmap maps each of `chars` to the glyph of +/// the Latin capital beside it, and the space to its own glyph. +fn repeat_font(family: &str, chars: &[(char, char)]) -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mut mappings: Vec<(char, write_fonts::types::GlyphId)> = Vec::new(); + for &(c, latin) in chars.iter().chain(&[(' ', ' ')]) { + mappings.push((c, write_fonts::types::GlyphId::new(charmap.map(latin)?.to_u32()))); + } + let cmap = Cmap::from_mappings(mappings).ok()?; + let full = format!("{family} Regular"); + let postscript = format!("{}-Regular", family.replace(' ', "")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GSUB") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`half_form_font`]. pub const HALF_FORM_FAMILY: &str = "Halftest Sans"; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 4bab8aa561..477c3e3392 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2693,6 +2693,123 @@ fn bunri_kinshi_keeps_two_em_dashes_on_one_line() { assert_eq!(ends(&t), [kept, text.len(), second + split, second + text.len()]); } +/// Kurikaeshi Moji Shori: the character a repeat mark stands for is the last one before it that is +/// not a repeat mark, in the mark's script; ゝ and ヽ give it without voicing marks, ゞ and ヾ give +/// its voiced form when it has one. +#[test] +fn repeat_marks_stand_for_the_character_before_them() { + use crate::shape::repeated_char; + for (before, mark, want) in [ + ("時", '々', Some('時')), + ("時々", '々', Some('時')), + ("時\u{2028}", '々', Some('時')), + ("す", 'ゝ', Some('す')), + ("ず", 'ゝ', Some('す')), + ("す", 'ゞ', Some('ず')), + ("ず", 'ゞ', Some('ず')), + ("ぱ", 'ゝ', Some('は')), + ("は", 'ゞ', Some('ば')), + ("ぽ", 'ゞ', Some('ぼ')), + ("つ", 'ゞ', Some('づ')), + ("う", 'ゞ', Some('ゔ')), + ("あ", 'ゞ', Some('あ')), + ("サ", 'ヽ', Some('サ')), + ("ザ", 'ヽ', Some('サ')), + ("サ", 'ヾ', Some('ザ')), + ("ウ", 'ヾ', Some('ヴ')), + ("ピ", 'ヾ', Some('ビ')), + ("サ", 'ゝ', None), + ("す", 'ヽ', None), + ("す", '々', None), + ("時", 'ゝ', None), + ("A", '々', None), + ("", '々', None), + ("々ゝ", '々', None), + ("時", 'x', None), + // A kana followed by a combining voicing mark is that kana. + ("か\u{3099}\u{2028}", 'ゝ', Some('か')), + ("か\u{3099}", 'ゞ', Some('が')), + ("ハ\u{309A}", 'ヽ', Some('ハ')), + ] { + assert_eq!(repeated_char(None, before, mark), want, "{before:?} {mark}"); + } + // The character before a paragraph that continues from the frame before stands in when the text + // before the mark in this frame has none. + assert_eq!(repeated_char(Some('時'), "", '々'), Some('時')); + assert_eq!(repeated_char(Some('時'), "\u{2028}々", '々'), Some('時')); + assert_eq!(repeated_char(Some('時'), "日", '々'), Some('日')); + assert_eq!(repeated_char(Some('す'), "", '々'), None); +} + +/// Kurikaeshi Moji Shori (a paragraph attribute): on, a repeat mark that starts a line is drawn as +/// the character it repeats, in point and area type, horizontal and vertical, at a soft return or +/// where a line wraps; a mark inside a line, one starting a paragraph and every mark with the +/// setting off keep their own glyph. The line breaks and the glyphs' bytes do not change. Uses a test +/// font that draws each character with a different Latin glyph. +#[test] +fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let glyph = |c: char| Some(face.glyph_for(c)); + let gid_of = |l: &TextLayout, b: usize| l.glyphs.iter().find(|g| g.byte == b).map(|g| g.gid); + let ends = |l: &TextLayout| l.lines.iter().map(|line| line.end).collect::>(); + // 時 | 々す | ゞ時々ザ | ヽ, then a paragraph that starts with 々. + let text = "時\u{2028}々す\u{2028}ゞ時々ザ\u{2028}ヽ\n々"; + let at = |s: &str| text.find(s).unwrap(); + let (first_mark, voiced, inner, katakana, para_start) = (at("々す"), at("ゞ"), at("時々ザ") + "時".len(), at("ヽ"), text.len() - "々".len()); + for vertical in [false, true] { + let mut t = TextObject::point(Point::ZERO, text, st.clone()); + t.vertical = vertical; + let off = layout(&db, &t); + t.set_paragraph_styles(vec![ + vectorcraft_doc::ParaStyle { kurikaeshi_moji_shori: true, ..t.para.clone() }, + vectorcraft_doc::ParaStyle { kurikaeshi_moji_shori: true, ..t.para.clone() }, + ]); + let on = layout(&db, &t); + assert_eq!(ends(&on), ends(&off), "vertical {vertical}"); + let bytes = |l: &TextLayout| l.glyphs.iter().map(|g| g.byte).collect::>(); + assert_eq!(bytes(&on), bytes(&off), "vertical {vertical}"); + // Off, each mark has its own glyph. + for (b, mark) in [(first_mark, '々'), (voiced, 'ゞ'), (inner, '々'), (katakana, 'ヽ'), (para_start, '々')] { + assert_eq!(gid_of(&off, b), glyph(mark), "vertical {vertical}: off, {mark} at {b}"); + } + assert_eq!(gid_of(&on, first_mark), glyph('時'), "vertical {vertical}: 々 drawn as 時"); + assert_eq!(gid_of(&on, voiced), glyph('ず'), "vertical {vertical}: ゞ after す drawn as ず"); + assert_eq!(gid_of(&on, katakana), glyph('サ'), "vertical {vertical}: ヽ after ザ drawn as サ"); + assert_eq!(gid_of(&on, inner), glyph('々'), "vertical {vertical}: a mark inside a line keeps its glyph"); + assert_eq!(gid_of(&on, para_start), glyph('々'), "vertical {vertical}: a paragraph's first mark keeps its glyph"); + assert!(off.repeat_marks.is_empty()); + assert_eq!(on.repeat_marks, [(first_mark, '時'), (voiced, 'ず'), (katakana, 'サ')], "vertical {vertical}"); + } + // Where area type wraps: each line holds one character, so 々 starts the second line. + let mut t = TextObject::point(Point::ZERO, "時々", st.clone()); + let both: f64 = layout(&db, &t).glyphs.iter().map(|g| g.advance).sum(); + t.xf = Affine::IDENTITY; + // The Soft set lets 々 start a line. + t.para.kinsoku = vectorcraft_doc::Kinsoku::Soft; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, both - 1.0, 200.0).to_path(0.1)) }; + let off = layout(&db, &t); + assert_eq!(ends(&off), ["時".len(), "時々".len()]); + t.para.kurikaeshi_moji_shori = true; + let on = layout(&db, &t); + assert_eq!(ends(&on), ends(&off)); + assert_eq!(gid_of(&off, "時".len()), glyph('々')); + assert_eq!(gid_of(&on, "時".len()), glyph('時'), "a wrapped line's 々 is drawn as 時"); + // A threaded frame whose first paragraph continues: a mark that starts the frame is drawn as the + // character before it in the frame before, only while the paragraph continues. + let mut t = TextObject::point(Point::ZERO, "々す\n々", st.clone()); + t.para.kurikaeshi_moji_shori = true; + t.first_para_lead = Some('時'); + assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "a frame that does not continue"); + t.first_para_continues = true; + let on = layout(&db, &t); + assert_eq!(gid_of(&on, 0), glyph('時'), "the frame's first 々 is drawn as 時"); + assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..466bf21b1b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2978,6 +2978,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Латинска висяща пунктуация Korean Line Break Anywhere Пренасяне на корейски текст навсякъде Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Настройки за източноазиатска композиция Korean Composition Settings Настройки за корейска композиция Rotate Завъртане diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..b0d3668edf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2076,6 +2076,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Latinična viseća interpunkcija Korean Line Break Anywhere Prelom korejskog reda bilo gdje Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Postavke istočnoazijske kompozicije Korean Composition Settings Postavke korejske kompozicije Select a text object to edit its paragraph attributes. Odaberite tekstualni objekat da uredite njegove atribute pasusa. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..e9c8189f1e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3810,6 +3810,7 @@ digits Malayalam Malaiàlam Roman Hanging Punctuation Puntuació penjant romana Korean Line Break Anywhere Salt de línia coreà a qualsevol lloc Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Configuració de composició de l’Àsia oriental Korean Composition Settings Configuració de composició coreana Rotate Gira diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..7cac30c893 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2147,6 +2147,7 @@ digits Malayalam Malajálamské Roman Hanging Punctuation Visící latinková interpunkce Korean Line Break Anywhere Zalomení korejského řádku kdekoli Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Nastavení východoasijské sazby Korean Composition Settings Nastavení korejské sazby Select a text object to edit its paragraph attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho odstavce. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..6b97db1903 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2565,6 +2565,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Romersk hængende tegnsætning Korean Line Break Anywhere Koreansk linjeskift hvor som helst Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Indstillinger for østasiatisk komposition Korean Composition Settings Indstillinger for koreansk komposition Select a text object to edit its paragraph attributes. Markér et tekstobjekt for at redigere dets afsnitsattributter. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..fbb09e5340 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3021,6 +3021,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Hängende Interpunktion (lateinisch) Korean Line Break Anywhere Koreanischer Zeilenumbruch überall Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Einstellungen für ostasiatischen Satz Korean Composition Settings Einstellungen für koreanischen Satz Rotate Drehen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..b71d14db76 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2073,6 +2073,7 @@ font-technology Variable Μεταβλητές Roman Hanging Punctuation Κρεμαστή στίξη όρθιας γραφής Korean Line Break Anywhere Αλλαγή γραμμής κορεατικών οπουδήποτε Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ρυθμίσεις σύνθεσης ανατολικής Ασίας Korean Composition Settings Ρυθμίσεις κορεατικής σύνθεσης Rotate Περιστροφή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..eb281bb92e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3057,6 +3057,7 @@ digits Malayalam Malayálam Roman Hanging Punctuation Puntuación colgante romana Korean Line Break Anywhere Salto de línea coreano en cualquier lugar Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ajustes de composición de Asia oriental Korean Composition Settings Ajustes de composición coreana Rotate Rotar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..d50fbf4ad3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2110,6 +2110,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Latinalaiset riippuvat välimerkit Korean Line Break Anywhere Korean rivinvaihto missä tahansa Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Itäaasialaisen ladonnan asetukset Korean Composition Settings Korean ladonnan asetukset Select a text object to edit its paragraph attributes. Valitse tekstiobjekti, jonka kappalemääritteitä haluat muokata. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..d04586aa05 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3049,6 +3049,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Ponctuation romaine hors justification Korean Line Break Anywhere Saut de ligne coréen n’importe où Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Paramètres de composition d’Asie orientale Korean Composition Settings Paramètres de composition coréenne Rotate Rotation diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..108352cc12 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4465,6 +4465,7 @@ antiAlias Sharp શાર્પ Save Prominent Colors મુખ્ય રંગો સાચવો Korean Line Break Anywhere કોરિયન લાઇન ગમે ત્યાં તોડો Bunri-Kinshi બુનરી-કિન્શી + Kurikaeshi Moji Shori કુરિકાએશી મોજી શોરી East Asian Composition Settings પૂર્વ એશિયાઈ કમ્પોઝિશન સેટિંગ્સ Korean Composition Settings કોરિયન કમ્પોઝિશન સેટિંગ્સ Show Bounding Box While Moving and Drawing ખસેડતી અને દોરતી વખતે બાઉન્ડિંગ બોક્સ બતાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..0d5de80b4e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4187,6 +4187,7 @@ antiAlias Sharp शार्प Roman Hanging Punctuation रोमन हैंगिंग विराम चिह्न Korean Line Break Anywhere कोरियाई लाइन ब्रेक कहीं भी Bunri-Kinshi बुनरी-किंशी + Kurikaeshi Moji Shori कुरिकाएशी मोजी शोरी East Asian Composition Settings पूर्वी एशियाई संरचना सेटिंग्स Korean Composition Settings कोरियाई संरचना सेटिंग्स Rotate घुमाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..f94014cb6f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3645,6 +3645,7 @@ mark-style Japanese Japán Roman Hanging Punctuation Latin függő írásjelek Korean Line Break Anywhere Koreai sortörés bárhol Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Kelet-ázsiai szedési beállítások Korean Composition Settings Koreai szedési beállítások Rotate Elforgatás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..0d369293a0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1899,6 +1899,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Tanda baca gantung Romawi Korean Line Break Anywhere Putus baris Korea di mana saja Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Pengaturan komposisi Asia Timur Korean Composition Settings Pengaturan komposisi Korea Select a text object to edit its paragraph attributes. Pilih objek teks untuk mengedit atribut paragrafnya. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..70d3026e6a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3098,6 +3098,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Punteggiatura sporgente romana Korean Line Break Anywhere Interruzione di riga coreana ovunque Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Impostazioni di composizione dell’Asia orientale Korean Composition Settings Impostazioni di composizione coreana Rotate Ruota diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..563a2b1966 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3064,6 +3064,7 @@ mark-style Japanese 日本式 Roman Hanging Punctuation 欧文ぶら下がり Korean Line Break Anywhere 韓国語の任意位置での改行 Bunri-Kinshi 分離禁止 + Kurikaeshi Moji Shori 繰り返し文字処理 East Asian Composition Settings 東アジア言語の組版設定 Korean Composition Settings 韓国語の組版設定 Rotate 回転 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 358960bd37..12be5345a9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3955,6 +3955,7 @@ digits Malayalam მალაიალამური Roman Hanging Punctuation რომაული გამოწეული პუნქტუაცია Korean Line Break Anywhere კორეული სტრიქონის გადატანა ნებისმიერ ადგილას Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings აღმოსავლეთ აზიური აწყობის პარამეტრები Korean Composition Settings კორეული აწყობის პარამეტრები Select a text object to edit its paragraph attributes. აბზაცის ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..ca1687819b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3053,6 +3053,7 @@ mark-style Japanese 일본식 Roman Hanging Punctuation 로마자 걸림 문장 부호 Korean Line Break Anywhere 한글 어디서나 줄 바꿈 Bunri-Kinshi 분리 금지 + Kurikaeshi Moji Shori 반복 문자 처리 East Asian Composition Settings 동아시아 조판 설정 Korean Composition Settings 한글 조판 설정 Rotate 회전 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..513cb35895 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2461,6 +2461,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Romeinse hangende leestekens Korean Line Break Anywhere Koreaans regeleinde overal Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Instellingen voor Oost-Aziatische zetting Korean Composition Settings Instellingen voor Koreaanse zetting Select a text object to edit its paragraph attributes. Selecteer een tekstobject om de alineakenmerken ervan te bewerken. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..61b9465dec 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2065,6 +2065,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Wysunięta interpunkcja łacińska Korean Line Break Anywhere Koreański podział wiersza w dowolnym miejscu Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ustawienia składu wschodnioazjatyckiego Korean Composition Settings Ustawienia składu koreańskiego Select a text object to edit its paragraph attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty akapitu. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..460e581b15 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2544,6 +2544,7 @@ digits Malayalam Malaiala Roman Hanging Punctuation Pontuação Pendurada Romana Korean Line Break Anywhere Quebra de Linha Coreana em Qualquer Lugar Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Configurações de Composição do Leste Asiático Korean Composition Settings Configurações de Composição Coreana Rotate Girar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..dca47d1e4c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3087,6 +3087,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Римская висячая пунктуация Korean Line Break Anywhere Перенос корейского текста в любом месте Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Параметры восточноазиатского набора Korean Composition Settings Параметры корейского набора Rotate Повернуть diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..e7f7555c6a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2991,6 +2991,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Hängande interpunktion (roman) Korean Line Break Anywhere Koreansk radbrytning var som helst Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Inställningar för östasiatisk sättning Korean Composition Settings Inställningar för koreansk sättning Rotate Rotera diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..4aca424124 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2826,6 +2826,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Roma Asılı Noktalama İşaretleri Korean Line Break Anywhere Korece Satırı Her Yerde Kes Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Doğu Asya Dizgi Ayarları Korean Composition Settings Korece Dizgi Ayarları Rotate Döndür diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..704309b261 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3090,6 +3090,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Римська висяча пунктуація Korean Line Break Anywhere Перенесення корейського тексту будь-де Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Параметри східноазійського набору Korean Composition Settings Параметри корейського набору Rotate Повернути diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..b2b5b8f0da 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3407,6 +3407,7 @@ mark-style Japanese Kiểu Nhật Roman Hanging Punctuation Dấu câu treo Roman Korean Line Break Anywhere Ngắt dòng tiếng Hàn ở bất kỳ đâu Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Cài đặt dàn trang Đông Á Korean Composition Settings Cài đặt dàn trang tiếng Hàn Rotate Xoay diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..6105919a37 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2948,6 +2948,7 @@ digits Malayalam 马拉雅拉姆数字 Roman Hanging Punctuation 西文悬挂标点 Korean Line Break Anywhere 韩文任意位置换行 Bunri-Kinshi 分离禁止 + Kurikaeshi Moji Shori 重复字符处理 East Asian Composition Settings 东亚排版设置 Korean Composition Settings 韩文排版设置 Rotate 旋转 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..cae679bd47 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4176,6 +4176,7 @@ digits Malayalam 馬來亞拉姆數字 Roman Hanging Punctuation 羅馬懸掛標點 Korean Line Break Anywhere 韓文任意位置換行 Bunri-Kinshi 分離禁止 + Kurikaeshi Moji Shori 重複字元處理 East Asian Composition Settings 東亞排版設定 Korean Composition Settings 韓文排版設定 Rotate 旋轉 diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 3f1a56cee5..52b3135cc2 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -859,6 +859,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + // A repeat mark starting a line is drawn as the character it repeats. + let repeat = shared_para(app, |p| p.kurikaeshi_moji_shori) == Some(true); + if menu_item(ui, tl!("Kurikaeshi Moji Shori"), has, repeat) { + toggle_kurikaeshi_moji_shori(app); + } // How a line keeps the kinsoku characters off its ends: the selected paragraphs' type is // checked, and none is when they differ. let kinsoku_type = shared_para(app, |p| p.kinsoku_type); @@ -937,6 +942,14 @@ fn toggle_bunri_kinshi(app: &mut VectorcraftApp) { format(app, json!({"bunriKinshi": !on})); } +/// Kurikaeshi Moji Shori (Paragraph panel menu): the menu item is checked when every paragraph the +/// panel acts on ([`format`]) has it, and a click turns it off for all of them then, and on for all +/// of them otherwise, in one undo step. +fn toggle_kurikaeshi_moji_shori(app: &mut VectorcraftApp) { + let on = shared_para(app, |p| p.kurikaeshi_moji_shori) == Some(true); + format(app, json!({"kurikaeshiMojiShori": !on})); +} + /// Korean Line Break Anywhere (Paragraph panel menu): the menu item is checked when every paragraph /// the panel acts on ([`format`]) has it, and a click turns it off for all of them then, and on for /// all of them otherwise, in one undo step. @@ -949,7 +962,7 @@ fn toggle_korean_line_break_anywhere(app: &mut VectorcraftApp) { /// indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification /// options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi /// Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, -/// Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo +/// Kurikaeshi Moji Shori, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo /// step named Reset Panel (inside an undo group that is already open, as part of its step). fn reset_panel(app: &mut VectorcraftApp) { let h = HyphenationOptions::default(); @@ -971,7 +984,7 @@ fn reset_panel(app: &mut VectorcraftApp) { "autoLeading": j.auto_leading, "singleWordJustification": "fullJustify", "direction": "auto", "leadingModel": "romanBaseline", "mojikumi": "lineEndHalf", "burasagari": "standard", "kinsoku": "hard", "kinsokuType": "pushOutOnly", "composer": "everyLine", "romanHangingPunctuation": false, "koreanLineBreakAnywhere": false, - "bunriKinshi": false + "bunriKinshi": false, "kurikaeshiMojiShori": false }), ); para_cmd(app, "text.tabs.clear", json!({})); diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 11fd7fbafc..aebdbbf1cf 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -324,6 +324,37 @@ fn bunri_kinshi_toggle_follows_kinsoku_and_the_selected_paragraphs() { assert_eq!(flags(&app), (false, false), "Reset Panel turns it off"); } +/// Kurikaeshi Moji Shori: new type has it off; the menu item turns it on for the paragraphs the Type +/// tool's selection touches in one undo step, a click while the selected paragraphs differ turns it +/// on for all of them, and a click while all have it turns it off. Reset Panel turns it off. +#[test] +fn kurikaeshi_moji_shori_toggle_follows_the_selected_paragraphs() { + let (mut app, id) = editing_text("時々\nすゝ\n"); + app.session.prefs.show_east_asian_options = true; + let flags = |app: &VectorcraftApp| { + let node = app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Text(text) = &node.kind else { panic!("text") }; + (text.para_at(0).kurikaeshi_moji_shori, text.para_at(1).kurikaeshi_moji_shori) + }; + assert_eq!(flags(&app), (false, false), "new type has it off"); + select_range(&mut app, 0, 3); + let history = app.session.active().unwrap().history.undo.len(); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (true, false)); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (true, true), "mixed: a click turns it on for all"); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (false, false), "all on: a click turns it off"); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + app.session.set_tool_option("selectAll", &json!(true)); + reset_panel(&mut app); + assert_eq!(flags(&app), (false, false), "Reset Panel turns it off"); +} + #[test] fn paragraph_mixed_indent_fields_show_blank() { let (mut app, id) = editing_text("A\nB\n"); diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..ba9e16985d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9451,6 +9451,30 @@ https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html {"name":"run_command","arguments":{"command":"text.setFormat","params":{"bunriKinshi":true}}} ``` +## Kurikaeshi Moji Shori + +`text.setFormat {kurikaeshiMojiShori: bool}` (Paragraph panel menu › Kurikaeshi Moji Shori, shown with the East Asian +options) turns it on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a `start` / `end` +range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, is drawn as the +character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, +searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. +SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. +VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the +repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a +combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph +from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the +plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a +paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph +(`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph +style's attributes), and Reset Panel turns it off. A value that is not true or false is refused, and a call that gives +the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a +save reports a paragraph with it on as left out. The help page: +https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html + +```json +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"kurikaeshiMojiShori":true}}} +``` + ## Korean Line Break Anywhere `text.setFormat {koreanLineBreakAnywhere: bool}` (Paragraph panel menu › Korean Line Break Anywhere, shown with the diff --git a/docs/type-parity.md b/docs/type-parity.md index 5b332efd5e..419ccc7717 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -67,6 +67,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: input methods (marked text, candidate window) | done | | | CJK: kinsoku (Hard, Soft, None), the predefined mojikumi sets (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku, YakumonoZenkaku, with VectorCraft's own spacing for each) and Line-end Punctuation Half Width, tate-chu-yoko (auto) | done / partial | custom kinsoku sets, custom mojikumi sets and the Mojikumi Settings dialog missing | | CJK: Kinsoku Shori Type (Push In First, Push Out First, Push Out Only) | done | Paragraph panel menu › Kinsoku Shori Type (`text.setFormat {kinsokuType}`), with the East Asian options ([Formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); Push Out Only is the default, and a push-in closes the line's gaps next to CJK characters by at most a tenth of an em each (VectorCraft's own limit). Evidence: `layout::wrapping_tests::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `tests::vertical::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `typecmd::area_tests::kinsoku_shori_type_is_set_per_paragraph_and_saved_only_when_not_push_out_only` | +| CJK: Kurikaeshi Moji Shori | done | Paragraph panel menu › Kurikaeshi Moji Shori (`text.setFormat {kurikaeshiMojiShori}`), with the East Asian options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): a repeat mark (々, ゝ, ゞ, ヽ, ヾ) that starts a line of point or area type is drawn as the character it repeats, and the text keeps the mark; SVG export with live type writes the drawn character. The set of marks and the voicing rules are VectorCraft's own. Off by default, saved natively only when on, carried by paragraph styles. Evidence: `tests::repeat_marks_stand_for_the_character_before_them`, `tests::kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start`, `typecmd::area_tests::kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on`, `threads::tests::a_continued_frame_carries_the_character_a_repeat_mark_stands_for`, `panels::paragraph::tests::kurikaeshi_moji_shori_toggle_follows_the_selected_paragraphs`, `text_layout::a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws` | | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | | CJK: East Asian Type units (Q, Ha) | done | Preferences › Units › East Asian Type (`unitsAsianType`, Points by default) offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`). The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Tate-chu-yoko Settings… (`ui.tateChuYokoSettings`, `{tcyUpDown, tcyLeftRight}` in points) moves a marked block up or down and right or left as one piece. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `tests_vertical::tate_chu_yoko_settings_move_a_marked_block_up_down_left_and_right`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on`, `typecmd::tate_chu_yoko_settings_are_character_attributes_saved_only_when_set`, `dialogs::tate_chu_yoko::tests` | From 411310a75789182880028044d808e461f5e44da3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:28:29 -0800 Subject: [PATCH 05/54] PDF export: Preserve Numbers converts tagged images from their profile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Output › Convert to Destination (Preserve Numbers), and in PDF/X-1a, which converts the same way, a gray or RGB image that carries an ICC profile had its numbers read as sRGB: converted as sRGB to a CMYK destination, and kept as they were in an RGB one. Preserve Numbers keeps the numbers of untagged content only, so such an image is now converted from its profile to sRGB with the color settings' intent, and then to a CMYK or other RGB destination, the document's own RGB profile included. - An untagged RGB image keeps its numbers in an RGB destination and converts from sRGB to a CMYK one, as before. - A gray image is converted to sRGB grays in an sRGB destination and keeps its profile in the others. - With RGB colors ICC-tagged as sRGB, the image is written as sRGB. - A profile the color engine can't read leaves the image as it is in an RGB destination, and its numbers read as sRGB in a CMYK one, with a warning each. - The table for an RGB destination is built only when the first tagged image needs it. --- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/pdf/src/export/images.rs | 3 +- crates/pdf/src/images.rs | 32 ++++--- crates/pdf/src/output.rs | 50 +++++++++-- crates/pdf/src/tests/compression.rs | 124 +++++++++++++++++++++++++++- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 7 files changed, 199 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 77902b4a15..90b3401821 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 04a3a811f3..70cc868c23 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -139,7 +139,8 @@ impl Exporter<'_> { let doc = self.doc; let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit }); + let then = out.converts_tagged_pixels().then_some(&*out); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then }); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index ac1d77f372..2f81d84571 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -12,7 +12,9 @@ //! conversion leaves unchanged (an sRGB profile) keeps its JPEG data. A black-and-white image whose //! converted levels are grey is compressed as greyscale. A colour image the Output settings also //! convert to their destination ([`Pixels`]) goes from its profile to sRGB, then to the -//! destination; a grey one keeps its profile there, as grey pixels are not converted. +//! destination, and so does one converted from its profile to an RGB destination whose untagged +//! images keep their numbers (Preserve Numbers); a grey one keeps its profile there, as grey +//! pixels are not converted. //! //! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is //! when its numbers are kept; the others' ink amounts are resampled, converted when the Output @@ -319,15 +321,20 @@ pub(crate) struct Recoded { pub note: Option<&'static str>, } -/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to -/// Destination, [`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, -/// else the step before the image's [`Pixels`] conversion. -#[derive(Clone, Copy, Debug)] -pub(crate) struct ToSrgb { +/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB +/// ([`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, else the +/// step before the image's [`Pixels`] conversion. +#[derive(Clone, Copy)] +pub(crate) struct ToSrgb<'a> { /// The rendering intent of the conversion. pub intent: Intent, /// 16-bit samples may be written (PDF 1.5 and later). pub sixteen_bit: bool, + /// The colour output whose [`crate::output::ColorOut::tagged_pixels`] then convert a colour + /// image converted from its profile, when other colour images are not converted (`recode`'s + /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve + /// Numbers). Its table is built when the first such image needs it. + pub then: Option<&'a crate::output::ColorOut>, } /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of @@ -476,8 +483,8 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile /// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces); /// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB -/// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as -/// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be +/// instead ([`ToSrgb`]), and colour ones then by `convert`, or without it by the conversion +/// `to_srgb` gives ([`ToSrgb::then`]); grey ones that either leaves as they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be /// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. pub(crate) fn recode( bytes: &[u8], @@ -497,7 +504,8 @@ pub(crate) fn recode( let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. - let to_srgb = to_srgb.filter(|_| !(grey && convert.is_some())); + let then = to_srgb.and_then(|t| t.then); + let to_srgb = to_srgb.filter(|_| !(grey && (convert.is_some() || then.is_some()))); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { @@ -533,6 +541,8 @@ pub(crate) fn recode( return Recoded { image: None, warning: rule.instead, note: None }; } let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + // Converted from its profile: then by `convert`, else by the conversion `to_srgb` gives. + let mut from_profile = false; if let Some((p, t)) = &source { let srgb = match into_srgb(img, p, t.intent) { Some(s) => Some(s), @@ -550,8 +560,9 @@ pub(crate) fn recode( if kind == Kind::Mono && !bilevel(&srgb) { (kind, rule) = (Kind::Gray, self::rule(c, Kind::Gray)); } + from_profile = true; // Written as it is only when nothing converts it further. - let as_is = kept(&rule, dims, size, jpeg) && convert.is_none(); + let as_is = kept(&rule, dims, size, jpeg) && convert.is_none() && then.is_none(); // A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB // profile): its JPEG data, without the profile. if !changed && as_is && jpeg { @@ -570,6 +581,7 @@ pub(crate) fn recode( } }; } + let convert = if from_profile { convert.or_else(|| then.and_then(crate::output::ColorOut::tagged_pixels)) } else { convert }; // Pixels that keep their colours keep the profile they are in; converted ones are in the // destination's. let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 92381e1628..dce763e9d6 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -14,7 +14,10 @@ //! that carries an ICC profile is converted from it to sRGB with the same intent and written //! without it ([`ColorOut::image_srgb_intent`]); with `destination` and a destination its //! pixels are converted to (CMYK, another RGB space), a colour image is converted from its -//! profile to sRGB and then to the destination. Without conversion it keeps its profile. The +//! profile to sRGB and then to the destination. With `preserveNumbers` (and PDF/X-1a), which +//! keeps the numbers of untagged colours only, such an image is converted from its profile +//! whatever the destination: to sRGB, and then to a CMYK or other RGB destination +//! ([`ColorOut::tagged_pixels`]). Without conversion it keeps its profile. The //! destination is a profile name; empty, the document's profile for its colour mode. //! - Profiles ([`ProfileInclusion`]): with `all`, with `destination`, and with `taggedSource` on a //! document that was assigned profiles, colours are written in ICC-based colour spaces: CMYK @@ -77,6 +80,9 @@ pub(crate) struct ColorOut { pub srgb_note: Option, /// The image transform, built when the first image needs it. pixels: OnceLock>, + /// The transform of images converted from their profile, when it isn't `pixels` + /// ([`Self::tagged_pixels`]). + tagged_pixels: OnceLock>, /// The CMYK image transform, built when the first CMYK image needs it. cmyk_pixels: OnceLock>, intent: Intent, @@ -120,6 +126,7 @@ impl Default for ColorOut { cmyk_profile, srgb_note: None, pixels: OnceLock::new(), + tagged_pixels: OnceLock::new(), cmyk_pixels: OnceLock::new(), intent, catalog: None, @@ -348,13 +355,42 @@ impl ColorOut { /// The intent a gray or RGB image that carries an ICC profile is converted from it to sRGB /// with ([`crate::images::recode`]): the colour settings' intent, with Convert to Destination /// and an sRGB destination, also when the document's RGB space is sRGB, or a destination - /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space). - /// `None` otherwise, Preserve Numbers and an RGB destination that is the document's own RGB - /// profile (which leaves RGB colours and RGB images as they are) included: such an image - /// keeps its profile, or its numbers are converted as sRGB ones. + /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space); + /// and with Preserve Numbers (and PDF/X-1a's own conversion), whatever the destination, as + /// only untagged colours of the destination's model keep their numbers. The pixels are then + /// converted by [`Self::tagged_pixels`]. `None` otherwise, an RGB destination that is the + /// document's own RGB profile with Convert to Destination (which leaves RGB colours and RGB + /// images as they are) included: such an image keeps its profile. pub(crate) fn image_srgb_intent(&self) -> Option { - let d = self.dest.as_ref().filter(|d| d.destination)?; - ((d.model == Model::Rgb && d.srgb) || self.pixels().is_some()).then_some(self.intent) + let d = self.dest.as_ref()?; + let rgb = d.model == Model::Rgb && (d.srgb || !d.destination); + (rgb || self.pixels().is_some()).then_some(self.intent) + } + + /// The destination a colour image converted from its ICC profile to sRGB + /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not + /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose + /// untagged RGB images keep their numbers (unless RGB is tagged as sRGB). + fn tagged_rgb_dest(&self) -> Option<&Dest> { + self.dest.as_ref().filter(|d| !d.destination && d.model == Model::Rgb && !d.srgb && !self.tagged) + } + + /// Are colour images converted from their ICC profile then converted by + /// [`Self::tagged_pixels`]? + pub(crate) fn converts_tagged_pixels(&self) -> bool { + self.tagged_rgb_dest().is_some() + } + + /// How a colour image converted from its ICC profile to sRGB is then converted into that + /// destination's RGB space ([`Self::converts_tagged_pixels`]), built when the first such image + /// needs it; `None` when there is no such destination. + pub(crate) fn tagged_pixels(&self) -> Option<&Pixels> { + self.tagged_pixels + .get_or_init(|| { + let d = self.tagged_rgb_dest()?; + Some(Pixels::Rgb(Box::new(ProofLut::build(|rgb| d.cms.srgb_to_rgb(rgb))))) + }) + .as_ref() } /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index f36cb88e4b..8ad11de270 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -776,7 +776,7 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); @@ -980,3 +980,125 @@ fn convert_to_destination_converts_tagged_images_from_their_profile() { let as_srgb = converted_samples(&img, to_cmyk); assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile: converted as sRGB"); } + +/// With Preserve Numbers, an RGB image that carries an ICC profile is converted from that profile +/// whatever the destination, while an untagged one keeps its numbers in an RGB destination (and +/// converts from sRGB to a CMYK one, as before): to Generic CMYK, sRGB, Wide Gamut RGB, and Wide +/// Gamut RGB that is also the document's RGB profile, and in PDF/X-1a, which converts the same way. +/// A gray image keeps its profile, except in an sRGB destination, where it is converted to sRGB +/// grays. An RGB profile the CMS can't read leaves the image as it is in an RGB destination, and +/// its numbers converted as sRGB ones to a CMYK destination, with a warning. +#[test] +fn preserve_numbers_converts_tagged_images_from_their_profile() { + use vectorcraft_color::cms::{self, ColorSettings, DISPLAY_P3, GENERIC_CMYK, Intent, SRGB, WIDE_GAMUT_RGB, icc_bytes}; + let intent = Intent::RelativeColorimetric; + let settings_with = + |rgb: &str| std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, rgb: rgb.into(), ..ColorSettings::default() }).unwrap()); + let (active, own) = (settings_with(SRGB), settings_with(WIDE_GAMUT_RGB)); + let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); + p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + let p3_profile = cms::IccProfile::from_bytes(None, &p3).unwrap(); + let from_p3 = |rgb: [u8; 3]| p3_profile.to_srgb(&rgb.map(|v| f32::from(v) / 255.0), intent).unwrap().map(|v| (v * 255.0).round() as u8); + let img = colour_blocks(); + let tagged_png = doc(tagged(&img, &p3, ImageFormat::Png), "image/png"); + let untagged_png = doc(encoded(img.clone(), ImageFormat::Png), "image/png"); + let device = |space: &str| vec![Written { space: space.into(), icc: None, bits: 8, filter: "FlateDecode".into(), smask: false }]; + let cmyk = cms::Cms::new(&ColorSettings { intent, cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let cmy = cms::ProofLut::build(|rgb| { + let v = cmyk.srgb_to_cmyk(rgb, intent); + [v[0], v[1], v[2]] + }); + let black = cms::ProofLut::build(|rgb| [cmyk.srgb_to_cmyk(rgb, intent)[3], 0.0, 0.0]); + let wide_lut = cms::ProofLut::build(|rgb| own.srgb_to_rgb(rgb)); + let to_cmyk = |rgb: [u8; 3]| [cmy.apply8(rgb).as_slice(), &black.apply8(rgb)[..1]].concat(); + let to_wide = |rgb: [u8; 3]| wide_lut.apply8(rgb).to_vec(); + let to_srgb = |rgb: [u8; 3]| rgb.to_vec(); + type ToDest<'a> = &'a dyn Fn([u8; 3]) -> Vec; + // Each case: what, the color settings, the export settings, the space images are written in, + // how an sRGB pixel converts to the destination, and whether untagged images keep their numbers. + type Case<'a> = (&'a str, &'a std::sync::Arc, Value, &'a str, ToDest<'a>, bool); + let cases: [Case<'_>; 5] = [ + ("CMYK", &active, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}}), "DeviceCMYK", &to_cmyk, false), + ("sRGB", &active, json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}), "DeviceRGB", &to_srgb, true), + ("Wide Gamut", &active, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ("own RGB", &own, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ( + "PDF/X-1a", + &active, + json!({"standard": "pdfX1a", "compatibility": "1.3", "output": {"destination": GENERIC_CMYK}}), + "DeviceCMYK", + &to_cmyk, + false, + ), + ]; + for (what, color, settings, space, to_dest, keeps) in cases { + let export = |d: &Document| { + let mut s: PdfSettings = serde_json::from_value(settings.clone()).unwrap(); + s.compression.compress_text = false; + let r = cms::with_active((*color).clone(), || export_with_report(d, &PdfOptions { settings: s, ..Default::default() })).unwrap(); + assert!(r.warnings.is_empty(), "{what}: {:?}", r.warnings); + if what == "PDF/X-1a" { + crate::pdfx::verify(&r.bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{what}: {e}")); + } + (image_spaces(&r.bytes), image_samples(&r.bytes)) + }; + let (spaces, samples) = export(&tagged_png); + assert_eq!(spaces, device(space), "{what}: tagged"); + let want = converted_samples(&img, |rgb| to_dest(from_p3(rgb))); + let as_numbers = converted_samples(&img, to_dest); + assert!( + samples.len() == 1 && samples_close(&samples[0], &want, false, 1), + "{what}: converted from the profile, {}", + max_diff(&samples[0], &want) + ); + assert!(!samples_close(&samples[0], &as_numbers, false, 8), "{what}: not converted as its numbers"); + let (spaces, samples) = export(&untagged_png); + assert_eq!(spaces, device(space), "{what}: untagged"); + let untagged = if keeps { img.to_rgb8().into_raw() } else { as_numbers }; + assert!(samples.len() == 1 && samples_close(&samples[0], &untagged, false, 1), "{what}: untagged, {}", max_diff(&samples[0], &untagged)); + } + // With RGB colours ICC-tagged as sRGB, the tagged image is written as its sRGB samples, in an + // ICC-based colour space with the sRGB profile. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}}); + let (spaces, pdf) = cms::with_active(active.clone(), || export_images(&tagged_png, settings)); + let is_srgb = |icc: &[u8]| { + let p = cms::IccProfile::from_bytes(None, icc).unwrap(); + [[0.2, 0.5, 0.9], [0.9, 0.1, 0.4]].iter().all(|v| p.to_srgb(v, intent).unwrap().iter().zip(v).all(|(a, b)| (a - b).abs() < 0.01)) + }; + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref().is_some_and(is_srgb), "tagged as sRGB: {spaces:?}"); + let samples = image_samples(&pdf); + let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); + assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); + // A gray image keeps its gray profile, in a CMYK and in an RGB destination. + let gray = gray_profile(&[0x01CD]); + let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); + for destination in [GENERIC_CMYK, WIDE_GAMUT_RGB] { + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": destination}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!( + spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), + "gray, {destination}: {spaces:?}" + ); + } + // In an sRGB destination it is converted to sRGB grays and written without it. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!(spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none(), "gray, sRGB: {spaces:?}"); + // A profile the CMS can't read: the image keeps it and its numbers in an RGB destination, and + // its numbers are converted as sRGB ones to a CMYK destination, with a warning each. + let unread = icc_profile(b"RGB ", 600); + let unread_doc = doc(tagged(&img, &unread, ImageFormat::Png), "image/png"); + let unread_export = |destination: &str| { + let mut s: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "preserveNumbers", "destination": destination}})).unwrap(); + s.compression.compress_text = false; + cms::with_active(active.clone(), || export_with_report(&unread_doc, &PdfOptions { settings: s, ..Default::default() })).unwrap() + }; + let r = unread_export(WIDE_GAMUT_RGB); + assert!(r.warnings.iter().any(|w| w.contains("the image keeps it")), "{:?}", r.warnings); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(unread.as_slice()), "unread profile: {spaces:?}"); + let r = unread_export(GENERIC_CMYK); + assert!(r.warnings.iter().any(|w| w.contains("converted to the destination as sRGB")), "{:?}", r.warnings); + let as_srgb = converted_samples(&img, to_cmyk); + assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile, CMYK: converted as sRGB"); +} diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..6cdd88a9e1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5911,7 +5911,13 @@ and then to the destination, instead of having its numbers read as sRGB (a profi them read as sRGB, with a warning); a gray image keeps its profile, as gray is not converted. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there. -`preserveNumbers` still reads an image's numbers as sRGB. The destination is any profile `edit.colorSettings` lists (default: the document's +`preserveNumbers` (and PDF/X-1a, which converts the same way) keeps the numbers of untagged content only: an RGB image +that carries an ICC profile is converted from that profile to sRGB with the same intent, and then to a CMYK or other +RGB destination, the document's own RGB profile included (written as sRGB when colours are ICC-tagged), while an untagged RGB image keeps its numbers in an RGB +destination and converts from sRGB to a CMYK one. A gray image that carries one is converted to sRGB grays in an +sRGB destination and keeps its profile in the others, and a profile the color engine can't +read leaves the image as it is in an RGB destination, with a warning, and its numbers read as sRGB in a CMYK one. +The destination is any profile `edit.colorSettings` lists (default: the document's for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8b2d43f8..35bce4927e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1935,6 +1935,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). - PDF export with Output › Convert to Destination and an sRGB destination converts a gray or RGB image that carries an ICC profile from that profile to sRGB, with the color settings' rendering intent, and writes it without the profile, as the conversion applies to every color ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)): 8-bit and 16-bit TIFFs (16 bits a sample from PDF 1.5 on when not resampled or recompressed), PNGs, JPEGs (kept as JPEG) and resampled images. A JPEG in an sRGB profile keeps its JPEG data, a black-and-white image whose converted levels are gray is written as grayscale, and without conversion every image keeps its profile. An image whose profile the color engine can't read, or whose pixels can't be decoded, is not converted: it keeps its profile, with a warning (`crates/pdf/src/tests/compression.rs`). - PDF export with Output › Convert to Destination and a CMYK destination, or an RGB destination other than sRGB that images are converted to, converts an RGB image that carries an ICC profile from that profile to sRGB and then to the destination, with the color settings' rendering intent, instead of reading its numbers as sRGB ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). An untagged image converts from sRGB as before, a gray image keeps its profile, and a profile the color engine can't read leaves the numbers read as sRGB, with a warning. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there (`convert_to_destination_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`). + - PDF export with Output › Convert to Destination (Preserve Numbers), and PDF/X-1a, keeps the numbers of untagged content only, as the option describes ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)): an RGB image that carries an ICC profile is converted from that profile to sRGB with the color settings' rendering intent, and then to a CMYK or other RGB destination, the document's own RGB profile included, while an untagged RGB image keeps its numbers in an RGB destination. A gray image is converted to sRGB grays in an sRGB destination and keeps its profile in the others, and a profile the color engine can't read leaves the image as it is in an RGB destination, with a warning (`preserve_numbers_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`). - SVG import shows a raster `` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`). - An image that SVG import stores again, as PNG or as a CMYK TIFF, keeps the resolution its PNG, JPEG, TIFF, WebP or BMP file declares, as Open and Place keep it: in a PNG `pHYs` chunk () or the TIFF's resolution tags, with the horizontal and vertical values swapped when the image turns a quarter. An image that declares no resolution is stored without one (`a_turned_raster_keeps_its_resolution`, `an_upright_tiff_keeps_its_resolution` and `a_cmyk_tiff_keeps_its_resolution_turned_or_not` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). From a230ea470d5ea96b358238d8a5f06fee532d49c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:31:15 -0800 Subject: [PATCH 06/54] 3D (Classic): the Black Overprint shading color shades with overprinting black over the fill Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) take shadingColor blackOverprint. Each face keeps its paint unchanged, and a face that darkens gets black over it, as strong as the darkening of the shading color Black: a fill multiplied and overprinting, and a seam stroke overprinting with Darken. The black is on the black plate in Separations Preview and is written to PDF as overprinting fills. The Plastic highlight is not drawn with it. Preserve Spot Colors draws its black with the same helper, so its seam stroke no longer multiplies the black a second time along face edges. The dialogs list the choice, with catalog rows next to Shading Color. Params text, docs/mcp.md, docs/three-d.md and docs/effects-parity.md describe it. --- crates/effects/src/catalog.rs | 6 +- crates/effects/src/revolve/classic.rs | 35 +++++++++++ crates/effects/src/solids/classic.rs | 69 ++++++++++++++------ crates/effects/src/solids/tests.rs | 91 ++++++++++++++++++++++++++- crates/engine/src/tests/overprint.rs | 58 +++++++++++++++++ crates/ui-egui/src/dialogs/effect.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/effects-parity.md | 2 +- docs/mcp.md | 16 +++-- docs/three-d.md | 6 +- 37 files changed, 282 insertions(+), 31 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 8e0d63e9d0..7a93ab079e 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,21 +210,21 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( CLASSIC_ROTATE, "Rotate (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 8dc013e9dc..4aefb13eef 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -164,6 +164,41 @@ mod tests { } } + /// With Black Overprint every face keeps the blue, and the faces that darken get black over it, + /// overprinting, as strong as the darkening of the shading color Black. + #[test] + fn black_overprint_keeps_the_blue_under_overprinting_black() { + let darkened = revolved(json!({"surface": "diffuse"})); + let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"})); + let (darkened, drawn) = (faces(&darkened), faces(&art)); + assert_eq!(darkened.len(), drawn.len()); + let mut shaded = 0; + for (face, black) in drawn.iter().zip(&darkened) { + let fills: Vec<&vectorcraft_doc::FillLayer> = face + .appearance + .items + .iter() + .filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f), + AppearanceItem::Stroke(_) => None, + }) + .collect(); + assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false)); + let k = match fills.get(1) { + Some(shadow) => { + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true)); + shaded += 1; + k + } + None => 0.0, + }; + let b = fill(black).unwrap().to_rgb()[2]; + assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}"); + } + assert!(shaded > 0, "faces turned from the light get black"); + } + #[test] fn angle_offset_edge_and_cap_shape_the_surface() { let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap(); diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index f48b94bce9..e2c3347efa 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"]; /// The width of a Wireframe edge, in points. const WIRE: f64 = 0.5; -/// The Shading Color choices: black, a custom color, or none. -pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"]; +/// The Shading Color choices: black, a custom color, none, or black overprinting the paint. +pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"]; /// The surface settings of Extrude & Bevel (Classic)'s parameters. pub fn classic_shading(p: &Value) -> ClassicShading { @@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { } } -/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only -/// the highlight lightens them). +/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces +/// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { match text(p, "shadingColor", "black") { "none" => None, @@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool { /// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower /// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where -/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`, -/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam +/// tone `tone` is below full light and the faces darken (`shade`), black over it as +/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam /// stroke each layer draws around the face. fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option, seam: f64) -> Vec { let Paint::Solid { color, swatch, tint } = paint else { return vec![] }; let keep = (1.0 - spec).clamp(0.0, 1.0) as f32; let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep }; let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]; - if shade.is_some() && tone < 1.0 { - let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); - let mut layer = FillLayer::new(black.clone()); - layer.blend = BlendMode::Multiply; - layer.overprint = true; - let mut edge = crate::lighting::seam_stroke(black, seam); - edge.blend = BlendMode::Multiply; - edge.overprint = true; - items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]); + if shade.is_some() { + items.extend(overprinting_black(tone, seam)); } items } +/// The black that shades a face at tone `tone` on the black plate, when the tone is below full +/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam` +/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a +/// neighbor's, the face is not darkened twice. +fn overprinting_black(tone: f64, seam: f64) -> Vec { + if tone >= 1.0 { + return vec![]; + } + let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); + let mut layer = FillLayer::new(black.clone()); + layer.blend = BlendMode::Multiply; + layer.overprint = true; + let mut edge = crate::lighting::seam_stroke(black, seam); + edge.blend = BlendMode::Darken; + edge.overprint = true; + vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)] +} + +/// Whether the shading color of parameters `p` is Black Overprint. +fn black_overprint(p: &Value) -> bool { + text(p, "shadingColor", "black") == "blackOverprint" +} + +/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full +/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they +/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of +/// the seam stroke each layer draws around the face. +fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + items.extend(overprinting_black(tone, seam)); + items +} + /// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on /// Wireframe, else the seam between faces. pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { @@ -229,14 +256,16 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child /// 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 tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; 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. 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 overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; let paint = &paint; @@ -251,6 +280,10 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let (tone, spec) = shading.tone(face.normal, &lights); // A narrow stroke of the face's own paint closes the hairline seams between faces. let seam = super::seam_width(&face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); + } let items = match paint.color() { // Unshaded (No Shading, no shading color, or a face in full light) with no // highlight: the paint itself, its color space and swatch kept. diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index de1ec75de3..17e746d1aa 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1902,6 +1902,89 @@ fn classic_shading_color_blend_steps_and_lights() { assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6); } +/// The fills, then the strokes, of face `face`. +fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) { + let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect(); + let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect(); + (fills, strokes) +} + +/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in +/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice); +/// `None` when the face has none. +fn overprinted_black(face: &Node) -> Option { + let (fills, strokes) = layers_of(face); + assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke"); + let shadow = fills.get(1)?; + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0)); + assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true)); + assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out"); + Some(k) +} + +/// Black Overprint keeps the paint on every face and draws the shading over it as black, +/// overprinting, as strong as the darkening of the shading color Black; the +/// highlight is not drawn, and No Shading adds no black. +#[test] +fn classic_black_overprint_keeps_the_paint_under_overprinting_black() { + let diffuse = json!({"surface": "diffuse", "ambient": 20}); + let mut over = diffuse.clone(); + over["shadingColor"] = json!("blackOverprint"); + let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect(); + let faces = classic_faces(over); + assert_eq!(faces.len(), darkened.len()); + let mut shaded = 0; + for (face, rgb) in faces.iter().zip(&darkened) { + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept"); + let k = overprinted_black(face).unwrap_or(0.0); + assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}"); + shaded += usize::from(k > 0.0); + } + assert!(shaded > 0, "faces turned from the light get black"); + // Plastic: no white layer for the highlight. + let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60}); + for face in classic_faces(shiny) { + let (fills, _) = layers_of(&face); + assert_eq!(fills[0].paint, Paint::solid(RED)); + assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}"); + } + // No Shading: the paint alone. + for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) { + assert_eq!(overprinted_black(&face), None); + assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED)); + } +} + +/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate +/// (Classic) draws its plane the same way. +#[test] +fn classic_black_overprint_keeps_gradients_and_shades_rotate() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint}; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)], + )))); + let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = gradient.clone(); + } + let art = solid_art(&n).unwrap(); + let mut shaded = 0; + for face in faces(&art) { + assert_eq!(layers_of(face).0[0].paint, gradient); + shaded += usize::from(overprinted_black(face).is_some()); + } + assert!(shaded > 0); + // Rotate (Classic), turned from the light: red with black over it; facing it: red alone. + let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + let face = &turned[0].children().unwrap()[0]; + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED)); + assert!(overprinted_black(face).is_some_and(|k| k > 0.05)); + let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None); +} + #[test] fn classic_bevel_height_extent_and_cap_shape_the_solid() { let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap(); @@ -2077,9 +2160,12 @@ fn classic_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), + (json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"), + (json!({"shadingColor": true}), "`shadingColor` must be one of"), (json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"), @@ -2156,11 +2242,12 @@ fn classic_rotate_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"), (json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"), (json!({"surface": 2}), "`surface` must be one of"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"), (json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"), diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index 15fbb721e2..3f18ddf644 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -276,3 +276,61 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { s.execute("edit.colors.overprintBlack", &json!({"includeCmyBlacks": true, "includeSpotBlacks": true})).unwrap(); assert!(fill(&s, g) && fill(&s, spot)); } + +/// The plate `plate` of `doc`, drawn as Separations Preview draws one plate, as one gray value per +/// pixel (0 full ink, 255 none). +fn plate(doc: &Document, plate: &str) -> Vec { + let mut r = Renderer::new(); + r.threads = 0; + let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() }; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() }; + let image = r.render(doc, 100, 100, Affine::IDENTITY, &opts); + (0..100 * 100).map(|i| image.pixel(i % 100, i / 100)[0]).collect() +} + +/// 3D (Classic) with the shading color Black Overprint puts the shading on the black plate, shows +/// it as the cyan darkened, and writes it to PDF as overprinting fills. +#[test] +fn classic_3d_black_overprint_shades_on_the_black_plate() { + let doc = |params: Value| { + let mut s = session(); + rect(&mut s, [30.0, 30.0, 40.0, 40.0], cyan_ink(), None, 0.0); + s.execute("effect.apply", &json!({"effect": "threeD.classicExtrude", "item": null, "params": params})).unwrap(); + s + }; + let over = doc(json!({"surface": "diffuse", "depth": 20, "shadingColor": "blackOverprint"})); + let flat = doc(json!({"surface": "none", "depth": 20, "shadingColor": "blackOverprint"})); + let black = doc(json!({"surface": "diffuse", "depth": 20})); + let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc); + let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count(); + assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn"); + assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate"); + assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black"); + // On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan. + let image = |d: &Document| { + let mut r = Renderer::new(); + r.threads = 0; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let (shaded, unshaded) = (image(over_doc), image(flat_doc)); + let mut darker = 0; + for (x, y) in (0..100u32).flat_map(|y| (0..100u32).map(move |x| (x, y))) { + let (s, u) = (shaded.pixel(x, y), unshaded.pixel(x, y)); + // Inside the solid (no white mixed in at an antialiased edge) where the shading darkens it. + if u[0] < 30 && (s[1] as i32) + 20 < u[1] as i32 { + darker += 1; + assert!(s[2] as i32 > s[0] as i32 + 20, "a shaded face keeps its cyan at ({x}, {y}): {s:?}"); + } + } + assert!(darker > 100, "the faces turned from the light are darker"); + + let pdf_overprints = |s: &mut Session| { + let v = s.execute("document.exportPdf", &json!({"compression": {"compressText": false}, "preserveEditing": false})).unwrap(); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + String::from_utf8_lossy(&bytes).matches("/OP true/op true/OPM 1").count() + }; + let (mut over, mut black) = (over, black); + assert!(pdf_overprints(&mut over) > 0, "the black is written overprinting"); + assert_eq!(pdf_overprints(&mut black), 0); +} diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index cd089e04bd..82309cf1a0 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -542,7 +542,7 @@ pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option vec![(tl!("No Shading"), "none"), (tl!("Diffuse"), "diffuse")], (vectorcraft_effects::CLASSIC_EXTRUDE | vectorcraft_effects::CLASSIC_REVOLVE | vectorcraft_effects::CLASSIC_ROTATE, "shadingColor") => { - vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none")] + vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none"), (tl!("Black Overprint"), "blackOverprint")] } (vectorcraft_effects::EXTRUDE | vectorcraft_effects::CLASSIC_EXTRUDE, "bevel") => vec![ (tl!("None"), "none"), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..79c9b2230c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1162,6 +1162,7 @@ font-technology Variable Променливи Highlight Size Размер на отблясъка Blend Steps Стъпки на преливане Shading Color Цвят на засенчването + Black Overprint Черно с напечатване Draw Hidden Faces Изчертаване на скритите страни Eyedropper Пипета Eyedropper Applies: Пипетата прилага: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..c328ae9a05 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -520,6 +520,7 @@ Highlight Size Veličina odsjaja Blend Steps Koraci prelaza Shading Color Boja sjenčenja + Black Overprint Crni pretisak Draw Hidden Faces Crtaj skrivene strane Revolve… Rotaciono tijelo… Inflate… Napuhni… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..221fde4557 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1642,6 +1642,7 @@ antiAlias Sharp Nítid Highlight Size Mida de la brillantor Blend Steps Passos de fusió Shading Color Color de l’ombra + Black Overprint Negre en sobreimpressió Draw Hidden Faces Dibuixa les cares ocultes Eyedropper Comptagotes Eyedropper Applies: El comptagotes aplica: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..49255c036a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -533,6 +533,7 @@ Highlight Size Velikost odlesku Blend Steps Kroky prolnutí Shading Color Barva stínování + Black Overprint Přetisk černou Draw Hidden Faces Kreslit skryté stěny Revolve… Rotační těleso… Inflate… Nafouknutí… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..c84c49dfa0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1111,6 +1111,7 @@ Highlight Size Højlysstørrelse Blend Steps Overgangstrin Shading Color Skyggefarve + Black Overprint Sort overprint Draw Hidden Faces Tegn skjulte flader Revolve… Omdrej… Inflate… Pust op… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..e420257131 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1173,6 +1173,7 @@ font-technology Variable Variabel Highlight Size Glanzpunktgröße Blend Steps Angleichungsstufen Shading Color Schattierungsfarbe + Black Overprint Überdruckendes Schwarz Draw Hidden Faces Verdeckte Flächen zeichnen Eyedropper Pipette Sample Color from Screen Farbe vom Bildschirm aufnehmen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..f3fa7aea6b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1140,6 +1140,7 @@ font-technology Variable Μεταβλητές Highlight Size Μέγεθος ανταύγειας Blend Steps Βήματα ανάμειξης Shading Color Χρώμα σκίασης + Black Overprint Μαύρο με υπερεκτύπωση Draw Hidden Faces Σχεδίαση κρυφών εδρών Eyedropper Σταγονόμετρο (Eyedropper Tool) Eyedropper Applies: Το σταγονόμετρο εφαρμόζει: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..f0c90a60a0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1196,6 +1196,7 @@ font-technology Variable Variables Highlight Size Tamaño del brillo Blend Steps Pasos de fusión Shading Color Color de sombreado + Black Overprint Negro sobreimpreso Draw Hidden Faces Dibujar caras ocultas Eyedropper Cuentagotas Sample Color from Screen Tomar color de la pantalla diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..c42f5a9c3c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -530,6 +530,7 @@ Highlight Size Kiillon koko Blend Steps Sulautusvaiheet Shading Color Varjostusväri + Black Overprint Päällepainettu musta Draw Hidden Faces Piirrä piilotetut pinnat Revolve… Pyöräytä… Inflate… Täytä ilmalla… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..792514e69f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1191,6 +1191,7 @@ font-technology Variable Variables Highlight Size Taille de la brillance Blend Steps Étapes de transition Shading Color Couleur d’ombrage + Black Overprint Noir en surimpression Draw Hidden Faces Dessiner les faces cachées Eyedropper Pipette Sample Color from Screen Prélever une couleur à l’écran diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..b1d6b7e124 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3462,6 +3462,7 @@ Setup… સેટઅપ… Shading શેડિંગ Shading Color શેડિંગ રંગ + Black Overprint કાળો ઓવરપ્રિન્ટ Shadows and Glows પડછાયા અને ગ્લો Shape શેપ Shape Builder શેપ બિલ્ડર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..79781c16dd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1840,6 +1840,7 @@ antiAlias Sharp शार्प Highlight Size हाइलाइट आकार Blend Steps ब्लेंड चरण Shading Color शेडिंग रंग + Black Overprint काला ओवरप्रिंट Draw Hidden Faces छिपे हुए फलक बनाएँ Eyedropper आईड्रॉपर Eyedropper Applies: आईड्रॉपपर लागू होता है: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..e126652d26 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1495,6 +1495,7 @@ font-technology Variable Változó Highlight Size Csillanás mérete Blend Steps Átmenetlépések Shading Color Árnyékolás színe + Black Overprint Felülnyomó fekete Draw Hidden Faces Rejtett lapok rajzolása Eyedropper Pipetta Sample Color from Screen Szín mintavétele a képernyőről diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..88a5d92366 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -487,6 +487,7 @@ Highlight Size Ukuran kilau Blend Steps Langkah campuran Shading Color Warna pengarsiran + Black Overprint Hitam overprint Draw Hidden Faces Gambar sisi tersembunyi Revolve… Revolusi… Inflate… Gelembungkan… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..186a7181ee 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1203,6 +1203,7 @@ font-technology Variable Variabili Highlight Size Dimensione lucentezza Blend Steps Passaggi di fusione Shading Color Colore ombreggiatura + Black Overprint Nero in sovrastampa Draw Hidden Faces Disegna facce nascoste Eyedropper Contagocce Sample Color from Screen Campiona colore dallo schermo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..73c3670166 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -577,6 +577,7 @@ digits Malayalam マラヤーラム数字 Highlight Size ハイライトのサイズ Blend Steps ブレンドの階調 Shading Color 陰影のカラー + Black Overprint ブラックオーバープリント Draw Hidden Faces 隠れた面を描画 Revolve… 回転体… Inflate… 膨張… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 358960bd37..6e904cdb61 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2544,6 +2544,7 @@ Highlight Size ელვარების ზომა Blend Steps შერევის საფეხურები Shading Color დაჩრდილვის ფერი + Black Overprint ზედდაბეჭდილი შავი Draw Hidden Faces დამალული წახნაგების დახატვა Revolve… ბრუნვა… Inflate… გაბერვა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..b8116ec6d8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -570,6 +570,7 @@ digits Malayalam 말라얄람어 Highlight Size 하이라이트 크기 Blend Steps 혼합 단계 Shading Color 셰이딩 색상 + Black Overprint 검정 겹쳐찍기 Draw Hidden Faces 숨겨진 면 그리기 Revolve… 회전체… Inflate… 부풀리기… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..18484b6c1b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1007,6 +1007,7 @@ Highlight Size Glansgrootte Blend Steps Overvloeistappen Shading Color Arceringskleur + Black Overprint Zwart overprinten Draw Hidden Faces Verborgen vlakken tekenen Revolve… Draaien… Inflate… Opblazen… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..10d07baad9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -492,6 +492,7 @@ Highlight Size Rozmiar połysku Blend Steps Kroki przejścia Shading Color Kolor cieniowania + Black Overprint Czarny nadruk Draw Hidden Faces Rysuj ukryte ściany Revolve… Obrót… Inflate… Nadmuchanie… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..a8f5051c4e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1085,6 +1085,7 @@ antiAlias Sharp Nítido Highlight Size Tamanho do Realce Blend Steps Etapas de Mesclagem Shading Color Cor do Sombreamento + Black Overprint Preto em Sobreimpressão Draw Hidden Faces Desenhar Faces Ocultas Eyedropper Conta-gotas Eyedropper Applies: O Conta-gotas Aplica: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..5a83489ac0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1194,6 +1194,7 @@ font-technology Variable Вариативные Highlight Size Размер блика Blend Steps Шаги перехода Shading Color Цвет затенения + Black Overprint Чёрный с наложением Draw Hidden Faces Рисовать скрытые грани Eyedropper Пипетка Sample Color from Screen Взять цвет с экрана diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..c7c9cc79ca 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1173,6 +1173,7 @@ font-technology Variable Variabla Highlight Size Högdagerstorlek Blend Steps Övergångssteg Shading Color Skuggningsfärg + Black Overprint Svart övertryck Draw Hidden Faces Rita dolda ytor Eyedropper Pipett Eyedropper Applies: Pipetten tillämpar: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..7eac71007e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1167,6 +1167,7 @@ font-technology Variable Değişken Highlight Size Parlama Boyutu Blend Steps Karışım Adımları Shading Color Gölgeleme Rengi + Black Overprint Siyah Üst Baskı Draw Hidden Faces Gizli Yüzleri Çiz Eyedropper Damlalık Sample Color from Screen Ekrandan Örnek Renk diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..ba601bde45 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1197,6 +1197,7 @@ font-technology Variable Варіативні Highlight Size Розмір відблиску Blend Steps Кроки переходу Shading Color Колір затінення + Black Overprint Чорний із накладенням Draw Hidden Faces Малювати приховані грані Eyedropper Піпетка Sample Color from Screen Взяти колір з екрана diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..3042ae2089 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1380,6 +1380,7 @@ font-technology Variable Biến thiên Highlight Size Kích thước điểm sáng Blend Steps Số bước hòa trộn Shading Color Màu tô bóng + Black Overprint Đen in chồng Draw Hidden Faces Vẽ các mặt ẩn Eyedropper Ống hút màu Sample Color from Screen Lấy mẫu màu từ màn hình diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..6494b6b557 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1134,6 +1134,7 @@ antiAlias Sharp 锐利 Highlight Size 高光大小 Blend Steps 混合步骤 Shading Color 底纹颜色 + Black Overprint 黑色叠印 Draw Hidden Faces 绘制隐藏表面 Eyedropper 吸管 Sample Color from Screen 从屏幕取样颜色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..b4f286d3bf 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1167,6 +1167,7 @@ font-technology Variable 可變 Highlight Size 亮部大小 Blend Steps 漸變階數 Shading Color 網底顏色 + Black Overprint 黑色疊印 Draw Hidden Faces 繪製隱藏表面 Eyedropper 滴管 Sample Color from Screen 從螢幕取樣顏色 diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 290148b89d..e84973de83 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,7 +181,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); Map Art: none | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..670b693021 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4359,16 +4359,24 @@ is tall), `bevelInside` (false adds the bevel around the shape, true carves it i `softness` are not used). `ambient` (0..100%, default 50) lights every face. - `highlightIntensity` (0..100%, default 60) and `highlightSize` (0..100%, default 90; 100 is broad) shape the Plastic highlight. `blendSteps` (whole number, 1..256, default 25) is how many levels the shading is rounded to. -- `shadingColor`: `black` (the default), `custom` (darkens toward `shadingCustom`, a `#rrggbb` color) or `none` (the - paint is kept and only the highlight lightens it). `drawHiddenFaces` also draws the faces turned away from the - viewer, behind the others. +- `shadingColor`: `black` (the default), `custom` (darkens toward `shadingCustom`, a `#rrggbb` color), `none` (the + paint is kept and only the highlight lightens it) or `blackOverprint`. With `blackOverprint` every face keeps the + paint unchanged, and each face that darkens gets overprinting black over it, as strong as `black` would darken it. + The paint's own inks print as they are and the shading prints on the black plate. On screen the black is multiplied + over the paint, Separations Preview shows it on the Black plate, and `document.exportPdf` writes it as overprinting + fills + ([Shading Color options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)). + The highlight is not drawn with `blackOverprint`; that rule is VectorCraft's own. On a pattern face the black covers + the whole face, transparent pattern cells included, as the shading of the other shading colors does. + `drawHiddenFaces` also draws the faces turned away from the viewer, behind the others. - `preserveSpotColors` (default false) is the Lighting tab's Preserve Spot Colors checkbox. When it is on, a fill or stroke linked to a spot or global swatch stays linked on every face, so a spot color prints on its own plate in separations and PDF. The highlight lowers the swatch's tint, and a face that darkens gets black at the shade's strength over the swatch, multiplied and overprinting. These rules for drawing the shading are VectorCraft's own. The option does nothing while `shadingColor` is `custom`, since a custom shading color cannot keep a spot color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)). - Unlinked colors, gradients, patterns and the Wireframe surface draw as they do with it off. + Unlinked colors, gradients, patterns and the Wireframe surface draw as they do with it off. With `blackOverprint` + every face keeps its paint, swatch link included, whether the option is on or off. The defaults are VectorCraft's own. An unknown parameter, a number out of range, a flag that is not true or false, or an unknown surface or shading color is refused with an error and the document is not changed. diff --git a/docs/three-d.md b/docs/three-d.md index 2861bee0b7..461bd2352f 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -553,8 +553,10 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. face that darkens gets black over it, multiplied and overprinting, so a spot color stays on its own plate. The checkbox is unavailable while Shading Color is Custom ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); how - the faces are shaded with it is VectorCraft's own. The track cube, map art, Turntable and 3D export are separate, - unbuilt items. + the faces are shaded with it is VectorCraft's own. The Black Overprint shading color keeps each face's paint and + draws the shading over it as overprinting black, without the highlight. The shading is on the black plate in + Separations Preview and PDF output. The track cube, map art, Turntable and 3D export are + separate, unbuilt items. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md). From 4f09041edc55696daf4f2ed439619f0a3874506d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:31:47 -0800 Subject: [PATCH 07/54] 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 c08b4d932f341fb7b2dd1e6cd127e5db693c9acf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:52:00 -0800 Subject: [PATCH 08/54] MCP docs: Kurikaeshi Moji Shori says null leaves the setting as it is --- docs/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 7a8396740c..b0bdf2972e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9466,8 +9466,8 @@ from one frame into the next; ゝ and ヽ draw it without its voicing marks, and plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph -style's attributes), and Reset Panel turns it off. A value that is not true or false is refused, and a call that gives -the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a +style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the +setting as it is, and a call that gives the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a save reports a paragraph with it on as left out. The help page: https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html From be2f993c4b27b9010529a25622f9f384f70acde4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:56:03 -0800 Subject: [PATCH 09/54] PDF export: Preserve Numbers keeps a gray image's profile when RGB is tagged as sRGB With Preserve Numbers, a non-sRGB RGB destination and RGB colors ICC-tagged as sRGB (the `all` profiles setting, PDF/A-2b, PDF/X-3 and PDF/X-4), a gray image that carries an ICC profile was converted to sRGB grays and lost its profile. It now keeps its profile there, as in the other destinations other than sRGB. --- crates/pdf/src/export/images.rs | 3 ++- crates/pdf/src/images.rs | 12 ++++++++---- crates/pdf/src/output.rs | 7 +++++++ crates/pdf/src/tests/compression.rs | 18 ++++++++++-------- 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 70cc868c23..a91e6f8a0f 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -140,7 +140,8 @@ impl Exporter<'_> { let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); let then = out.converts_tagged_pixels().then_some(&*out); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then }); + let grey = out.converts_grey_images(); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then, grey }); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index 2f81d84571..c578c23176 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -335,6 +335,9 @@ pub(crate) struct ToSrgb<'a> { /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve /// Numbers). Its table is built when the first such image needs it. pub then: Option<&'a crate::output::ColorOut>, + /// Gray images are converted too: with an sRGB destination + /// ([`crate::output::ColorOut::converts_grey_images`]). In the others they keep their profile. + pub grey: bool, } /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of @@ -484,8 +487,9 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// they carry when `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces); /// with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB /// instead ([`ToSrgb`]), and colour ones then by `convert`, or without it by the conversion -/// `to_srgb` gives ([`ToSrgb::then`]); grey ones that either leaves as they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be -/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. +/// `to_srgb` gives ([`ToSrgb::then`]); grey ones keep their profile unless the destination is +/// sRGB ([`ToSrgb::grey`]). `interpolate` lets viewers smooth it. An image that can't be decoded +/// is kept as it is, with a warning when its pixels were to be converted to sRGB. pub(crate) fn recode( bytes: &[u8], size: (f64, f64), @@ -503,9 +507,9 @@ pub(crate) fn recode( use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. - // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. + // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). let then = to_srgb.and_then(|t| t.then); - let to_srgb = to_srgb.filter(|_| !(grey && (convert.is_some() || then.is_some()))); + let to_srgb = to_srgb.filter(|t| !grey || t.grey); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index dce763e9d6..d1365dc8d9 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -367,6 +367,13 @@ impl ColorOut { (rgb || self.pixels().is_some()).then_some(self.intent) } + /// Are gray images that carry an ICC profile converted from it to sRGB grays too + /// ([`Self::image_srgb_intent`])? Only with an sRGB destination; in the others, RGB tagged as + /// sRGB included, grey pixels are not converted and keep their profile. + pub(crate) fn converts_grey_images(&self) -> bool { + self.dest.as_ref().is_some_and(|d| d.model == Model::Rgb && d.srgb) + } + /// The destination a colour image converted from its ICC profile to sRGB /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 8ad11de270..871ab42bcb 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -776,7 +776,7 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None, grey: true }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, true, srgb_out); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); @@ -1069,16 +1069,18 @@ fn preserve_numbers_converts_tagged_images_from_their_profile() { let samples = image_samples(&pdf); let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); - // A gray image keeps its gray profile, in a CMYK and in an RGB destination. + // A gray image keeps its gray profile, in a CMYK and in an RGB destination, and in an RGB one + // with RGB colours ICC-tagged as sRGB (`all` profiles, PDF/A-2b). let gray = gray_profile(&[0x01CD]); let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); - for destination in [GENERIC_CMYK, WIDE_GAMUT_RGB] { - let settings = json!({"output": {"conversion": "preserveNumbers", "destination": destination}}); + for (what, settings) in [ + (GENERIC_CMYK, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}})), + (WIDE_GAMUT_RGB, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ("all profiles", json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}})), + ("PDF/A-2b", json!({"standard": "pdfA2b", "output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ] { let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); - assert!( - spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), - "gray, {destination}: {spaces:?}" - ); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), "gray, {what}: {spaces:?}"); } // In an sRGB destination it is converted to sRGB grays and written without it. let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); From 65b2129138859a518439ab43f506e421ecc7d7dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:44:08 -0800 Subject: [PATCH 10/54] 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 b6463e53cc6c2a026a172866d6d7979048f43924 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:13:16 -0800 Subject: [PATCH 11/54] Paragraph: threaded Kurikaeshi Moji Shori leads come from one pass over the frames A thread of frames that hold only repeat marks or soft returns made each frame look back through every frame before it, so opening or flowing such a story took quadratic time, with the setting off as well. The leads are now carried forward in one pass. --- crates/engine/src/cmd/threads.rs | 39 +++++++++++++++----------- crates/engine/src/cmd/threads/tests.rs | 18 ++++++++++++ 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 7ccf26d3de..f4f807cb15 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -404,23 +404,22 @@ pub(crate) fn mark_continued(doc: &mut Document) { /// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and /// whether each one's first paragraph `continues` from the frame before: the last character of -/// that paragraph in the frames before that a repeat mark could stand for, or None. +/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over +/// the frames: each frame's lead is carried forward to the next. fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec> { - (0..texts.len()) - .map(|k| { - let mut j = k; - while continues.get(j) == Some(&true) && j > 0 { - j -= 1; - let text = texts.get(j)?; - let tail = text.rfind('\n').map_or(Some(text.as_str()), |at| text.get(at + 1..))?; - if let Some(c) = vectorcraft_text::repeat_base(tail) { - return Some(c); - } - if tail.len() != text.len() { - return None; - } - } - None + // The lead the next frame takes when its first paragraph continues from this one. + let mut carry = None; + texts + .iter() + .enumerate() + .map(|(k, text)| { + #[cfg(test)] + LEAD_SCANS.with(|c| c.set(c.get() + 1)); + let lead = carry.filter(|_| continues.get(k) == Some(&true)); + let tail = text.rsplit('\n').next().unwrap_or(text); + // A paragraph break in this frame ends the paragraph the lead came from. + carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len())); + lead }) .collect() } @@ -432,6 +431,8 @@ thread_local! { static THREAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many times [`story_in`] went through a thread's frames on this thread. static STORY_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many frame texts [`first_para_leads`] went through on this thread. + static LEAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's @@ -447,6 +448,12 @@ pub(crate) fn story_builds() -> usize { STORY_BUILDS.with(std::cell::Cell::get) } +/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread. +#[cfg(test)] +pub(crate) fn lead_scans() -> usize { + LEAD_SCANS.with(std::cell::Cell::get) +} + /// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a /// path; empty when `id` is in no thread or the thread has fewer than two such frames. pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec { diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index ba2cbaa1d4..82ac2f9f76 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2262,3 +2262,21 @@ fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { assert!(tb.first_para_continues); assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); } + +/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one +/// pass over the frames, each frame's text gone through once, not once for every frame after it. +#[test] +fn continued_frame_leads_go_through_each_frame_once() { + let n = 2000; + let mut texts = vec!["時".to_string()]; + texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1)); + let continues: Vec = (0..n).map(|k| k > 0).collect(); + let before = lead_scans(); + let leads = first_para_leads(&texts, &continues); + assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before); + assert_eq!(leads.first(), Some(&None)); + assert!(leads.iter().skip(1).all(|l| *l == Some('時'))); + // A paragraph break stops the carry, and a frame that starts a paragraph carries nothing. + let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]); + assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]); +} From 74f139062b468992fb79d76d2e0277a46702861c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:31:23 -0800 Subject: [PATCH 12/54] Paragraph: Kurikaeshi Moji Shori scans a paragraph once while laying it out Each line that started with a repeat mark scanned the paragraph's text from its start for the character the mark stands for, so a paragraph with marks at the start of many lines took quadratic time to lay out. The scan now goes on from the line before. --- crates/text/src/layout/flow.rs | 47 ++++++++++++++++++++++++---------- crates/text/src/shape.rs | 14 ++++++++++ crates/text/src/tests.rs | 22 ++++++++++++++++ 3 files changed, 70 insertions(+), 13 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index f028d47898..3999401a05 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -13,7 +13,8 @@ use super::{ is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeated_char, shape_range}; +use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeat_base, repeated_char, shape_range}; +use std::cell::Cell; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? @@ -216,6 +217,9 @@ struct ParagraphData<'a, 'text> { /// Kurikaeshi Moji Shori: the character before a `continued` paragraph in the frames before /// ([`TextObject::first_para_lead`]). lead: Option, + /// Kurikaeshi Moji Shori: the byte the paragraph's text has been scanned to for the character a + /// repeat mark could stand for, and that character so far ([`ParagraphData::repeat_base_before`]). + repeat_scan: Cell<(usize, Option)>, sg: Vec, compressed: Vec, wakan: Vec, @@ -234,6 +238,21 @@ struct ParagraphData<'a, 'text> { regions: Option<&'a [Region]>, } +impl ParagraphData<'_, '_> { + /// Kurikaeshi Moji Shori: the character a repeat mark at byte `at` of `text` could stand for, + /// the last one before it in the paragraph that [`repeat_base`] takes, or else the paragraph's + /// `lead`. Lines are laid out in order, so each call scans on from where the call before it + /// stopped; a byte before that starts the scan again at the paragraph's start. None when `at` + /// does not fall on a character boundary after the paragraph's start. + fn repeat_base_before(&self, text: &str, at: usize) -> Option> { + let (from, base) = self.repeat_scan.get(); + let (from, base) = if from <= at { (from, base) } else { (self.pr.start, self.lead) }; + let base = repeat_base(text.get(from..at)?).or(base); + self.repeat_scan.set((at, base)); + Some(base) + } +} + fn prepare_paragraph<'a, 'text>( cx: &mut Ctx<'text>, pen: &mut Pen<'_>, @@ -327,14 +346,16 @@ fn prepare_paragraph<'a, 'text>( let zone = if cx.opts.composer.unwrap_or(para.composer).is_single_line() { para.hyphenation.zone } else { 0.0 }; let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX); let mirror = mirrors_indents(para, rtl, cx.vertical); + let lead = t.first_para_lead.filter(|_| continued); ParagraphData { para, + repeat_scan: Cell::new((pr.start, lead)), pr, marker_text, bidi, rtl, continued, - lead: t.first_para_lead.filter(|_| continued), + lead, sg, compressed, wakan, @@ -1277,18 +1298,18 @@ fn emit_line_glyph( } /// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of -/// a line of the paragraph starting at byte `para_start`, when `g` is a repeat mark, and the -/// character it shows: the character [`repeated_char`] gives, shaped in the mark's style with the -/// type's features (so vertical type gets the font's vertical forms), from the same face, with the -/// mark's advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, -/// belongs to a tate-chu-yoko or warichu block, nothing before it in the paragraph fits, or the face -/// draws the character with no glyph or with more than one. `lead` stands before a paragraph that -/// continues from the frame before ([`TextObject::first_para_lead`]). -fn repeat_mark_glyph(cx: &Ctx<'_>, para_start: usize, lead: Option, g: &SGlyph) -> Option<(SGlyph, char)> { - if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() { +/// a line of `paragraph`, when `g` is a repeat mark, and the character it shows: the character +/// [`repeated_char`] gives, shaped in the mark's style with the type's features (so vertical type +/// gets the font's vertical forms), from the same face, with the mark's advance and place, so the +/// line breaks stay as they are. None when `g` is no repeat mark, belongs to a tate-chu-yoko or +/// warichu block, nothing before it in the paragraph fits, or the face draws the character with no +/// glyph or with more than one. The paragraph's `lead` stands before a paragraph that continues +/// from the frame before ([`TextObject::first_para_lead`]). +fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph) -> Option<(SGlyph, char)> { + if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(lead, cx.text.get(para_start..g.byte)?, g.ch)?; + let c = repeated_char(paragraph.repeat_base_before(cx.text, g.byte)?, "", g.ch)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1305,7 +1326,7 @@ fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: return None; } let g = paragraph.sg.get(first)?; - let (glyph, c) = repeat_mark_glyph(cx, paragraph.pr.start, paragraph.lead, g)?; + let (glyph, c) = repeat_mark_glyph(cx, paragraph, g)?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 9d09ce076e..097b056d7d 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -456,9 +456,23 @@ pub fn inseparable(a: char, b: char) -> bool { /// paragraph continues from the frame before the result for the text before it /// (`TextObject::first_para_lead`). pub fn repeat_base(text: &str) -> Option { + #[cfg(test)] + REPEAT_SCANNED.with(|c| c.set(c.get() + text.len())); text.chars().rev().find(|&c| !matches!(c, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ' | '\u{2028}' | '\u{3099}' | '\u{309A}')) } +#[cfg(test)] +thread_local! { + /// Tests: how many bytes of text [`repeat_base`] was given on this thread. + static REPEAT_SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Tests: how many bytes of text [`repeat_base`] has been given on this thread. +#[cfg(test)] +pub(crate) fn repeat_scanned() -> usize { + REPEAT_SCANNED.get() +} + /// Kurikaeshi Moji Shori: the character the repeat mark `mark` stands for after the text `before` /// it, or None when `mark` is not a repeat mark or nothing before it fits. `lead` stands before /// `before` (the text of a threaded paragraph in the frames before). VectorCraft's rules: the diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 477c3e3392..b15b0757be 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2810,6 +2810,28 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); } +/// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid +/// out in one scan of its text, not one scan of everything before each line. +#[test] +fn kurikaeshi_moji_shori_scans_a_paragraph_once() { + use crate::shape::repeat_scanned; + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let text = format!("時{}", "\u{2028}々".repeat(2000)); + let mut t = TextObject::point(Point::ZERO, &text, st); + t.para.kurikaeshi_moji_shori = true; + let before = repeat_scanned(); + let l = layout(&db, &t); + let scanned = repeat_scanned() - before; + assert!(scanned <= 2 * text.len(), "{scanned} bytes scanned for a paragraph of {}", text.len()); + // Every line's 々 is still drawn as 時. + assert_eq!(l.repeat_marks.len(), 2000); + assert!(l.glyphs.iter().filter(|g| g.byte > 0 && text.get(g.byte..).is_some_and(|s| s.starts_with('々'))).all(|g| g.gid == face.glyph_for('時'))); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] From a5b84d8e2ae997a1059ce4ce22573de0e1d13ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:38:15 -0800 Subject: [PATCH 13/54] Paragraph: Kurikaeshi Moji Shori keeps one record per mark when area type flows again Vertically aligned area type in a frame that is not a rectangle flows its text again until it settles, and each pass added the line-start repeat marks to the layout's records once more, so SVG export could look up the wrong character. Each pass now starts from empty records, and an undone pass restores the ones before it. --- crates/text/src/layout/vertical.rs | 3 ++- crates/text/src/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 30f12139a2..3262362fae 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -529,13 +529,14 @@ pub(super) fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range], t: &Tex std::mem::take(&mut cx.out.lines), std::mem::take(&mut cx.out.inlines), std::mem::take(&mut cx.out.markers), + std::mem::take(&mut cx.out.repeat_marks), std::mem::replace(&mut cx.out.overflow, false), ); flow(cx, paras, t, Some(regions)); if laid_out(&cx.out) < before { // Text no longer fits (lines got narrower, or flow around a wrap object): undo the // pass and try a smaller step. - (cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.markers, cx.out.overflow) = prev; + (cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.markers, cx.out.repeat_marks, cx.out.overflow) = prev; for (r, (shift, gap)) in regions.iter_mut().zip(saved) { r.shift = shift; r.gap = gap; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index b15b0757be..d2940f83b5 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2832,6 +2832,29 @@ fn kurikaeshi_moji_shori_scans_a_paragraph_once() { assert!(l.glyphs.iter().filter(|g| g.byte > 0 && text.get(g.byte..).is_some_and(|s| s.starts_with('々'))).all(|g| g.gid == face.glyph_for('時'))); } +/// Kurikaeshi Moji Shori: area type in a frame that isn't a rectangle, centered vertically, flows +/// again until it settles, and keeps one record for each repeat mark it draws as another character. +#[test] +fn vertically_centered_repeat_marks_in_a_round_frame_are_recorded_once() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + use vectorcraft_doc::VerticalAlign; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let text = format!("時{}", "\u{2028}々".repeat(5)); + let frame = kurbo::Ellipse::new((150.0, 150.0), (150.0, 150.0), 0.0).to_path(0.1); + let mut t = area(&text, st, Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left); + t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) }; + t.para.kurikaeshi_moji_shori = true; + let top = layout(&db, &t); + let marks: Vec<(usize, char)> = text.match_indices('々').map(|(b, _)| (b, '時')).collect(); + assert_eq!(top.repeat_marks, marks); + t.area.vertical_align = VerticalAlign::Center; + let lay = layout(&db, &t); + assert!(lay.lines[0].baseline > top.lines[0].baseline + 1.0, "the text moves down"); + assert_eq!(lay.repeat_marks, marks); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] From fcaed952fb9825420cbc99d6b7848f47e4092cef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:50:38 -0800 Subject: [PATCH 14/54] Paragraph: Kurikaeshi Moji Shori draws a threaded type-on-path frame's first repeat mark A frame of type on a path whose first paragraph continues from the frame before now draws a repeat mark at its start as the character before it in the frames before, as area and point type do. The mark keeps its advance, so the glyphs stay where they were, and live SVG text writes the character drawn. --- crates/text/src/layout/flow.rs | 24 +++++++++++++----------- crates/text/src/layout/on_path.rs | 22 +++++++++++++++++++++- crates/text/src/tests.rs | 18 ++++++++++++++++++ 3 files changed, 52 insertions(+), 12 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 3999401a05..50f0cef433 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1298,18 +1298,17 @@ fn emit_line_glyph( } /// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of -/// a line of `paragraph`, when `g` is a repeat mark, and the character it shows: the character -/// [`repeated_char`] gives, shaped in the mark's style with the type's features (so vertical type -/// gets the font's vertical forms), from the same face, with the mark's advance and place, so the -/// line breaks stay as they are. None when `g` is no repeat mark, belongs to a tate-chu-yoko or -/// warichu block, nothing before it in the paragraph fits, or the face draws the character with no -/// glyph or with more than one. The paragraph's `lead` stands before a paragraph that continues -/// from the frame before ([`TextObject::first_para_lead`]). -fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph) -> Option<(SGlyph, char)> { +/// a line, when `g` is a repeat mark, and the character it shows: the character [`repeated_char`] +/// gives for the character `base` finds before the mark, shaped in the mark's style with the type's +/// features (so vertical type gets the font's vertical forms), from the same face, with the mark's +/// advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, belongs +/// to a tate-chu-yoko or warichu block, `base` gives None, nothing before it fits, or the face draws +/// the character with no glyph or with more than one. `base` runs only for a repeat mark. +pub(super) fn repeat_mark_glyph(cx: &Ctx<'_>, g: &SGlyph, base: impl FnOnce() -> Option>) -> Option<(SGlyph, char)> { if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(paragraph.repeat_base_before(cx.text, g.byte)?, "", g.ch)?; + let c = repeated_char(base()?, "", g.ch)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1320,13 +1319,16 @@ fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph /// Kurikaeshi Moji Shori: the glyph drawn in place of glyph `first` of `paragraph`, the first /// character of a line that ends before glyph `end`, when the paragraph has the setting on and -/// [`repeat_mark_glyph`] gives one; it is recorded in [`crate::TextLayout::repeat_marks`]. +/// [`repeat_mark_glyph`] gives one for the character before it in the paragraph, or the paragraph's +/// `lead` before a paragraph that continues from the frame before ([`TextObject::first_para_lead`]); +/// it is recorded in [`crate::TextLayout::repeat_marks`]. fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: usize, end: usize) -> Option { if !paragraph.para.kurikaeshi_moji_shori || first >= end { return None; } let g = paragraph.sg.get(first)?; - let (glyph, c) = repeat_mark_glyph(cx, paragraph, g)?; + let text = cx.text; + let (glyph, c) = repeat_mark_glyph(cx, g, || paragraph.repeat_base_before(text, g.byte))?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index ecb1377d10..80aaa5ea9a 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -1,6 +1,6 @@ use super::bidi::{is_rtl, para_bidi_with, visual_order}; use super::breaking::{Metrics, optical_hangs, optical_hangs_rtl, optical_share, roman_share}; -use super::flow::list_markers; +use super::flow::{list_markers, repeat_mark_glyph}; use super::region::in_range; use super::{ Affine, ArcPath, BezPath, Ctx, GlyphBend, Justify, LineInfo, ListMarker, ParamCurve, PathAlign, PathData, PathEffect, PathEl, Point, Range, @@ -409,6 +409,21 @@ fn hide_before_open_path(cx: &mut Ctx<'_>, ap: &ArcPath, lead: bool, at: usize, true } +/// Kurikaeshi Moji Shori: type on a path is one line, which starts with the first character of its +/// first paragraph `pr` (shaped as `glyphs`). When that paragraph continues from the frame before +/// and has the setting on, a repeat mark there is drawn as the character before it in the frames +/// before ([`TextObject::first_para_lead`]): its glyph in `glyphs` is replaced, and the mark's byte +/// and the character drawn are returned. +fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range, glyphs: &mut [SGlyph]) -> Option<(usize, char)> { + if !t.first_para_continues || !t.para_at(0).kurikaeshi_moji_shori { + return None; + } + let g = glyphs.iter_mut().find(|g| g.len > 0 && g.byte == pr.start)?; + let (glyph, c) = repeat_mark_glyph(cx, g, || Some(t.first_para_lead))?; + *g = glyph; + Some((g.byte, c)) +} + /// Lay type on a path out along `path` (text space), between its brackets. pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, path: &PathData) { cx.out.on_path = true; @@ -431,6 +446,8 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, } shaped.push((pr.clone(), bidi.filter(|b| b.has_rtl() && !cx.vertical), glyphs)); } + // Kurikaeshi Moji Shori: the repeat mark that starts the line, recorded when its glyph is drawn. + let mut repeat = shaped.first_mut().and_then(|(pr, _, glyphs)| line_start_repeat(cx, t, pr, glyphs)); let rtl = rtl.unwrap_or(false); // The text before byte `cut` in visual order, as area type reorders each line it breaks. let visual = |cut: usize| { @@ -710,6 +727,9 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, let at = cx.out.glyphs.len(); cx.emit(g, pre, origin, angle, g.adv, 0); let hidden = hide_before_open_path(cx, &ap, lead, at, s + step * 0.5, rise); + if !hidden && let Some(mark) = repeat.take_if(|&mut (byte, _)| g.len > 0 && g.byte == byte) { + cx.out.repeat_marks.push(mark); + } // A glyph of a script whose letters join is bent along a curved path (Rainbow), so its // joining strokes meet its neighbours' instead of standing off the curve. if !hidden && t.path_effect == PathEffect::Rainbow && g.cursive && !cx.vertical && g.inline.is_none() { diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index d2940f83b5..147b6a4818 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2808,6 +2808,24 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { let on = layout(&db, &t); assert_eq!(gid_of(&on, 0), glyph('時'), "the frame's first 々 is drawn as 時"); assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); + assert_eq!(on.repeat_marks, [(0, '時')]); + // Type on a path is one line: a threaded frame on a path starts it the same way. + let mut line = BezPath::new(); + line.move_to((0.0, 50.0)); + line.line_to((500.0, 50.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let on = layout(&db, &t); + assert!(on.on_path); + assert_eq!(gid_of(&on, 0), glyph('時'), "type on a path: the frame's first 々 is drawn as 時"); + assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "type on a path: the next paragraph's first mark keeps its glyph"); + assert_eq!(on.repeat_marks, [(0, '時')]); + t.para.kurikaeshi_moji_shori = false; + let off = layout(&db, &t); + assert_eq!(gid_of(&off, 0), glyph('々'), "type on a path with the setting off"); + assert!(off.repeat_marks.is_empty()); + t.para.kurikaeshi_moji_shori = true; + t.first_para_continues = false; + assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "type on a path in a frame that does not continue"); } /// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid From 7d7c5918f3966364c21e29953138929686e9ee69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:52:57 -0800 Subject: [PATCH 15/54] MCP docs: Kurikaeshi Moji Shori covers the first repeat mark of a frame of type on a path --- docs/mcp.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index b0bdf2972e..0769d0a97e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9455,8 +9455,8 @@ https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html `text.setFormat {kurikaeshiMojiShori: bool}` (Paragraph panel menu › Kurikaeshi Moji Shori, shown with the East Asian options) turns it on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a `start` / `end` -range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, is drawn as the -character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, +range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, or starts a frame +of type on a path (which holds one line), is drawn as the character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the @@ -9464,7 +9464,7 @@ repeated character is the last one before the mark in the paragraph that is not combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a -paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph +paragraph, and inside tate-chu-yoko or warichu. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the setting as it is, and a call that gives the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a From 3ca38f2237e73d24a87fbe7e13d3c6e12374df0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:01:43 -0800 Subject: [PATCH 16/54] =?UTF-8?q?Paragraph:=20Kurikaeshi=20Moji=20Shori=20?= =?UTF-8?q?draws=20=E3=82=9D=20or=20=E3=83=BD=20with=20a=20combining=20voi?= =?UTF-8?q?cing=20mark=20as=20voiced?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ゝ or ヽ followed by U+3099, which a font draws as one glyph, is now drawn at a line start as ゞ or ヾ would be, instead of as the plain kana. A mark that shares its cluster with other glyphs, or with any other combining character, keeps its own glyphs. --- crates/text/src/layout/flow.rs | 28 ++++++++++++++++++++++------ crates/text/src/layout/on_path.rs | 5 +++-- crates/text/src/tests.rs | 23 +++++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 50 insertions(+), 9 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 50f0cef433..36881e20d8 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1301,14 +1301,30 @@ fn emit_line_glyph( /// a line, when `g` is a repeat mark, and the character it shows: the character [`repeated_char`] /// gives for the character `base` finds before the mark, shaped in the mark's style with the type's /// features (so vertical type gets the font's vertical forms), from the same face, with the mark's -/// advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, belongs -/// to a tate-chu-yoko or warichu block, `base` gives None, nothing before it fits, or the face draws -/// the character with no glyph or with more than one. `base` runs only for a repeat mark. -pub(super) fn repeat_mark_glyph(cx: &Ctx<'_>, g: &SGlyph, base: impl FnOnce() -> Option>) -> Option<(SGlyph, char)> { +/// advance and place, so the line breaks stay as they are. ゝ or ヽ followed by a combining voicing +/// mark (U+3099) in one glyph counts as ゞ or ヾ. None when `g` is no repeat mark, belongs to a +/// tate-chu-yoko or warichu block, holds other characters with the mark, shares its cluster with the +/// glyph after it (`next`), `base` gives None, nothing before it fits, or the face draws the +/// character with no glyph or with more than one. `base` runs only for a repeat mark. +pub(super) fn repeat_mark_glyph( + cx: &Ctx<'_>, + g: &SGlyph, + next: Option<&SGlyph>, + base: impl FnOnce() -> Option>, +) -> Option<(SGlyph, char)> { if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(base()?, "", g.ch)?; + if next.is_some_and(|n| n.byte == g.byte) { + return None; + } + let mark = match cx.text.get(g.byte..g.byte + g.len)? { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + cluster if cluster.len() == g.ch.len_utf8() => g.ch, + _ => return None, + }; + let c = repeated_char(base()?, "", mark)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1328,7 +1344,7 @@ fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: } let g = paragraph.sg.get(first)?; let text = cx.text; - let (glyph, c) = repeat_mark_glyph(cx, g, || paragraph.repeat_base_before(text, g.byte))?; + let (glyph, c) = repeat_mark_glyph(cx, g, paragraph.sg.get(first + 1), || paragraph.repeat_base_before(text, g.byte))?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 80aaa5ea9a..b69470b9d9 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -418,8 +418,9 @@ fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range, glyphs: &m if !t.first_para_continues || !t.para_at(0).kurikaeshi_moji_shori { return None; } - let g = glyphs.iter_mut().find(|g| g.len > 0 && g.byte == pr.start)?; - let (glyph, c) = repeat_mark_glyph(cx, g, || Some(t.first_para_lead))?; + let at = glyphs.iter().position(|g| g.len > 0 && g.byte == pr.start)?; + let (glyph, c) = repeat_mark_glyph(cx, glyphs.get(at)?, glyphs.get(at + 1), || Some(t.first_para_lead))?; + let g = glyphs.get_mut(at)?; *g = glyph; Some((g.byte, c)) } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 147b6a4818..c04200a94f 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2828,6 +2828,29 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "type on a path in a frame that does not continue"); } +/// Kurikaeshi Moji Shori: ゝ or ヽ typed with a combining voicing mark (U+3099) after it, which the +/// font draws as one glyph, is drawn as the voiced character at a line start, as ゞ and ヾ are. +#[test] +fn kurikaeshi_moji_shori_draws_a_decomposed_voiced_mark_voiced() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let glyph = |c: char| Some(face.glyph_for(c)); + let gid_of = |l: &TextLayout, b: usize| l.glyphs.iter().find(|g| g.byte == b).map(|g| g.gid); + for (text, mark, want) in [("す\u{2028}ゝ\u{3099}", 'ゞ', 'ず'), ("サ\u{2028}ヽ\u{3099}", 'ヾ', 'ザ')] { + let at = text.find(['ゝ', 'ヽ']).expect("mark"); + let mut t = TextObject::point(Point::ZERO, text, st.clone()); + let off = layout(&db, &t); + assert_eq!(gid_of(&off, at), glyph(mark), "{text:?}: off, the font draws the voiced mark"); + t.para.kurikaeshi_moji_shori = true; + let on = layout(&db, &t); + assert_eq!(gid_of(&on, at), glyph(want), "{text:?}"); + assert_eq!(on.repeat_marks, [(at, want)], "{text:?}"); + } +} + /// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid /// out in one scan of its text, not one scan of everything before each line. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0769d0a97e..9dadf1c1d2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9463,7 +9463,8 @@ VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the -plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a +plain kana when it has none; ゝ or ヽ followed by a combining voicing mark (U+3099) counts as ゞ or ヾ when the font draws the +pair as one glyph, and is drawn as it is when the font draws two. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a paragraph, and inside tate-chu-yoko or warichu. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the From 9548a669a0e3c89435f4730a07cae2a0a2e3e7ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:17:36 -0800 Subject: [PATCH 17/54] SVG export: type on a path that starts with a drawn repeat mark is outlined Type on a path whose frame starts with a repeat mark drawn as the character it repeats is now written as outlines with a warning, as other type on a path that a cannot reproduce is. With Kurikaeshi Moji Shori off it stays live text. --- crates/svg/src/export/text.rs | 5 +++++ crates/svg/tests/it/text_layout.rs | 31 ++++++++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 5a1e811062..907068c56d 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -294,6 +294,11 @@ impl Writer<'_> { self.warn("type on a path with bullets or numbers is outlined to keep its look"); return self.text_outlines(n, t); } + // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). + if !lay.repeat_marks.is_empty() { + self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); + return self.text_outlines(n, t); + } return self.text_on_path(n, t, path, *start); } self.note_fonts(t, &lay); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index a190f21dea..ff27c96955 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -941,3 +941,34 @@ fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { } } } + +/// Kurikaeshi Moji Shori: a `` cannot draw a character in another character's width, so +/// type on a path whose threaded frame starts with a repeat mark drawn as the character it repeats +/// is outlined, with a warning; with the setting off it stays live text. +#[test] +fn a_repeat_mark_starting_a_frame_on_a_path_is_outlined() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), ..style(12.0) }; + let mut line = BezPath::new(); + line.move_to((20.0, 40.0)); + line.line_to((280.0, 40.0)); + for on in [false, true] { + let mut t = TextObject::point(Point::ZERO, "々龘々", st.clone()); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t.para.kurikaeshi_moji_shori = on; + t.first_para_continues = true; + t.first_para_lead = Some('龘'); + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = vectorcraft_svg::export_full(&d, &ExportOptions::default(), None); + let warned = out.warnings.iter().any(|w| w.contains("repeat mark")); + if on { + assert!(!out.svg.contains("々龘々<") && !warned, "{:?}: {}", out.warnings, out.svg); + } + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 9dadf1c1d2..89393a9ae6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9458,7 +9458,8 @@ options) turns it on or off for the paragraphs of the selected type (or `ids`, o range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, or starts a frame of type on a path (which holds one line), is drawn as the character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. -SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. +SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded; it writes type on a +path that starts with such a mark as outlines, with a warning. VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph From 6bc3249fdfd9f1a890d71167ec850526547ca128 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:20:55 -0800 Subject: [PATCH 18/54] =?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 19/54] =?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 831e539ecc2455171bb1558f1e5f0a12a231da96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:54:05 -0800 Subject: [PATCH 20/54] SVG export: a drawn repeat mark in scaled type keeps its character's width In horizontally scaled type, live SVG text stretched the character a repeat mark is drawn as (Kurikaeshi Moji Shori) to the mark's advance with textLength, so a reader narrowed or widened it whenever the two glyphs' widths differ. Its textLength now takes the width the canvas draws that character at; the text after it is still placed anew. --- crates/svg/src/export/text.rs | 36 +++++++++++++++++++++++++++--- crates/svg/tests/it/text_layout.rs | 30 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 907068c56d..b341a62c0c 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -439,7 +439,8 @@ impl Writer<'_> { // reader would draw elsewhere, the next segment is placed. place = seg.brk || (!fewer && !base.anchored && positioned); if (st.h_scale - st.v_scale).abs() > 1e-9 || seg.scale != 1.0 { - attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(seg.advance * seg.scale))); + let length = seg.advance * seg.scale + seg.repeat_widen; + attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(length))); } if st.rotation != 0.0 { attrs.push_str(&format!(" rotate=\"{}\"", self.num(-st.rotation))); @@ -716,6 +717,9 @@ struct Segment { /// Glyph Scaling of the segment's one glyph (Justification…), which a reader stretches it to /// (`textLength`); 1 for other segments. scale: f64, + /// How much wider than the repeat mark the canvas draws the character the mark is drawn as + /// (Kurikaeshi Moji Shori), which a reader stretches it to (`textLength`); 0 for other segments. + repeat_widen: f64, /// A list marker's characters and tab, written in /// [`vectorcraft_doc::text::ParaList::marker_style`] of the run's style. marker: bool, @@ -736,6 +740,30 @@ fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_te lay.repeat_marks.get(at).map(|&(_, c)| c) } +/// Kurikaeshi Moji Shori: how much wider than repeat mark `cluster` the canvas draws glyph `g`, the +/// character the mark is drawn as in the mark's place (text space), or 0 when the face or the +/// mark's glyph is not found. +fn repeat_widen(g: &vectorcraft_text::PositionedGlyph, cluster: &str) -> f64 { + let Some(face) = FontDb::global().face_by_id(g.font_id) else { return 0.0 }; + // ゝ or ヽ with a combining voicing mark is drawn as one glyph, the voiced mark's. + let mark = match cluster { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + _ => match cluster.chars().next() { + Some(c) => c, + None => return 0.0, + }, + }; + let mark_gid = face.glyph_for(mark); + if mark_gid == 0 { + return 0.0; + } + // Font units along the baseline → text space (size, Horizontal Scale and Glyph Scaling). + let [a, b, ..] = g.xf.as_coeffs(); + let widen = (face.advance(g.gid) - face.advance(mark_gid)) * a.hypot(b); + if widen.is_finite() { widen } else { 0.0 } +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -829,6 +857,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - Some(c) => c.to_string(), None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), }; + let widen = if repeat.is_some() { repeat_widen(g, source(line.glyph_start + k, g)) } else { 0.0 }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; // The character a repeat mark is drawn as takes the mark's width on the canvas, which a // reader does not know: the text after it is placed anew. @@ -846,7 +875,8 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let marker = lay.marker_of(line.glyph_start + k).is_some(); let tab_apart = piece == "\t" && (run.style.h_scale - run.style.v_scale).abs() > 1e-9; match segs.last_mut() { - Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart => { + // The character a repeat mark is drawn as is a segment of its own, stretched to its width. + Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart && repeat.is_none() => { last.text.push_str(&piece); last.advance += advance; last.brk = brk; @@ -856,7 +886,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - last.brk |= moved || last.marker != marker; end_segment(last, tail, t, lay, &mut unkerned); } - segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, marker }); + segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, repeat_widen: widen, marker }); } } tail = set.map(|_| (g.byte, advance)); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index ff27c96955..95d2fd0b24 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -942,6 +942,36 @@ fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { } } +/// Kurikaeshi Moji Shori in horizontally scaled type: the character a repeat mark is drawn as is +/// stretched (`textLength`) to the width the canvas draws that character at, not to the mark's +/// advance, so a reader does not distort it when the two characters' widths differ. +#[test] +fn a_drawn_repeat_mark_in_scaled_type_keeps_the_width_of_its_character() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + // The test font draws 龘 and 々 with glyphs of different widths. + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), h_scale: 50.0, ..style(12.0) }; + let mut t = TextObject::point(Point::new(20.0, 40.0), "龘\u{2028}々", st); + t.para.kurikaeshi_moji_shori = true; + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let svg = export(&d, &ExportOptions::default()); + // The textLength of each `` that holds 龘 alone: the one on the first line and the one + // the mark is drawn as on the second. + let lengths: Vec<&str> = svg + .match_indices(">龘<") + .map(|(at, _)| { + let tag = &svg[svg[..at].rfind('<').unwrap_or(0)..at]; + let from = tag.find("textLength=\"").unwrap_or_else(|| panic!("{tag}: {svg}")) + "textLength=\"".len(); + &tag[from..from + tag[from..].find('"').unwrap_or(0)] + }) + .collect(); + assert_eq!(lengths.len(), 2, "{svg}"); + assert_eq!(lengths[0], lengths[1], "{svg}"); +} + /// Kurikaeshi Moji Shori: a `` cannot draw a character in another character's width, so /// type on a path whose threaded frame starts with a repeat mark drawn as the character it repeats /// is outlined, with a warning; with the setting off it stays live text. From d4bbacc3ebb4bfac4b83eff349f483768abccfd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:57:09 -0800 Subject: [PATCH 21/54] Export: live effects in symbol art apply in EMF, WMF and SVG EMF, WMF and SVG wrote a symbol instance from its symbol's art as stored, so live effects inside that art were missing: a square moved 100 pt by a Transform effect stayed in place in the file while the canvas drew it moved. Art whose own place is off the artboard was left out even when the effect moved it onto it. These exports now call bake_document_placing_symbols, as PDF, print, EPS and DXF do: each instance of a symbol whose art needs baking is written as that art placed by the instance and then baked, so an instance that scales or turns its art does not scale what its effects do. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances are written as groups; instances of symbols without such effects still share one . Preserve Editing still embeds the document with its live effects. WrittenLayers gains hidden_objects. SVG sets it with Hidden Layers on, since it then writes hidden objects too, so a hidden instance is written hidden with its effects applied. The other exporters leave it off. An SVG instance nested in another instance's art was shared through when the def allowed its own transform, while the writes that transform after the outer instances'. A stroked symbol nested in a scaled instance then drew its stroke at double weight. The check now uses the transform the writes. --- crates/cad/src/lib.rs | 4 +- crates/effects/src/bake.rs | 24 ++++---- crates/effects/src/bake/tests.rs | 14 ++++- crates/eps/src/lib.rs | 4 +- crates/metafile/src/lib.rs | 11 ++-- crates/metafile/src/tests/import.rs | 37 +++++++++++++ crates/pdf/src/export/entry.rs | 1 + crates/pdf/src/print.rs | 2 +- crates/svg/src/export.rs | 8 ++- crates/svg/src/export/nodes.rs | 7 ++- crates/svg/tests/it/symbols_layers.rs | 79 +++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 12 files changed, 167 insertions(+), 25 deletions(-) diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index bb752267aa..6ab16c61e3 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -429,8 +429,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result { return Err("the export region is not finite".into()); } // Symbols' art is placed without clipping, as the scene places it. - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); let doc = baked.as_ref().unwrap_or(doc); Ok(scene::Scene::new(doc, opts).run()) } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index d8f3ae0fe4..ec63c28707 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -162,7 +162,7 @@ struct Placing { layers: WrittenLayers, } -/// The layers an exporter writes besides the shown, printing ones +/// The layers and objects an exporter writes besides the shown, printing ones /// ([`bake_document_placing_symbols`]). Template layers are never written. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WrittenLayers { @@ -170,16 +170,19 @@ pub struct WrittenLayers { pub hidden: bool, /// Layers that do not print. pub non_printing: bool, + /// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden + /// layers). + pub hidden_objects: bool, } /// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`] -/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer +/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer /// that does not print when the export leaves those out ([`WrittenLayers`]). fn unwritten(n: &Node) -> bool { PLACING.with(|p| { p.borrow().as_ref().is_some_and(|p| match n.kind { NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden), - _ => !n.visible, + _ => !(n.visible || p.layers.hidden_objects), }) }) } @@ -1014,13 +1017,14 @@ pub fn bake_document(doc: &Document) -> Option { /// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or /// in the art of the symbols it places) replaced by that art as the instance places it, baked /// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For -/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than -/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped -/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the -/// exporter places other instances. `layers`: the hidden layers and layers that do not print -/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden -/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The -/// symbols' own art is left as it is. +/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and +/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`: +/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not +/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`: +/// the hidden layers, layers that do not print and hidden objects that the exporter writes. +/// Instances the export does not write (template layers, and the hidden objects and layers +/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as +/// it is. pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option { bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers))) } diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index fba4f75e5f..292d9461d6 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -1328,7 +1328,7 @@ fn placing_symbols_keeps_the_instances_stain() { } /// Every layer written, as DXF writes them (template layers are never written). -const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true }; +const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; fn is_instance(d: &Document, id: u64) -> bool { d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) @@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() { } // An export that writes the layers that do not print, or the hidden layers, places that // layer's instance first; the template layer's instance is never placed. - for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] { + for (layers, first) in + [(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)] + { let out = bake(&d, Some((true, each, layers))).unwrap(); assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}"); } + // An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance + // first, and the instance in the hidden group would come next; the hidden layer's instance + // stays, since that layer is still left out. + let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap(); + assert!(!is_instance(&out, 901), "the hidden instance is placed"); + for id in [900, 903, 911, 921, 931] { + assert!(is_instance(&out, id), "{id} stays as it is"); + } } /// `leaf` in `levels` groups, with ids from `id` up. diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index e36422b759..39737dae3a 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -232,8 +232,8 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb } // Type in the document's composite fonts is drawn in them, whether or not an app has the document open. let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, true, vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); let page = scene::Scene::new(doc, opts).run(); let mut setting_notes = vec![]; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 86d268cee1..61126ef228 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -74,15 +74,18 @@ pub struct Output { } /// Write the visible art of `doc` over `region` (document space: its top-left corner is the -/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first; -/// template layers, hidden objects and guides are left out. Raster effects should be turned into -/// images before (the engine does); the ones left are reported and left out. +/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first, +/// in symbols' art too, where each instance places that art (EMF clips 9-slice cells, WMF does +/// not); template layers, hidden objects and guides are left out. Raster effects should be turned +/// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result { let r = region.abs(); if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { return Err("the export region is empty".into()); } - let baked = vectorcraft_effects::bake_document(doc); + // The scene writes layers that do not print and leaves hidden layers and objects out. + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); let bytes = match kind { diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index f5870c5f95..622a800414 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -85,6 +85,43 @@ fn wmf_output_round_trips() { assert!(near(ellipse.geometric_bounds().unwrap(), Rect::new(100.0, 20.0, 180.0, 80.0), 0.1)); } +/// A symbol's square that a Transform effect moves 100 pt right is written where the canvas draws +/// it, in EMF and in WMF, read back: art whose own place is off the artboard is written where the +/// effect moves it onto it, and an instance that doubles the art's width places it first, so the +/// effect still moves it 100 pt (to x = 120, not 220). A stained instance keeps its stain. +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + let moved = |rect: Rect| { + let mut art = path(shapes::rectangle(rect), red(), Paint::None, 0.0); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: [("moveH", 100.0)].into_iter().collect(), + visible: true, + }); + art + }; + // The art's square, the instance's transform and fill, and the square and color it draws. + let cases = [ + (Rect::new(-90.0, 10.0, -80.0, 20.0), Affine::IDENTITY, None, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]), + (Rect::new(10.0, 30.0, 20.0, 40.0), Affine::scale_non_uniform(2.0, 1.0), Some(blue()), Rect::new(120.0, 30.0, 140.0, 40.0), [0, 0, 255]), + ]; + for (square, xf, stain, want, rgb) in cases { + let mut inst = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf }); + if let Some(p) = stain { + inst.appearance = vectorcraft_doc::Appearance::basic(p, Paint::None, 0.0).into(); + } + let mut d = doc_with(200.0, 100.0, vec![inst]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: std::sync::Arc::new(moved(square)) }); + for kind in [Kind::Emf, Kind::Wmf] { + let back = import(&export(&d, d.artboards[0].rect, kind).unwrap().bytes).unwrap(); + let drawn: Vec<(Option, Option<[u8; 3]>)> = paths(&back.document).iter().map(|n| (n.geometric_bounds(), fill_rgb(n))).collect(); + assert_eq!(drawn.len(), 1, "{kind:?} {xf:?}: {drawn:?}"); + assert!(drawn[0].0.is_some_and(|b| near(b, want, 0.1)), "{kind:?} {xf:?}: {drawn:?}"); + assert_eq!(drawn[0].1, Some(rgb), "{kind:?} {xf:?}"); + } + } +} + #[test] fn freeform_points_that_share_a_model_are_written_as_their_mix() { use vectorcraft_color::{Color, Freeform, FreeformPoint, GradientKind}; diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 00ac16a3fe..fcdcd01f63 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -57,6 +57,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let layers = vectorcraft_effects::WrittenLayers { hidden: set.writes_layers() && !doc.page_knockout, non_printing: set.include_non_printing || set.create_layers, + hidden_objects: false, }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); // Baking stops early when cancelled, leaving a half-baked copy that must not be written. diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 2a3cbf98af..54e85f44b4 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -187,7 +187,7 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D // the art that prints; the layers kept are shown. let mut kept = doc.clone(); keep_layers(&mut kept.layers, set.print_layers); - let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept); composite_overprints(&mut d, set); Cow::Owned(d) diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 05107bfb65..4c1f8f0ec2 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -38,7 +38,13 @@ const UNIQUE_PLACEHOLDER: &str = "u_vc_unique_-"; pub(crate) fn export(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>) -> Output { // Live geometry effects (Roughen, Warp, Offset Path, Effect → Pathfinder…) export as their result. - let baked = vectorcraft_effects::bake_document(doc); + // An instance of a symbol whose art has such effects is written as that art placed by the + // instance and then baked, as the canvas draws it; other symbols keep one `` def. + // Hidden layers and objects are written when the options keep them; layers that do not print + // always are. `native` (Preserve Editing) is the document as it is, with its live effects. + let hidden = opts.hidden_layers; + let layers = vectorcraft_effects::WrittenLayers { hidden, non_printing: true, hidden_objects: hidden }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); if opts.object_ids != ObjectIds::Unique { return write(doc, opts, native, ""); diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index ea1d5ab95b..b9af2a6c06 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1061,8 +1061,8 @@ impl Writer<'_> { (self.xf, self.instance_xf) = saved; return; } - if let Some(def) = self.symbol_use(sym, n, *xf) { - let m = self.xf * *xf; + let m = self.xf * *xf; + if let Some(def) = self.symbol_use(sym, n, m) { let tr = if m == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(m)) }; self.line(&format!("")); return; @@ -1103,7 +1103,8 @@ impl Writer<'_> { } } - /// The id of the `` def instance `inst` (transform `xf`) can ``, written on first + /// The id of the `` def instance `inst` can `` with transform `xf` (the ``'s + /// own: the instance's transform after those of the instances it sits in), written on first /// use. `None` when the instance needs its own copy of the art: stained by its fill, or moved /// by a transform under which the def would not look as the canvas paints it ([`Reuse`]). fn symbol_use(&mut self, sym: &vectorcraft_doc::Symbol, inst: &Node, xf: Affine) -> Option { diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 005a03e0fa..63b9136424 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -299,6 +299,85 @@ fn a_stained_instance_with_a_geometry_effect_keeps_its_stain() { } } +/// Symbol "Moved": a red square whose Transform effect moves it `dx` pt right. +fn add_moved_symbol(d: &mut Document, square: Rect, dx: f64) { + let mut art = Node::path(d.alloc_id(), shapes::rectangle(square), Appearance::basic(Paint::solid(Color::rgb8(255, 0, 0)), Paint::None, 0.0)); + art.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": dx}), visible: true }); + d.symbols.push(Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); +} + +/// Instances of a symbol whose art has a geometry effect are written as their art placed by the +/// instance and then baked, where the canvas draws it: moved by the instance, doubled in width +/// (the effect still moves it 100 pt, not 200 pt) and turned. They use no ``, while the +/// instances of a symbol without effects still share one. +#[test] +fn symbol_art_effects_are_written_where_the_canvas_draws_them() { + let mut d = symbol_doc(0.0, &[Affine::translate((30.0, 100.0)), Affine::translate((60.0, 100.0))]); + add_moved_symbol(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), 100.0); + instance(&mut d, "Moved", Affine::IDENTITY); + instance(&mut d, "Moved", Affine::translate((0.0, 20.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Moved", Affine::translate((-60.0, 40.0)) * Affine::rotate(0.5)); + let svg = export(&d, &ExportOptions::default()); + assert_eq!((svg.matches("