From 0e8dc3c0267ccff8b293de613bdae1c08579d420 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:27:56 -0800 Subject: [PATCH 001/138] Status bar: Copy, Cut and Image Trace count their notes and list them on hover After Copy or Cut writes its formats to the system clipboard, and after Image Trace's Make or Make and Expand, the status message names the first note and how many there are, and resting the pointer on it lists them all in order, as after a save or an export. Before, only the first note was shown and the rest were dropped. A Copy's or Cut's notes no longer replace a message shown while its formats were being made on the background worker; the formats are still written. Docs: docs/control-protocol.md, docs/mcp.md, docs/target-app-parity.md. --- crates/ui-egui/src/app/commands.rs | 36 +++++++--- crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tests.rs | 17 ++++- crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/character.rs | 13 ++-- crates/ui-egui/src/panels/character/tests.rs | 2 +- crates/ui-egui/src/sysclip.rs | 46 +++++++++++-- crates/ui-egui/src/tests/sysclip.rs | 72 ++++++++++++++++---- crates/ui-egui/src/tests/trace_runs.rs | 40 +++++++++++ crates/ui-egui/src/trace_runs.rs | 5 ++ docs/control-protocol.md | 3 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 38 files changed, 281 insertions(+), 39 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1d2493385e..f7726e396c 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -254,9 +254,7 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } - if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") { - self.publish_clipboard(); - } + let copied = r.is_ok() && self.publish_copy(id); self.sync_views(); self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. @@ -264,11 +262,8 @@ impl VectorcraftApp { match &r { Err(e) => self.ui.status = e.clone(), Ok(v) => { - // Image Trace's notes (a large image traces more slowly, or was scaled down). - if id.starts_with("imageTrace.make") - && let Some(w) = v["warnings"].as_array().and_then(|w| w.first()).and_then(Value::as_str) - { - self.ui.status = w.to_string(); + if matches!(id, "imageTrace.make" | "imageTrace.makeAndExpand") { + self.show_trace_notes(v); } if id == "file.new" { self.ui.status.clear(); @@ -312,9 +307,34 @@ impl VectorcraftApp { } } } + // The message the Copy or Cut leaves is the one its clipboard formats' notes may replace. + if copied { + self.clipboard_publishing.ran_with_status(&self.ui.status); + } r } + /// After a Copy or Cut `id` that ran: offer what it copied to other apps + /// ([`Self::publish_clipboard`]) → whether `id` is one. + fn publish_copy(&mut self, id: &str) -> bool { + let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut"); + if copy { + self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut")); + } + copy + } + + /// Image Trace's notes in `reply` (a large image traces more slowly, or was scaled down): the + /// first of them and how many there are, with the rest for the message's hover. Without notes + /// the status bar keeps its message. + fn show_trace_notes(&mut self, reply: &Value) { + let notes = io::notes_of(reply); + if let Some(first) = notes.first() { + let status = crate::trace_runs::traced_with_notes(notes.len(), first); + io::show_with_notes(self, status, notes); + } + } + fn set_command_warning(&mut self, id: &str, warning: &str) { self.ui.status = warning.to_string(); if id != "text.replaceFont" { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..5faea23c39 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4714,6 +4714,9 @@ axis Both И двете @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Изхвърлен е {n} възстановен документ|Изхвърлени са {n} възстановени документа @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Възстановен е {n} документ: запазете го, за да го съхраните|Възстановени са {n} документа: запазете ги, за да ги съхраните @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Отворено с {n} бележка: {first}|Отворено с {n} бележки: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Копирано с {n} бележка: {first}|Копирано с {n} бележки: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Изрязано с {n} бележка: {first}|Изрязано с {n} бележки: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Трасирано с {n} бележка: {first}|Трасирано с {n} бележки: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} е запазен с {n} бележка: {first}|{path} е запазен с {n} бележки: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вградено е {n} изображение; {missing} липсват: първо ги свържете наново|Вградени са {n} изображения; {missing} липсват: първо ги свържете наново @msgplural Embedded {n} image|Embedded {n} images Вградено е {n} изображение|Вградени са {n} изображения diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..69d1c18c03 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5119,6 +5119,9 @@ imageTrace Outline Obris @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Odbačen {n} oporavljeni dokument|Odbačena {n} oporavljena dokumenta|Odbačeno {n} oporavljenih dokumenata @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Vraćen {n} oporavljeni dokument; sačuvajte ga da ga zadržite|Vraćena {n} oporavljena dokumenta; sačuvajte ih da ih zadržite|Vraćeno {n} oporavljenih dokumenata; sačuvajte ih da ih zadržite @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otvoreno s {n} bilješkom: {first}|Otvoreno s {n} bilješke: {first}|Otvoreno s {n} bilješki: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopirano s {n} bilješkom: {first}|Kopirano s {n} bilješke: {first}|Kopirano s {n} bilješki: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Izrezano s {n} bilješkom: {first}|Izrezano s {n} bilješke: {first}|Izrezano s {n} bilješki: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Slika praćena s {n} bilješkom: {first}|Slika praćena s {n} bilješke: {first}|Slika praćena s {n} bilješki: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Sačuvano {path} s {n} bilješkom: {first}|Sačuvano {path} s {n} bilješke: {first}|Sačuvano {path} s {n} bilješki: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ugrađena je {n} slika; nedostaje {missing}: prvo ih ponovo povežite|Ugrađene su {n} slike; nedostaje {missing}: prvo ih ponovo povežite|Ugrađeno je {n} slika; nedostaje {missing}: prvo ih ponovo povežite @msgplural Embedded {n} image|Embedded {n} images Ugrađena je {n} slika|Ugrađene su {n} slike|Ugrađeno je {n} slika diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..019821f9cf 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5955,6 +5955,9 @@ digits Malayalam Malaiàlam @msg Saved to User Defined: {_1} Desat a User Defined: {_1} @msg Saved {n} files beside {path} S’han desat {n} fitxers al costat de {path} @msg Saved {path} Desat {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} S’ha copiat amb {n} nota: {first}|S’ha copiat amb {n} notes: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} S’ha retallat amb {n} nota: {first}|S’ha retallat amb {n} notes: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} S’ha traçat la imatge amb {n} nota: {first}|S’ha traçat la imatge amb {n} notes: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} S’ha desat {path} amb {n} nota: {first}|S’ha desat {path} amb {n} notes: {first} @msg Saving S’està desant @msg Saving recovery data for {_1} S’estan desant les dades de recuperació de {_1} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..17238a6696 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5308,6 +5308,9 @@ imageTrace Outline Obrys @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Zahozen {n} obnovený dokument|Zahozeny {n} obnovené dokumenty|Zahozeno {n} obnovených dokumentů @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Obnoven {n} dokument; pokud ho chcete zachovat, uložte ho|Obnoveny {n} dokumenty; pokud je chcete zachovat, uložte je|Obnoveno {n} dokumentů; pokud je chcete zachovat, uložte je @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otevřeno, {n} poznámka: {first}|Otevřeno, {n} poznámky: {first}|Otevřeno, {n} poznámek: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Zkopírováno, {n} poznámka: {first}|Zkopírováno, {n} poznámky: {first}|Zkopírováno, {n} poznámek: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Vyjmuto, {n} poznámka: {first}|Vyjmuto, {n} poznámky: {first}|Vyjmuto, {n} poznámek: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Obraz vektorizován, {n} poznámka: {first}|Obraz vektorizován, {n} poznámky: {first}|Obraz vektorizován, {n} poznámek: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Uloženo: {path}, {n} poznámka: {first}|Uloženo: {path}, {n} poznámky: {first}|Uloženo: {path}, {n} poznámek: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Vložen {n} obrázek; chybí {missing}: nejprve je znovu propojte|Vloženy {n} obrázky; chybí {missing}: nejprve je znovu propojte|Vloženo {n} obrázků; chybí {missing}: nejprve je znovu propojte @msgplural Embedded {n} image|Embedded {n} images Vložen {n} obrázek|Vloženy {n} obrázky|Vloženo {n} obrázků diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..819388e4da 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4804,6 +4804,9 @@ imageTrace Outline Kontur @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kasserede {n} gendannet dokument|Kasserede {n} gendannede dokumenter @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Gendannede {n} dokument: gem det for at beholde det|Gendannede {n} dokumenter: gem dem for at beholde dem @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Åbnede med {n} note: {first}|Åbnede med {n} noter: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopierede med {n} note: {first}|Kopierede med {n} noter: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Klippede med {n} note: {first}|Klippede med {n} noter: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Sporede billedet med {n} note: {first}|Sporede billedet med {n} noter: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Gemte {path} med {n} note: {first}|Gemte {path} med {n} noter: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Indlejrede {n} billede; {missing} mangler: link dem igen først|Indlejrede {n} billeder; {missing} mangler: link dem igen først @msgplural Embedded {n} image|Embedded {n} images Indlejrede {n} billede|Indlejrede {n} billeder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..01a9ccf652 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4925,6 +4925,9 @@ theme Appearance Erscheinungsbild @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} wiederhergestelltes Dokument verworfen|{n} wiederhergestellte Dokumente verworfen @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} wiederhergestelltes Dokument geöffnet: Speichern Sie es, um es zu behalten|{n} wiederhergestellte Dokumente geöffnet: Speichern Sie sie, um sie zu behalten @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Mit {n} Hinweis geöffnet: {first}|Mit {n} Hinweisen geöffnet: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Mit {n} Hinweis kopiert: {first}|Mit {n} Hinweisen kopiert: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Mit {n} Hinweis ausgeschnitten: {first}|Mit {n} Hinweisen ausgeschnitten: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Mit {n} Hinweis nachgezeichnet: {first}|Mit {n} Hinweisen nachgezeichnet: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} mit {n} Hinweis gespeichert: {first}|{path} mit {n} Hinweisen gespeichert: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} Bild eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu|{n} Bilder eingebettet; {missing} fehlen: Verknüpfen Sie sie zuerst neu @msgplural Embedded {n} image|Embedded {n} images {n} Bild eingebettet|{n} Bilder eingebettet diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..ebec15c3ed 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4947,6 +4947,9 @@ digits Malayalam Μαλαγιάλαμ @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Απορρίφθηκε {n} ανακτημένο έγγραφο|Απορρίφθηκαν {n} ανακτημένα έγγραφα @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Επαναφέρθηκε {n} ανακτημένο έγγραφο: αποθηκεύστε το για να διατηρηθεί|Επαναφέρθηκαν {n} ανακτημένα έγγραφα: αποθηκεύστε τα για να διατηρηθούν @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Άνοιξε με {n} σημείωση: {first}|Άνοιξε με {n} σημειώσεις: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Αντιγράφηκε με {n} σημείωση: {first}|Αντιγράφηκε με {n} σημειώσεις: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Αποκόπηκε με {n} σημείωση: {first}|Αποκόπηκε με {n} σημειώσεις: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Η εικόνα ανιχνεύτηκε με {n} σημείωση: {first}|Η εικόνα ανιχνεύτηκε με {n} σημειώσεις: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Αποθηκεύτηκε το {path} με {n} σημείωση: {first}|Αποθηκεύτηκε το {path} με {n} σημειώσεις: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Ενσωματώθηκε {n} εικόνα· λείπουν {missing}: επανασυνδέστε τις πρώτα|Ενσωματώθηκαν {n} εικόνες· λείπουν {missing}: επανασυνδέστε τις πρώτα @msgplural Embedded {n} image|Embedded {n} images Ενσωματώθηκε {n} εικόνα|Ενσωματώθηκαν {n} εικόνες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..0f1fd696e0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5000,6 +5000,9 @@ axis Both Ambos @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Se descartó {n} documento recuperado|Se descartaron {n} documentos recuperados @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Se restauró {n} documento recuperado: guárdalo para conservarlo|Se restauraron {n} documentos recuperados: guárdalos para conservarlos @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Se abrió con {n} nota: {first}|Se abrió con {n} notas: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Se copió con {n} nota: {first}|Se copió con {n} notas: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Se cortó con {n} nota: {first}|Se cortó con {n} notas: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Se calcó la imagen con {n} nota: {first}|Se calcó la imagen con {n} notas: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Se guardó {path} con {n} nota: {first}|Se guardó {path} con {n} notas: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Se incrustó {n} imagen; faltan {missing}: vuelve a vincularlas primero|Se incrustaron {n} imágenes; faltan {missing}: vuelve a vincularlas primero @msgplural Embedded {n} image|Embedded {n} images Se incrustó {n} imagen|Se incrustaron {n} imágenes diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..a85a96c520 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5208,6 +5208,9 @@ imageTrace Outline Ääriviiva @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Hylättiin {n} palautettu asiakirja|Hylättiin {n} palautettua asiakirjaa @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Palautettiin {n} asiakirja: tallenna se säilyttääksesi sen|Palautettiin {n} asiakirjaa: tallenna ne säilyttääksesi ne @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Avattiin, {n} huomautus: {first}|Avattiin, {n} huomautusta: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopioitiin, {n} huomautus: {first}|Kopioitiin, {n} huomautusta: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Leikattiin, {n} huomautus: {first}|Leikattiin, {n} huomautusta: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kuva jäljitettiin, {n} huomautus: {first}|Kuva jäljitettiin, {n} huomautusta: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Tallennettiin {path}, {n} huomautus: {first}|Tallennettiin {path}, {n} huomautusta: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Upotettiin {n} kuva; {missing} puuttuu: linkitä ne ensin uudelleen|Upotettiin {n} kuvaa; {missing} puuttuu: linkitä ne ensin uudelleen @msgplural Embedded {n} image|Embedded {n} images Upotettiin {n} kuva|Upotettiin {n} kuvaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..d3b68af3f2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4987,6 +4987,9 @@ axis Both Les deux @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} document récupéré supprimé|{n} documents récupérés supprimés @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} document récupéré restauré : enregistrez-le pour le conserver|{n} documents récupérés restaurés : enregistrez-les pour les conserver @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Ouvert avec {n} remarque : {first}|Ouvert avec {n} remarques : {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copié avec {n} remarque : {first}|Copié avec {n} remarques : {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Coupé avec {n} remarque : {first}|Coupé avec {n} remarques : {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Image vectorisée avec {n} remarque : {first}|Image vectorisée avec {n} remarques : {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} enregistré avec {n} remarque : {first}|{path} enregistré avec {n} remarques : {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} image incorporée ; il en manque {missing} : rétablissez d’abord leurs liens|{n} images incorporées ; il en manque {missing} : rétablissez d’abord leurs liens @msgplural Embedded {n} image|Embedded {n} images {n} image incorporée|{n} images incorporées diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..65c39ed997 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8491,6 +8491,9 @@ antiAlias Sharp शार्प @msgplural Relinked {n} image|Relinked {n} images {n} इमेज दोबारा लिंक हुई|{n} इमेज दोबारा लिंक हुईं @msgplural Replaced {n} image|Replaced {n} images {n} इमेज बदली गई|{n} इमेज बदली गईं @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} रिकवर किया डॉक्यूमेंट बहाल हुआ: रखने के लिए उसे सेव करें|{n} रिकवर किए डॉक्यूमेंट बहाल हुए: रखने के लिए उन्हें सेव करें +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} कॉपी किया गया, {n} नोट के साथ: {first}|कॉपी किया गया, {n} नोट्स के साथ: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} काटा गया, {n} नोट के साथ: {first}|काटा गया, {n} नोट्स के साथ: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} इमेज ट्रेस किया गया, {n} नोट के साथ: {first}|इमेज ट्रेस किया गया, {n} नोट्स के साथ: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} सेव किया गया, {n} नोट के साथ: {first}|{path} सेव किया गया, {n} नोट्स के साथ: {first} @msgplural Selected {n} embedded image|Selected {n} embedded images {n} एम्बेड की गई इमेज सिलेक्टेड|{n} एम्बेड की गई इमेज सिलेक्टेड @msgplural Selected {n} image|Selected {n} images {n} इमेज सिलेक्टेड|{n} इमेज सिलेक्टेड diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..9bb1441ddc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5519,6 +5519,9 @@ imageTrace Outline Körvonal @msg Saved to User Defined: {_1} Mentve a felhasználóiak közé: {_1} @msg Saved {n} files beside {path} Mentett fájlok: {n}, a következő mellett: {path} @msg Saved {path} Mentve: {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Másolva; megjegyzések: {n}, az első: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Kivágva; megjegyzések: {n}, az első: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kép vektorizálva; megjegyzések: {n}, az első: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Mentve: {path}; megjegyzések: {n}, az első: {first} @msg Saving Mentés @msg Saving recovery data for {_1} Helyreállítási adatok mentése: {_1} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..2f6653eddd 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4804,6 +4804,9 @@ imageTrace Outline Kontur @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} dokumen hasil pemulihan dibuang @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} dokumen hasil pemulihan dipulihkan: simpan agar tidak hilang @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Dibuka dengan {n} catatan: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Disalin dengan {n} catatan: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Dipotong dengan {n} catatan: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Gambar dilacak dengan {n} catatan: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} disimpan dengan {n} catatan: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} gambar tersemat; {missing} hilang: tautkan ulang dulu @msgplural Embedded {n} image|Embedded {n} images {n} gambar tersemat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..3ee1d9e3e6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5051,6 +5051,9 @@ axis Both Entrambi @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Scartato {n} documento recuperato|Scartati {n} documenti recuperati @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Ripristinato {n} documento recuperato. Salvalo per conservarlo|Ripristinati {n} documenti recuperati. Salvali per conservarli @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Aperto con {n} nota: {first}|Aperto con {n} note: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copiato con {n} nota: {first}|Copiato con {n} note: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Tagliato con {n} nota: {first}|Tagliato con {n} note: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Immagine ricalcata con {n} nota: {first}|Immagine ricalcata con {n} note: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Salvato {path} con {n} nota: {first}|Salvato {path} con {n} note: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Incorporata {n} immagine; mancanti: {missing} (ricollegale prima)|Incorporate {n} immagini; mancanti: {missing} (ricollegale prima) @msgplural Embedded {n} image|Embedded {n} images Incorporata {n} immagine|Incorporate {n} immagini diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..b74e8ad14c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5168,6 +5168,9 @@ swatch Bright Violet ビビッドバイオレット @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 復帰用データのドキュメントを {n} 件破棄しました @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 復帰用データからドキュメントを {n} 件復元しました: 残すには保存してください @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} ドキュメントを開きました (注意 {n} 件): {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} コピーしましたが、注意事項が {n} 件あります: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 切り取りましたが、注意事項が {n} 件あります: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 画像をトレースしましたが、注意事項が {n} 件あります: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} を保存しましたが、注意事項が {n} 件あります: {first} @msg Saving recovery data for {_1} {_1} の復帰用データを保存中 @msg This shortcut file is in a form VectorCraft can't read. このショートカットファイルは VectorCraft で読み込めない形式です。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..07a171905e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4653,6 +4653,9 @@ font-technology Variable ცვლადი @msgplural Discarded {n} recovered document|Discarded {n} recovered documents უარყოფილია აღდგენილი დოკუმენტები: {n} @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them აღდგენილია დოკუმენტები: {n}: შესანარჩუნებლად შეინახეთ ისინი @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} გაიხსნა, შენიშვნები: {n}: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} კოპირებულია, შენიშვნები: {n}: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} ამოჭრილია, შენიშვნები: {n}: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} გამოსახულება ვექტორიზებულია, შენიშვნები: {n}: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} შენახულია {path}, შენიშვნები: {n}: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first ჩაშენებულია გამოსახულებები: {n}; აკლია {missing}: ჯერ ხელახლა მიაბით @msgplural Embedded {n} image|Embedded {n} images ჩაშენებულია გამოსახულებები: {n} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..16c39178c3 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5095,6 +5095,9 @@ theme Appearance 외관 @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 복구된 문서 {n}개를 삭제했습니다 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 복구된 문서 {n}개를 복원했습니다: 보관하려면 저장하세요 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 참고 {n}건과 함께 열었습니다: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 참고 {n}건과 함께 복사했습니다: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 참고 {n}건과 함께 잘라냈습니다: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 참고 {n}건과 함께 이미지를 추적했습니다: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 참고 {n}건과 함께 {path}을(를) 저장했습니다: {first} @msg Saving recovery data for {_1} {_1}의 복구 데이터를 저장하는 중 @msg bad shortcut 잘못된 단축키 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..d8f89db400 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4816,6 +4816,9 @@ imageTrace Outline Contour @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} hersteld document verworpen|{n} herstelde documenten verworpen @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} hersteld document teruggezet: sla het op om het te behouden|{n} herstelde documenten teruggezet: sla ze op om ze te behouden @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Geopend met {n} opmerking: {first}|Geopend met {n} opmerkingen: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Gekopieerd met {n} opmerking: {first}|Gekopieerd met {n} opmerkingen: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Geknipt met {n} opmerking: {first}|Geknipt met {n} opmerkingen: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Afbeelding getraceerd met {n} opmerking: {first}|Afbeelding getraceerd met {n} opmerkingen: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} opgeslagen met {n} opmerking: {first}|{path} opgeslagen met {n} opmerkingen: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} afbeelding ingesloten; {missing} ontbreken: koppel ze eerst opnieuw|{n} afbeeldingen ingesloten; {missing} ontbreken: koppel ze eerst opnieuw @msgplural Embedded {n} image|Embedded {n} images {n} afbeelding ingesloten|{n} afbeeldingen ingesloten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..eaa51fe15c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5134,6 +5134,9 @@ imageTrace Outline Kontur @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Odrzucono {n} odzyskany dokument|Odrzucono {n} odzyskane dokumenty|Odrzucono {n} odzyskanych dokumentów @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Przywrócono {n} odzyskany dokument: zapisz go, aby go zachować|Przywrócono {n} odzyskane dokumenty: zapisz je, aby je zachować|Przywrócono {n} odzyskanych dokumentów: zapisz je, aby je zachować @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Otwarto z {n} uwagą: {first}|Otwarto z {n} uwagami: {first}|Otwarto z {n} uwagami: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Skopiowano z {n} uwagą: {first}|Skopiowano z {n} uwagami: {first}|Skopiowano z {n} uwagami: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Wycięto z {n} uwagą: {first}|Wycięto z {n} uwagami: {first}|Wycięto z {n} uwagami: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Obrysowano obraz z {n} uwagą: {first}|Obrysowano obraz z {n} uwagami: {first}|Obrysowano obraz z {n} uwagami: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Zapisano {path} z {n} uwagą: {first}|Zapisano {path} z {n} uwagami: {first}|Zapisano {path} z {n} uwagami: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Osadzono {n} obraz; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazy; brakuje {missing}: najpierw połącz je ponownie|Osadzono {n} obrazów; brakuje {missing}: najpierw połącz je ponownie @msgplural Embedded {n} image|Embedded {n} images Osadzono {n} obraz|Osadzono {n} obrazy|Osadzono {n} obrazów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..8bb19e00fa 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4455,6 +4455,9 @@ axis Both Ambos @msgplural Discarded {n} recovered document|Discarded {n} recovered documents {n} documento recuperado descartado|{n} documentos recuperados descartados @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them {n} documento recuperado restaurado: salve-o para mantê-lo|{n} documentos recuperados restaurados: salve-os para mantê-los @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Aberto com {n} observação: {first}|Aberto com {n} observações: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Copiado com {n} observação: {first}|Copiado com {n} observações: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Recortado com {n} observação: {first}|Recortado com {n} observações: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Imagem rastreada com {n} observação: {first}|Imagem rastreada com {n} observações: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path} salvo com {n} observação: {first}|{path} salvo com {n} observações: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} imagem incorporada; faltam {missing}: revincule-as primeiro|{n} imagens incorporadas; faltam {missing}: revincule-as primeiro @msgplural Embedded {n} image|Embedded {n} images {n} imagem incorporada|{n} imagens incorporadas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..ed76793c3e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5037,6 +5037,9 @@ axis Both Оба @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Отменён {n} восстановленный документ|Отменено {n} восстановленных документа|Отменено {n} восстановленных документов @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Восстановлен {n} документ: сохраните его, чтобы оставить|Восстановлено {n} документа: сохраните их, чтобы оставить|Восстановлено {n} документов: сохраните их, чтобы оставить @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Открыто с {n} примечанием: {first}|Открыто с {n} примечаниями: {first}|Открыто с {n} примечаниями: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Скопировано с {n} примечанием: {first}|Скопировано с {n} примечаниями: {first}|Скопировано с {n} примечаниями: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Вырезано с {n} примечанием: {first}|Вырезано с {n} примечаниями: {first}|Вырезано с {n} примечаниями: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Изображение трассировано с {n} примечанием: {first}|Изображение трассировано с {n} примечаниями: {first}|Изображение трассировано с {n} примечаниями: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Сохранено: {path} с {n} примечанием: {first}|Сохранено: {path} с {n} примечаниями: {first}|Сохранено: {path} с {n} примечаниями: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Внедрено {n} изображение; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображения; отсутствует {missing}: сначала восстановите связи|Внедрено {n} изображений; отсутствует {missing}: сначала восстановите связи @msgplural Embedded {n} image|Embedded {n} images Внедрено {n} изображение|Внедрено {n} изображения|Внедрено {n} изображений diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..8f46aa32c2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4895,6 +4895,9 @@ axis Both Båda @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kastade {n} återställt dokument|Kastade {n} återställda dokument @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Återställde {n} återskapat dokument: spara det för att behålla det|Återställde {n} återskapade dokument: spara dem för att behålla dem @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Öppnad med {n} anteckning: {first}|Öppnad med {n} anteckningar: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Kopierade med {n} anteckning: {first}|Kopierade med {n} anteckningar: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Klippte ut med {n} anteckning: {first}|Klippte ut med {n} anteckningar: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Kalkerade bilden med {n} anteckning: {first}|Kalkerade bilden med {n} anteckningar: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Sparade {path} med {n} anteckning: {first}|Sparade {path} med {n} anteckningar: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Bäddade in {n} bild; {missing} saknas: länka om dem först|Bäddade in {n} bilder; {missing} saknas: länka om dem först @msgplural Embedded {n} image|Embedded {n} images Bäddade in {n} bild|Bäddade in {n} bilder diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..c6767bafdc 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2153,19 +2153,32 @@ const COUNTED_STATUS_MESSAGES: &[(&str, &str)] = &[ ("Downloaded 1 file", "Downloaded 2 files"), ("Exported 1 file to /out", "Exported 2 files to /out"), ("Loaded “Tidy”: 1 step was left out", "Loaded “Tidy”: 2 steps were left out"), + ("Copied with 1 note: a note", "Copied with 2 notes: a note"), + ("Cut with 1 note: a note", "Cut with 2 notes: a note"), + ("Traced with 1 note: a note", "Traced with 2 notes: a note"), ]; -/// The link, font, export and action set status messages name a count of 1 in the singular and other counts in -/// the plural, and every complete catalog translates both, in the form its plural rule picks. +/// The link, font, export, action set, clipboard and Image Trace status messages name a count of 1 in the singular +/// and other counts in the plural, and every complete catalog translates both, in the form its plural rule picks. #[test] fn counted_status_messages_take_the_plural_form() { use crate::panels::links::{relinked_status, updated_status}; + use crate::sysclip::copied_with_notes; + use crate::trace_runs::traced_with_notes; assert_eq!((relinked_status(1), relinked_status(2)), ("Relinked 1 image".to_string(), "Relinked 2 images".to_string())); assert_eq!((updated_status(1), updated_status(2)), ("Updated 1 image".to_string(), "Updated 2 images".to_string())); assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(1), COUNTED_STATUS_MESSAGES[2].0); assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(2), COUNTED_STATUS_MESSAGES[2].1); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 1, "a note"), COUNTED_STATUS_MESSAGES[4].0); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 2, "a note"), COUNTED_STATUS_MESSAGES[4].1); + let n = COUNTED_STATUS_MESSAGES.len(); + let owned = |(one, other): (&str, &str)| (one.to_string(), other.to_string()); + assert_eq!((copied_with_notes(false, 1, "a note"), copied_with_notes(false, 2, "a note")), owned(COUNTED_STATUS_MESSAGES[n - 3])); + assert_eq!((copied_with_notes(true, 1, "a note"), copied_with_notes(true, 2, "a note")), owned(COUNTED_STATUS_MESSAGES[n - 2])); + assert_eq!((traced_with_notes(1, "a note"), traced_with_notes(2, "a note")), owned(COUNTED_STATUS_MESSAGES[n - 1])); + // A note that holds placeholder text is not filled in again. + assert_eq!(copied_with_notes(true, 3, "{n} {first}"), "Cut with 3 notes: {n} {first}"); + assert_eq!(message(de(), &traced_with_notes(2, "{n}")), "Mit 2 Hinweisen nachgezeichnet: {n}"); // A value that holds placeholder text is not filled in again. assert_eq!(crate::io::exported_with_notes("/out/{first}.svg", 1, "{n}"), "Exported /out/{first}.svg with 1 note: {n}"); for code in COMPLETE_MESSAGES { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..35260348e6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4733,6 +4733,9 @@ axis Both Her İkisi @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Kurtarılan {n} belge atıldı @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Kurtarılan {n} belge geri yüklendi: saklamak için kaydedin @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} {n} notla açıldı: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} {n} notla kopyalandı: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} {n} notla kesildi: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Görüntü {n} notla izlendi: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} {path}, {n} notla kaydedildi: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first {n} görsel gömüldü; {missing} eksik: önce onları yeniden bağlayın @msgplural Embedded {n} image|Embedded {n} images {n} görsel gömüldü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..3ec176de4f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5035,6 +5035,9 @@ axis Both Обидві @msgplural Discarded {n} recovered document|Discarded {n} recovered documents Скасовано {n} відновлений документ|Скасовано {n} відновлені документи|Скасовано {n} відновлених документів @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them Відновлено {n} документ: збережіть його, щоб залишити|Відновлено {n} документи: збережіть їх, щоб залишити|Відновлено {n} документів: збережіть їх, щоб залишити @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} Відкрито з {n} приміткою: {first}|Відкрито з {n} примітками: {first}|Відкрито з {n} примітками: {first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Скопійовано з {n} приміткою: {first}|Скопійовано з {n} примітками: {first}|Скопійовано з {n} примітками: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Вирізано з {n} приміткою: {first}|Вирізано з {n} примітками: {first}|Вирізано з {n} примітками: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Зображення трасовано з {n} приміткою: {first}|Зображення трасовано з {n} примітками: {first}|Зображення трасовано з {n} примітками: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Збережено: {path} з {n} приміткою: {first}|Збережено: {path} з {n} примітками: {first}|Збережено: {path} з {n} примітками: {first} @msgplural Embedded {n} image; {missing} missing: relink them first|Embedded {n} images; {missing} missing: relink them first Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображення; відсутніх: {missing}. Спочатку відновіть їхні зв’язки|Вбудовано {n} зображень; відсутніх: {missing}. Спочатку відновіть їхні зв’язки @msgplural Embedded {n} image|Embedded {n} images Вбудовано {n} зображення|Вбудовано {n} зображення|Вбудовано {n} зображень diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..596ce945a5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5182,6 +5182,9 @@ theme Appearance Giao diện @msg Saved to User Defined: {_1} Đã lưu vào Người dùng tùy chỉnh: {_1} @msg Saved {n} files beside {path} Đã lưu {n} tệp bên cạnh {path} @msg Saved {path} Đã lưu {path} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} Đã sao chép với {n} ghi chú: {first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} Đã cắt với {n} ghi chú: {first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} Đã vector hóa ảnh với {n} ghi chú: {first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} Đã lưu {path} với {n} ghi chú: {first} @msg Saving Đang lưu @msg Saving recovery data for {_1} Đang lưu dữ liệu phục hồi cho {_1} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..51839e55f9 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4856,6 +4856,9 @@ imageTrace Outline 轮廓 @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 已丢弃 {n} 个恢复的文档 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 已还原 {n} 个恢复的文档:请保存以保留它们 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 已打开,有 {n} 条注释:{first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 已复制,有 {n} 条注释:{first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 已剪切,有 {n} 条注释:{first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 已描摹图像,有 {n} 条注释:{first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 已保存 {path},有 {n} 条注释:{first} @msg Saving recovery data for {_1} 正在保存 {_1} 的恢复数据 @msg This shortcut file is in a form VectorCraft can't read. 此快捷键文件的格式 VectorCraft 无法读取。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..a1543bb69c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2623,6 +2623,9 @@ file-filter Templates 範本 @msgplural Discarded {n} recovered document|Discarded {n} recovered documents 已捨棄 {n} 份復原的文件 @msgplural Restored {n} recovered document: save it to keep it|Restored {n} recovered documents: save them to keep them 已還原 {n} 份復原的文件:請儲存以保留 @msgplural Opened with {n} note: {first}|Opened with {n} notes: {first} 已開啟,附有 {n} 則註解:{first} +@msgplural Copied with {n} note: {first}|Copied with {n} notes: {first} 已複製,附有 {n} 則註解:{first} +@msgplural Cut with {n} note: {first}|Cut with {n} notes: {first} 已剪下,附有 {n} 則註解:{first} +@msgplural Traced with {n} note: {first}|Traced with {n} notes: {first} 已描圖影像,附有 {n} 則註解:{first} @msgplural Saved {path} with {n} note: {first}|Saved {path} with {n} notes: {first} 已儲存 {path},附有 {n} 則註解:{first} @msg Saving recovery data for {_1} 正在儲存 {_1} 的復原資料 @msg This shortcut file is in a form VectorCraft can't read. VectorCraft 無法讀取此快速鍵檔案的格式。 diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 2ad678bf62..b8309ca2fb 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -545,7 +545,8 @@ static CTX: OnceLock = OnceLock::new(); static CLIP: Mutex = Mutex::new(String::new()); static CLIP_RUNS: Mutex> = Mutex::new(None); -fn text_copy(app: &mut VectorcraftApp) -> bool { +/// Copy the Type tool's selected text (with `cut`, for a Cut, whose caller then deletes it). +fn text_copy(app: &mut VectorcraftApp, cut: bool) -> bool { let Some((id, a, b)) = text_editing(app) else { return false }; let story = text_story(app); // An empty selection has nothing to copy, unless the story's text is in the other frames. @@ -573,7 +574,7 @@ fn text_copy(app: &mut VectorcraftApp) -> bool { // plain-text copy would replace its formats, so let the publisher provide both text and // rich art. Paste on the canvas can then keep the runs after Type editing ends. if app.services.system_clipboard.is_some() { - app.publish_clipboard(); + app.publish_clipboard(cut); return true; } } @@ -644,10 +645,10 @@ pub(crate) fn intercept_text_command(app: &mut VectorcraftApp, id: &str) -> Opti } match id { "edit.copy" => { - text_copy(app); + text_copy(app, false); } "edit.cut" => { - if text_copy(app) { + if text_copy(app, true) { text_key(app, ToolKey::Delete, Mods::default()); } } @@ -738,10 +739,10 @@ pub(crate) fn apply_type_input(app: &mut VectorcraftApp, t: TextInput) { match t { TextInput::Key(k, m) => text_key(app, k, m), TextInput::Copy => { - text_copy(app); + text_copy(app, false); } TextInput::Cut => { - if text_copy(app) { + if text_copy(app, true) { text_key(app, ToolKey::Delete, Mods::default()); } } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index a90286e2fb..1251ba6ef7 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -1427,7 +1427,7 @@ fn copy_and_cut_take_a_story_that_left_the_edited_frame() { // A story that holds no text has nothing to copy, so Cut does not run its delete. app.run("select.all", json!({})).unwrap(); assert_eq!(text_story(&app).map(|frames| frames.len()), Some(3)); - assert!(!text_copy(&mut app)); + assert!(!text_copy(&mut app, false)); } } } diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index ac382547de..722c602d72 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -97,6 +97,9 @@ pub(crate) struct Publishing { /// The latest one's formats could not be written: what the system clipboard held when the /// write failed, and the text of those formats. unwritten: Option<(Held, String)>, + /// The status bar's message when the latest one ran. Its formats' notes replace the message + /// only while the status bar still shows it. + status: String, } impl Publishing { @@ -110,6 +113,32 @@ impl Publishing { pub(crate) fn latest(&self) -> u64 { self.latest.load(Ordering::SeqCst) } + + /// `status` is the status bar's message the latest Copy or Cut left, which its formats' notes + /// may replace. + pub(crate) fn ran_with_status(&mut self, status: &str) { + status.clone_into(&mut self.status); + } +} + +/// The status bar's line after a Copy (or with `cut`, a Cut) whose formats have `n` notes, the +/// first of them `first`. +pub(crate) fn copied_with_notes(cut: bool, n: usize, first: &str) -> String { + let (one, other) = if cut { + ("Cut with {n} note: {first}", "Cut with {n} notes: {first}") + } else { + ("Copied with {n} note: {first}", "Copied with {n} notes: {first}") + }; + crate::i18n::msg_n(n as u64, one, other, &[("first", first)]) +} + +/// Show a Copy's (or with `cut`, a Cut's) formats' `notes` in the status bar: the first of them +/// and how many there are, with the rest for the message's hover. Without notes the status bar +/// keeps its message. +pub(crate) fn show_copy_notes(app: &mut VectorcraftApp, cut: bool, notes: Vec) { + let Some(first) = notes.first() else { return }; + let status = copied_with_notes(cut, notes.len(), first); + crate::io::show_with_notes(app, status, notes); } /// Does a flavour of type `mime` load with `clipboard.importImage` ([`import_command`])? @@ -166,9 +195,11 @@ impl VectorcraftApp { /// ([`Self::drop_formats_after_egui_copy`]), drops the formats not written yet. While the /// latest Copy or Cut's formats wait to be written, Paste takes the internal clipboard, and /// while a text field or type has the keyboard the app waits for them - /// ([`Self::write_formats_before_text_input`]). Once they are written, the status bar shows - /// the first of the PNG's and PDF's warnings. - pub(crate) fn publish_clipboard(&mut self) { + /// ([`Self::write_formats_before_text_input`]). Once they are written, while the status bar + /// still shows the message the Copy or Cut (`cut`) left ([`Publishing::ran_with_status`]), it + /// shows the first of the PNG's and PDF's notes and how many there are; hovering the message + /// lists them ([`crate::io::show_with_notes`]). + pub(crate) fn publish_clipboard(&mut self, cut: bool) { // Ruler guides copied alone stay in VectorCraft, but the Copy still replaces what the // system clipboard held: it is emptied, so the next Paste takes the guides rather than // what another app copied before, and what another app copies after still wins (#3226). @@ -188,6 +219,7 @@ impl VectorcraftApp { let n = latest.fetch_add(1, Ordering::SeqCst).wrapping_add(1); self.clipboard_publishing.pending = true; self.clipboard_publishing.unwritten = None; + self.clipboard_publishing.ran_with_status(&self.ui.status); // What the clipboard holds at the Copy or Cut: a copy made elsewhere before the write is newer. let before = self.services.system_clipboard.as_deref_mut().map(Held::now); let (tx, made) = channel(); @@ -236,11 +268,11 @@ impl VectorcraftApp { }); match written { Err(e) => app.ui.status = format!("Couldn't copy to the system clipboard: {e}"), - // Show the first of the PNG's and PDF's warnings (an image that couldn't be decoded, - // type in the fallback font). + // The PNG's and PDF's notes (an image that couldn't be decoded, type in the + // fallback font), unless another message has replaced the Copy or Cut's since. Ok(warnings) => { - if let Some(first) = warnings.into_iter().next() { - app.ui.status = first; + if app.ui.status == app.clipboard_publishing.status { + show_copy_notes(app, cut, warnings); } } } diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 1da5b93322..0efb576fd9 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -378,31 +378,77 @@ fn a_copy_while_the_worker_saves_writes_the_formats_at_once() { assert_eq!(board.borrow().writes, 1); } -/// Copy of an image the renderer can't decode: the PNG leaves it out, and once the formats are -/// written the status bar shows the PNG's note, made at once or on the worker. -#[test] -fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { - const WARNING: &str = "an image couldn't be decoded and is missing from the picture"; - // A PNG whose header reads but whose pixel data is cut short. +/// A PNG whose header reads but whose pixel data is cut short, which the renderer can't decode. +fn cut_short_png() -> Vec { let mut png = Vec::new(); image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) .unwrap(); + png +} + +/// The PNG's note on an image the renderer can't decode. +const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; + +/// Copy of an image the renderer can't decode: the PNG leaves it out, and once the formats are +/// written the status bar says the Copy (or Cut) has 1 note and shows it, made at once or on the +/// worker. The note is kept for the message's hover, and a Copy without notes leaves the message. +#[test] +fn copy_says_in_the_status_bar_when_an_image_could_not_be_decoded() { + let png = cut_short_png(); for worker in [false, true] { let (mut app, board) = if worker { app_with_worker() } else { app() }; app.status("Ready"); copy_rect(&mut app); background::wait_all(&mut app); - assert_eq!(app.ui.status, "Ready", "worker {worker}: no note"); - vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); - app.status("Ready"); - run(&mut app, "edit.copy", json!({})); - background::wait_all(&mut app); - assert_eq!(written(&board), [TEXT, SVG, PNG], "worker {worker}"); - assert_eq!(app.ui.status, WARNING, "worker {worker}"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None), "worker {worker}: no note"); + for (id, said) in [("edit.copy", "Copied"), ("artboard.copy", "Copied"), ("edit.cut", "Cut")] { + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &png, json!({})); + app.status("Ready"); + let p = if id == "artboard.copy" { json!({"index": 0}) } else { json!({}) }; + run(&mut app, id, p); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG], "worker {worker}: {id}"); + let status = format!("{said} with 1 note: {UNDECODED}"); + assert_eq!(app.ui.status, status, "worker {worker}: {id}"); + assert_eq!(app.ui.status_notes, Some((status, vec![UNDECODED.to_string()])), "worker {worker}: {id}"); + } } } +/// The status bar names how many notes a Copy's or Cut's formats have and the first of them, and +/// keeps them all, in order, for the message's hover. Without notes it keeps its message. +#[test] +fn copy_notes_are_counted_and_kept_in_order() { + let (mut app, _) = app(); + let notes: Vec = ["first", "second", "third"].map(String::from).to_vec(); + for (cut, said) in [(false, "Copied"), (true, "Cut")] { + crate::sysclip::show_copy_notes(&mut app, cut, notes.clone()); + let status = format!("{said} with 3 notes: first"); + assert_eq!(app.ui.status, status); + assert_eq!(app.ui.status_notes, Some((status, notes.clone()))); + } + app.status("Ready"); + app.ui.status_notes = None; + crate::sysclip::show_copy_notes(&mut app, false, vec![]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None)); +} + +/// A message shown while a Copy's formats are made on the worker stays: the formats are written +/// once they are ready, and their note does not replace the newer message. +#[test] +fn a_copy_note_does_not_replace_a_newer_message() { + let (mut app, board, hold) = app_with_busy_worker(""); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + app.status("Ready"); + run(&mut app, "edit.copy", json!({})); + app.status("Saved /out/a.vectorcraft"); + drop(hold); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Saved /out/a.vectorcraft", &None)); +} + /// Text copied in a field or with the Type tool after Copy, before the formats are written: they /// are not written, the system clipboard keeps the text, and Paste takes it. #[test] diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index d2de2f00f5..6da8e8a60e 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -108,6 +108,46 @@ fn without_threads_make_traces_at_once() { assert_eq!(undos(&app), before + 1); } +/// A trace's notes: the status bar names how many there are and the first of them, and keeps them +/// all, in the reply's order, for the message's hover. Make and Make and Expand, at once, off the +/// UI thread and from the Image Trace panel; a trace without notes leaves the status bar empty. +#[test] +fn a_trace_shows_how_many_notes_it_has() { + let mut app = app(); + let img = image::RgbaImage::from_fn(1501, 20, |x, _| image::Rgba(if x < 700 { [0, 0, 0, 255] } else { [255, 255, 255, 255] })); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let data = vectorcraft_format::base64_encode(&png); + let p = json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "keepColors": ["#ff00ff", "#00ffff"]}}); + for (command, threaded, from_panel) in + [("imageTrace.make", false, false), ("imageTrace.make", true, false), ("imageTrace.makeAndExpand", true, true)] + { + app.run("file.place", json!({"name": "wide.png", "dataBase64": data, "link": false})).unwrap(); + app.trace_runs.off_the_ui_thread = threaded; + app.ui.status.clear(); + trace_runs::start(&mut app, command, p.clone(), from_panel).unwrap(); + wait(&mut app); + let notes = [ + "Nothing was traced: none of the colors the trace found matches keepColors (#ff00ff, #00ffff).", + "The image is 1501 × 20 pixels, more than 1500 on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster.", + ] + .map(String::from) + .to_vec(); + let status = format!("Traced with 2 notes: {}", notes[0]); + assert_eq!(app.ui.status, status, "{command}, threaded {threaded}"); + assert_eq!(app.ui.status_notes, Some((status, notes)), "{command}, threaded {threaded}"); + } + // The 40 × 40 px image of [`app`] traces without notes: the status bar stays empty. + let mut app = self::app(); + for command in ["imageTrace.make", "imageTrace.makeAndExpand"] { + app.ui.status.clear(); + let v = app.run(command, json!({"preset": "Default"})).unwrap(); + assert_eq!(v["warnings"], json!([]), "{command}"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None), "{command}"); + app.run("edit.undo", json!({})).unwrap(); + } +} + /// Nothing to trace fails at once, before anything runs. #[test] fn nothing_to_trace_fails_at_once() { diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index e05448b10c..09df74f724 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -76,6 +76,11 @@ pub struct TraceRuns { pub(crate) off_the_ui_thread: bool, } +/// The status bar's line after an Image Trace with `n` notes, the first of them `first`. +pub(crate) fn traced_with_notes(n: usize, first: &str) -> String { + crate::i18n::msg_n(n as u64, "Traced with {n} note: {first}", "Traced with {n} notes: {first}", &[("first", first)]) +} + /// Does `app` trace off the UI thread? Where documents open off it ([`crate::opening::available`]), /// and in the unit tests that set `off_the_ui_thread`. pub fn available(app: &VectorcraftApp) -> bool { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5694d9582d..ab50aecf1e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -702,7 +702,8 @@ type with those options (`file.place {text: {…}}`). System clipboard formats: through the desktop app, `edit.copy`, `edit.cut`, `artboard.copy` and `artboard.cut` publish what `clipboard.flavours` lists to the system clipboard (once they are written, the status bar shows the first of the PNG's and PDF's -`warnings`, such as an image that couldn't be decoded), and every Paste command first loads what another app copied (`clipboard.importSvg`, +`warnings`, such as an image that couldn't be decoded, and how many there are, and hovering the message lists them, unless +another message has replaced the Copy or Cut's meanwhile), and every Paste command first loads what another app copied (`clipboard.importSvg`, `importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere; a copied `.ai` or `.ait` file that holds a PDF loads with `importPdf {editingData: true}`, which reads its editing data); an import error answers the Paste with that error and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..4aee59ff57 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6689,7 +6689,9 @@ area). Each one has a query command: (a one-page PDF, the page the objects' visual bounds) and `clipboard.exportPng {scale?}` (cropped to the objects, transparent around them). As in `document.export`, the PDF's and the PNG's replies list their notes in `warnings` (type written in the fallback font…; the PNG's also say when an image couldn't be decoded). After Copy or Cut the app -shows the first note of the PDF and PNG it offers in the status bar. +shows the first note of the PDF and PNG it offers in the status bar and how many there are, and hovering the message lists +them all, unless another message has replaced the Copy or Cut's while the formats were made. The `clipboard.export*` +replies still list every note. What other apps copied goes into the clipboard with `clipboard.importSvg`, `clipboard.importPdf {dataBase64, page?, password?, editingData?}` (the page's objects; with `editingData: true` the data is a `.ai` or `.ait` file, and every diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..68c56358e2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -594,6 +594,7 @@ since 2026-10-01. - **Clipped bottom-bar text (#6622):** A Help Bar hint wider than the window, such as the Dimension tool's hint in an 800-point window, ends in an ellipsis, as the status message does. In a narrow status bar the tool name ends in an ellipsis and leaves the status message its room. Resting the pointer on a clipped hint, tool name or message shows the full text in a tooltip that wraps within the window. Text that fits shows no tooltip, and screen readers receive the full text. Scores and estimates are unchanged. - **Notes of an open in the status bar:** After File › Open the status message names the first note that says reading the file left something out (the notes that make Save ask before writing over the file), else the first note, and counts them all. With several notes, resting the pointer on the message lists them in that order, as many as fit in the window and at most 30, then how many more. Screen readers receive the list after the message. Scores and estimates are unchanged. - **Notes of a save or an export in the status bar:** After Save, Save As, Save a Copy, Save as Template, Save a Timestamped Copy, Save as PDF, Export As, Export Selection, Export for Screens, Asset Export, Save for Web, Preview in Browser, Save for Office Documents, Text Export Options, a print to a file or the CSS Properties panel's export, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order the reply gives them (a save's notes start with what the format loses), as it lists an open's notes. Scores and estimates are unchanged. +- **Notes of a Copy, a Cut or an Image Trace in the status bar:** After Copy or Cut (also of artboards and of text in the Type tool) writes its formats to the system clipboard, and after Image Trace's Make or Make and Expand, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order they were made, as it lists a save's notes. A message shown while the clipboard formats were being made stays in place of the Copy's or Cut's notes. Scores and estimates are unchanged. - **What a save or an export loses, named first:** Each writer marks its notes as a loss (something of the document the file leaves out or writes differently) or a note on the options (an option it didn't apply or applied another way while the art reaches the file as it looks, or something an option turns off). The replies of the save and export commands list the losses first, each kind in the order given, across every file an export writes. The status message after a save or an export then names a loss when there is one: an export to lossy WebP of type in a font that isn't installed names the fallback-font note instead of the lossy WebP note. A print to a file and the print preview list theirs the same way: art outside the imageable area, type in a fallback font and transparency flattened for PostScript come before notes such as a fixed flatness that isn't written or copies per sheet that don't fit. Scores and estimates are unchanged. - **Canvas review follow-up:** Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Controlled-worker regression checks oversized width and height, high DPI and the render transform without allocating oversized images. Scores and estimates are unchanged. From 4716646c6bb4773c9866095029920ad4cc719b20 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:42:56 -0800 Subject: [PATCH 002/138] Scripts: File and Folder objects write files inside a script's scope, with per-script grants and pickers A script's File and Folder objects now open files for writing, appending and editing, and copy, rename, remove and create files and folders. A script reads and writes its run's temporary folder (Folder.temp) and its own data folder (Folder.userData), kept between runs for a script run from a file and inside Folder.temp for a script given as text. It reads its own folder, and reaches other places only through File.openDialog, File.saveDialog, Folder.selectDialog and the objects' openDlg, saveDlg and selectDlg. - A file dialog asks first. The person picks the file or folder with Choose..., then allows it once or, for a script run from a file, always. A kept grant is bound to the script's path, the SHA-256 of its text and every source the run evaluated. It is withdrawn when a later run of the script evaluates other code, including code an earlier run left in the same named engine. It stays on the real path that was granted, so a link put in that place later does not carry it elsewhere. - A dialog's filter is a string of file types or a function that is called with each file picked; multiSelect gives an array of the files picked, at most 2,048, and the dialog says when more were left out. - A folder's selectDlg opens the host's folder dialog in that folder, also where the host shows file dialogs in line. Enter in the file dialog denies, unless it goes to the focused Choose... button. script.grants.revoke is refused with the busy error while a script runs, as the run keeps the grants it started with. - The paths a file dialog allows come only from the host's file dialog: ui.dialog.set cannot set them. Only the person at the keyboard allows access; Allow Once and Always Allow sent by automation are refused. The dialog describes the access the run asked for, whatever its fields say. - No grant reaches the settings folder, also when the script's own folder holds it. - A file left open is not written through a link put in place of its folder since it was opened, and Folder.userData is null when the data folder or the script's folder in it is a link. - copy onto another link to the same file (a hard link) leaves the file's bytes as they are, after the source's open objects have written what they hold. Files are compared by identity (device and inode on Unix, volume and file index on Windows). - Folder.temp and Folder.userData check each folder they make against the automation write roots first, and Folder.create() makes nothing when a missing folder above the target is outside the places the script may write. - An open file holds at most 8 MiB, a run writes at most 32 MiB and keeps at most 256 files open, and the files a run left open are written in the order they were opened. Setting length and copying a file count the bytes every open object of that file takes, and write checks the joined text against the limit while joining it. The report names at most 4,096 written files and sets writtenMore when there were more. - Errors a script sees are translated in every complete message catalog. --- apps/vectorcraft-cli/src/main.rs | 6 +- apps/vectorcraft/src/host_services.rs | 48 +- apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/prefs_dir.rs | 9 + crates/engine/Cargo.toml | 5 +- crates/engine/src/cmd/scripts.rs | 66 +- crates/engine/src/file_access.rs | 254 +++- crates/engine/src/lib.rs | 4 + crates/engine/src/script/files.rs | 1339 +++++++++++++++++++++- crates/engine/src/script/mod.rs | 165 ++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/script_io.rs | 1259 +++++++++++++++++++- crates/engine/src/tests/script_run.rs | 140 ++- crates/js/src/builtins.rs | 2 + crates/js/src/file_classes.rs | 362 +++++- crates/js/src/host.rs | 7 +- crates/js/src/host_tests.rs | 18 + crates/js/src/interp.rs | 15 + crates/js/src/realm.rs | 18 +- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/dialogs.rs | 4 + crates/ui-egui/src/dialogs/script_run.rs | 214 +++- crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 30 +- crates/ui-egui/src/i18n/cs.tsv | 30 +- crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 30 +- crates/ui-egui/src/i18n/el.tsv | 30 +- crates/ui-egui/src/i18n/es.tsv | 30 +- crates/ui-egui/src/i18n/fi.tsv | 30 +- crates/ui-egui/src/i18n/fr.tsv | 30 +- crates/ui-egui/src/i18n/hi.tsv | 30 +- crates/ui-egui/src/i18n/hu.tsv | 30 +- crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 30 +- crates/ui-egui/src/i18n/ja.tsv | 30 +- crates/ui-egui/src/i18n/ka.tsv | 30 +- crates/ui-egui/src/i18n/ko.tsv | 30 +- crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 30 +- crates/ui-egui/src/i18n/pt-br.tsv | 30 +- crates/ui-egui/src/i18n/ru.tsv | 30 +- crates/ui-egui/src/i18n/sv.tsv | 30 +- crates/ui-egui/src/i18n/tests.rs | 66 +- crates/ui-egui/src/i18n/tr.tsv | 30 +- crates/ui-egui/src/i18n/uk.tsv | 30 +- crates/ui-egui/src/i18n/vi.tsv | 30 +- crates/ui-egui/src/i18n/zh-hans.tsv | 30 +- crates/ui-egui/src/i18n/zh-hant.tsv | 30 +- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/picks.rs | 31 +- crates/ui-egui/src/script_runs.rs | 11 +- crates/ui-egui/src/services.rs | 11 + crates/ui-egui/src/tests/picks.rs | 7 +- crates/ui-egui/src/tests/script_run.rs | 327 +++++- docs/mcp.md | 118 +- docs/target-app-parity.md | 3 +- 58 files changed, 4948 insertions(+), 265 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 0d4deca36f..9e2a63a9c1 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,12 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and -/// `VECTORCRAFT_CONFIG_DIR` apply as they do there. +/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there and starts new +/// documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they +/// do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 03a9b8848c..8622a19223 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -71,7 +71,7 @@ fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { /// `d` set up for `request`: its title, file types, folder and suggested name. fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) => pick, + PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( @@ -81,8 +81,9 @@ fn dialog_for(d: D, request: &PickRequest) -> D { }); } PickRequest::Folder => return d, + PickRequest::FolderAt(folder) => return d.folder(folder), }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_)); + let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); let d = pick.filters.iter().fold(d, |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), @@ -96,6 +97,37 @@ fn dialog_for(d: D, request: &PickRequest) -> D { if pick.name.is_empty() { d } else { d.file_name(&pick.name) } } +#[cfg(test)] +#[test] +fn a_folder_picker_asked_for_a_folder_starts_there() { + /// The settings a dialog was given, by name. + #[derive(Default)] + struct Recorded(Vec); + impl DialogSettings for Recorded { + fn parent(self, _: &winit::window::Window) -> Self { + self + } + fn title(mut self, title: &str) -> Self { + self.0.push(format!("title {title}")); + self + } + fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { + self.0.push(format!("filter {name}")); + self + } + fn folder(mut self, folder: &str) -> Self { + self.0.push(format!("folder {folder}")); + self + } + fn file_name(mut self, name: &str) -> Self { + self.0.push(format!("name {name}")); + self + } + } + assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); + assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); +} + /// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the /// window and keeps it in front). #[cfg(not(target_os = "macos"))] @@ -128,9 +160,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) } let paths = match request { PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), + PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder => dialog.pick_folder().into_iter().collect(), + PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), }; paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() } @@ -313,7 +345,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti let picked = dialog.pick_file(); Box::pin(async move { picked.await.iter().map(path).collect() }) } - PickRequest::OpenMany => { + PickRequest::OpenMany | PickRequest::OpenFiles(_) => { let picked = dialog.pick_files(); Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) } @@ -332,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti // on that nil; treat the pick as cancelled instead (#5980). Err(()) => Box::pin(async move { Vec::new() }), }, - PickRequest::Folder => { + PickRequest::Folder | PickRequest::FolderAt(_) => { let picked = dialog.pick_folder(); Box::pin(async move { picked.await.iter().map(path).collect() }) } @@ -353,7 +385,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .and_then(|w| w.window_handle().ok()) .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); + let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); #[cfg(any(target_os = "macos", target_os = "linux"))] let sampled_ui = ui.clone(); #[cfg(target_os = "linux")] @@ -361,6 +393,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { Services { pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), + pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows // dialogs run the window's events while they are open. @@ -407,6 +440,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), + pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] screen_color: Some(mac_screen_color::sampler(sampled_ui)), diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c2b40e37e6..92088fd67b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -479,6 +479,7 @@ fn main() -> std::process::ExitCode { // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..80b42ef219 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -73,6 +73,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people +/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first +/// needs them. +pub fn attach_script_data(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Script Data") { + session.attach_script_data(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fccbcdecb..264581e3ed 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -67,8 +67,9 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } -# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). -# Already in Cargo.lock (walkdir), so this adds no new crate. +# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), +# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock +# (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index f5edf1f91d..623ab8a87f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -90,6 +90,24 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.grants", + "List Script File Permissions", + [], + None, + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + always, + grants + ), + cmd!( + query "script.grants.revoke", + "Revoke Script File Permissions", + [], + None, + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed; refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + always, + grants_revoke + ), cmd!( query "script.check", "Check Script", @@ -228,6 +246,18 @@ impl Session { self.scripts_dir = Some(dir); } + /// Keep each script's data folder (`Folder.userData`) in the folder `dir`, and the file access + /// people allow scripts with Always in [`script::files::GRANTS_FILE`] beside it. The folders are + /// made when a script first needs them. + pub fn attach_script_data(&mut self, dir: std::path::PathBuf) { + self.script_data_dir = Some(dir); + } + + /// The folder of the scripts' data folders ([`Session::attach_script_data`]); none on the web. + pub fn script_data_dir(&self) -> Option<&std::path::Path> { + self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. pub fn scripts_dir(&self) -> Option<&std::path::Path> { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) @@ -308,6 +338,40 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { Ok(json!({"folder": folder, "scripts": scripts, "truncated": listing.truncated, "unreadable": listing.unreadable})) } +fn grants(s: &mut Session, _: &Value) -> Result { + let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; + let file = dir.with_file_name(script::files::GRANTS_FILE); + Ok(json!({"grants": script::files::stored_grants(dir), "file": file.to_string_lossy()})) +} + +fn grants_revoke(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.grants.revoke"; + let path_of = |key: &str| match p.get(key) { + None => Ok(None), + Some(Value::String(t)) if !t.is_empty() => { + Ok(Some(std::fs::canonicalize(t).map_or_else(|_| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()))) + } + Some(_) => Err(bad(C, format!("`{key}` must be a path"))), + }; + let (script_path, path) = (path_of("script")?, path_of("path")?); + let all = match p.get("all") { + None => false, + Some(Value::Bool(true)) => true, + Some(_) => return Err(bad(C, "`all` must be true")), + }; + if all == (script_path.is_some() || path.is_some()) { + return Err(bad(C, "give `all`, or `script` and `path` or one of them")); + } + // A running script holds the grants it started with until it ends. + if s.script_running() { + return Err(EngineError::Busy); + } + let Some(dir) = s.script_data_dir() else { return Ok(json!({"removed": 0})) }; + let removed = script::files::revoke_grants(dir, script_path.as_deref(), path.as_deref()) + .map_err(|e| EngineError::Other(format!("the script file permissions could not be saved: {e}")))?; + Ok(json!({"removed": removed})) +} + /// The folder a script is in, which its included files are read from. struct Folder { dir: std::path::PathBuf, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 6ca724d810..9aaeb58dab 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -25,7 +25,9 @@ //! guard against other programs on the computer. //! //! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) -//! are read from, inside the roots. +//! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. +//! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the +//! files of the open documents. use std::cell::RefCell; use std::ffi::OsString; @@ -185,22 +187,87 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_scope(Some(Scope::Unconfined), f) } -/// This thread's scope, to carry to work it hands to another thread ([`ScopeHandle::run`]). +/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to +/// another thread ([`ScopeHandle::run`]). #[derive(Clone, Debug)] -pub struct ScopeHandle(Option); +pub struct ScopeHandle(Option, Option>); impl ScopeHandle { /// The scope of the calling thread. pub fn capture() -> Self { - Self(SCOPE.with(|s| s.borrow().clone())) + Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone())) } /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { - with_scope(self.0, f) + let Self(scope, gate) = self; + with_gate(gate, || with_scope(scope, f)) } } +/// What a command a running script runs (`vc.run`) may read and write: the places the script's +/// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app +/// were opened from or saved to. The automation roots apply as well. A path refused by its name +/// alone ([`ScriptScope::refused_by_name`]) is refused here too. +#[derive(Clone, Debug)] +pub(crate) struct ScriptGate { + pub(crate) read: ScriptScope, + pub(crate) write: ScriptScope, + /// The paths of the open documents' files, as the documents hold them. + pub(crate) documents: Vec, +} + +impl ScriptGate { + fn check(&self, path: &str, access: Access) -> Result<(), String> { + let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; + let allowed = real.is_some_and(|real| { + let scoped = match access { + Access::Read => self.read.allows(&real) || self.write.allows(&real), + Access::Write => self.write.allows(&real), + }; + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + }); + if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } + } +} + +thread_local! { + /// The gate of the script command this thread runs ([`with_script_gate`]). + static GATE: RefCell>> = const { RefCell::new(None) }; +} + +/// Puts the gate it replaced back when dropped (also when `f` panics). +struct RestoreGate(Option>); + +impl Drop for RestoreGate { + fn drop(&mut self) { + let previous = self.0.take(); + GATE.with(|g| *g.borrow_mut() = previous); + } +} + +fn with_gate(gate: Option>, f: impl FnOnce() -> T) -> T { + let _restore = RestoreGate(GATE.with(|g| g.replace(gate))); + f() +} + +/// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or +/// writes must pass the gate as well as the automation roots. Reads of the app's own folders, +/// inside [`unconfined`], are not checked; writes there are, so a script's command does not save +/// into the app's libraries. +pub(crate) fn with_script_gate(gate: ScriptGate, f: impl FnOnce() -> T) -> T { + with_gate(Some(Arc::new(gate)), f) +} + +/// May `path` be read (or written) by the script command this thread runs? Always outside one, +/// and for a read inside [`unconfined`]. +fn check_gate(path: &str, access: Access) -> Result<(), String> { + if matches!(access, Access::Read) && SCOPE.with(|s| matches!(*s.borrow(), Some(Scope::Unconfined))) { + return Ok(()); + } + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) +} + /// The roots in force on this thread, if any. pub fn current() -> Option> { match SCOPE.with(|s| s.borrow().clone()) { @@ -210,9 +277,11 @@ pub fn current() -> Option> { } } -/// May `path` be read here? Always, without roots in force. +/// May `path` be read here? Always, without roots in force and outside a script's command +/// ([`with_script_gate`]). pub fn check_read(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Read)) + current().map_or(Ok(()), |r| r.check(path, Access::Read))?; + check_gate(path, Access::Read) } /// Is `path`, under a read root, written as an absolute path of another platform: outside Windows, one @@ -229,9 +298,11 @@ pub fn is_path_key(key: &str) -> bool { matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end)) } -/// May `path` be written here? Always, without roots in force. +/// May `path` be written here? Always, without roots in force and outside a script's command +/// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -323,6 +394,12 @@ fn inside(path: &Path, root: &Path) -> bool { root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) } +/// Is `path` `root` or inside it, both with their links followed, compared as [`AutomationRoots`] +/// compares them? +pub(crate) fn path_inside(path: &Path, root: &Path) -> bool { + inside(path, root) +} + fn same_component(a: Component, b: Component) -> bool { if a == b { return true; @@ -374,10 +451,21 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> { /// The file opened is the path with its links followed, and after reading, the path is followed /// again and must still lead to the same place: a process that changes the folders twice in between /// can still win that race. +/// +/// A scope can also be given more folders ([`ScriptScope::add`]) and single files +/// ([`ScriptScope::add_file`]), and folders it keeps out even inside a granted folder +/// ([`ScriptScope::fence`]), each but the places inside it that stay open. A granted file grants its +/// own path only, also when a folder later takes its place. #[derive(Clone, Debug, Default)] pub(crate) struct ScriptScope { /// The granted folders, made absolute with their links followed. roots: Vec, + /// The granted files, made absolute with their links followed. + files: Vec, + /// The folders kept out, with their links followed. + fenced: Vec, + /// The places inside a fenced folder that are not kept out. + open: Vec, } /// Why a script's file was not read. @@ -396,12 +484,62 @@ pub(crate) enum ScriptRead { impl ScriptScope { /// The scope of a script run from a file in folder `dir`: that folder. pub(crate) fn of_folder(dir: &Path) -> Self { - Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() } + Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect(), ..Self::default() } + } + + /// Grants the folder `real`, a path with its links followed, with everything inside it. + pub(crate) fn add(&mut self, real: PathBuf) { + if !self.roots.contains(&real) { + self.roots.push(real); + } + } + + /// Grants the file `real`, a path with its links followed: that path and nothing below it. + pub(crate) fn add_file(&mut self, real: PathBuf) { + if !self.files.contains(&real) { + self.files.push(real); + } + } + + /// Takes back the grant of the folder (`folder`) or file `real` that [`ScriptScope::add`] or + /// [`ScriptScope::add_file`] gave. + pub(crate) fn remove(&mut self, real: &Path, folder: bool) { + if folder { self.roots.retain(|r| r != real) } else { self.files.retain(|r| r != real) } + } + + /// Is nothing granted? + fn is_empty(&self) -> bool { + self.roots.is_empty() && self.files.is_empty() + } + + /// Keeps the folder `real` (links followed) and everything in it out, but for `open` and the + /// places inside it. + pub(crate) fn fence(&mut self, real: PathBuf, open: &[PathBuf]) { + self.fenced.push(real); + self.open.extend(open.iter().cloned()); + } + + /// Leaves the place `real` (links followed) and everything in it open inside a fenced folder. + pub(crate) fn fence_open(&mut self, real: PathBuf) { + self.open.push(real); + } + + /// The granted folders, with their links followed. + pub(crate) fn roots(&self) -> &[PathBuf] { + &self.roots + } + + /// Is the real path `real` a granted file or inside a granted folder, and not kept out? A place + /// left open counts only inside the fenced folder: one that holds the fenced folder opens none of it. + pub(crate) fn allows(&self, real: &Path) -> bool { + (self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count()) + || self.roots.iter().any(|r| inside(real, r))) + && !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) } /// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or /// stream, or a computer on the network? - fn refused_by_name(path: &Path) -> bool { + pub(crate) fn refused_by_name(path: &Path) -> bool { let text = path.to_string_lossy(); text.contains('\0') || path.components().any(|c| c == Component::ParentDir) @@ -411,7 +549,7 @@ impl ScriptScope { /// The real path of the file at `path` and its first `max` bytes, at most. pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec), ScriptRead> { use std::io::Read; - if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { + if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { return Err(ScriptRead::Refused); } let real = match std::fs::canonicalize(path) { @@ -422,7 +560,7 @@ impl ScriptScope { } Err(e) => return Err(ScriptRead::Failed(e.to_string())), }; - if !self.roots.iter().any(|r| inside(&real, r)) { + if !self.allows(&real) { return Err(ScriptRead::Refused); } let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; @@ -450,24 +588,24 @@ impl ScriptScope { self.roots.first().map(|r| crate::cmd::findfiles::plain(r.clone())) } - /// Does the absolute path `path` name a granted folder or a place inside one, by its names - /// alone, without regard to case? A path that does not is refused before the file system is - /// asked anything about it. + /// Does the absolute path `path` name a granted file, a granted folder or a place inside one, + /// by its names alone, without regard to case? A path that does not is refused before the file + /// system is asked anything about it. fn names_inside(&self, path: &Path) -> bool { let lower = |c: Component| c.as_os_str().to_string_lossy().to_lowercase(); - path.is_absolute() - && self.roots.iter().any(|r| { - let root = crate::cmd::findfiles::plain(r.clone()); - let mut names = path.components(); - root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c))) - }) + let names_under = |r: &PathBuf| { + let root = crate::cmd::findfiles::plain(r.clone()); + let mut names = path.components(); + root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c))) + }; + path.is_absolute() && (self.roots.iter().any(names_under) || self.files.iter().any(names_under)) } /// The real path of the file or folder at `path`, which must be absolute: refused as /// [`ScriptScope::read`] refuses a path, and also when its names alone place it outside every /// granted folder, in which case the file system is not asked about it. pub(crate) fn locate(&self, path: &Path) -> Result { - if self.roots.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { + if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { return Err(ScriptRead::Refused); } probed(); @@ -484,22 +622,72 @@ impl ScriptScope { } Err(e) => return Err(ScriptRead::Failed(e.to_string())), }; - if !self.roots.iter().any(|r| inside(&real, r)) { + if !self.allows(&real) { return Err(ScriptRead::Refused); } Ok(real) } - /// Is the missing `path` inside a granted folder: does the nearest folder above it that exists - /// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is - /// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too, - /// so a script cannot tell whether the folder a link leads to exists. + /// The real path that writing to `path` writes: `path` with its links followed (the last + /// name's too only when `follow`), and for a path that does not exist yet, its nearest existing + /// folder's links followed and the rest appended. Refused as [`ScriptScope::locate`] refuses a + /// path, also when a link on the way leads nowhere, and when the automation write roots in force + /// ([`check_write`]) do not take it. + pub(crate) fn target(&self, path: &Path, follow: bool) -> Result { + if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { + return Err(ScriptRead::Refused); + } + probed(); + if check_write(&path.to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return Err(ScriptRead::Refused) }; + let real = match std::fs::symlink_metadata(path) { + Ok(_) if follow => std::fs::canonicalize(path).map_err(|_| ScriptRead::Refused)?, + Ok(m) => { + // Where case does not matter, the name given can differ in case from the name the + // file system keeps, so a file or folder that is not a link is checked under the + // kept name too. + if !m.file_type().is_symlink() && !std::fs::canonicalize(path).is_ok_and(|kept| self.allows(&kept)) { + return Err(ScriptRead::Refused); + } + std::fs::canonicalize(parent).map_err(|_| ScriptRead::Refused)?.join(name) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let mut missing = vec![name.to_os_string()]; + let mut at = parent; + loop { + match std::fs::symlink_metadata(at) { + Ok(_) => break, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + missing.push(at.file_name().ok_or(ScriptRead::Refused)?.to_os_string()); + at = at.parent().ok_or(ScriptRead::Refused)?; + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + } + } + let mut real = std::fs::canonicalize(at).map_err(|_| ScriptRead::Refused)?; + real.extend(missing.iter().rev()); + real + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + }; + // The automation write roots take the place written as well as the path named. + if !self.allows(&real) || check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + Ok(real) + } + + /// Is the missing `path` inside a granted place: with the links of the nearest folder above it + /// that exists followed, and the rest of its names appended, is it granted? On a file system + /// where case matters, `MAIN/x` beside the granted `main` is outside, whether `MAIN` exists or + /// not. A link above it that leads to nothing is outside too, so a script cannot tell whether + /// the folder a link leads to exists. fn missing_inside(&self, path: &Path) -> bool { - path.ancestors() - .skip(1) - .find(|a| std::fs::symlink_metadata(a).is_ok()) - .and_then(|a| std::fs::canonicalize(a).ok()) - .is_some_and(|real| self.roots.iter().any(|r| inside(&real, r))) + let Some(found) = path.ancestors().skip(1).find(|a| std::fs::symlink_metadata(a).is_ok()) else { return false }; + let (Ok(real), Ok(rest)) = (std::fs::canonicalize(found), path.strip_prefix(found)) else { return false }; + self.allows(&real.join(rest)) } /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. @@ -542,7 +730,7 @@ impl ScriptScope { continue; } let Ok(target) = std::fs::canonicalize(entry.path()) else { continue }; - if !self.roots.iter().any(|r| inside(&target, r)) || check_read(&entry.path().to_string_lossy()).is_err() { + if !self.allows(&target) || check_read(&entry.path().to_string_lossy()).is_err() { continue; } if out.len() >= max { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3c3460ecb2..ebf52fb27f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -180,6 +180,10 @@ pub struct Session { /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option, + /// The folder of each script's data folder (`Folder.userData`), beside which the grants file + /// keeps the file access people allowed scripts; `None`: no folder + /// ([`Session::attach_script_data`]). + script_data_dir: Option, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option, diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ec848a973e..37f3b93213 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -21,7 +21,8 @@ //! `File` for an existing file, only where the path may be read. //! - Opening reads the whole file, at most [`MAX_FILE_BYTES`], checked from its size before any of //! it is read; a run reads at most [`MAX_RUN_BYTES`] in all and ends past that, and has at most -//! [`MAX_OPEN`] files open at once. +//! [`MAX_OPEN`] files open at once. A file opened again after its objects closed counts only the +//! bytes it has grown by; a file open in another object counts again. //! - The encoding of an opened file is the one its byte order mark gives (UTF-8, UTF-16LE or //! UTF-16BE), otherwise the one the script set, otherwise UTF-8 when the bytes are valid UTF-8, //! otherwise CP1252. `read`, `readln` and `readch` count characters and `seek` and `tell` bytes; @@ -29,12 +30,45 @@ //! as `"\n"`. A character the encoding cannot decode fails the read with [`UNDECODABLE`] and //! leaves the position where it was. //! - `getFiles` lists at most [`MAX_ENTRIES`] entries, sorted by name, and looks at most -//! [`crate::file_access::MAX_LISTED`] names; a mask matches `*` and `?` without regard to case, -//! in at most [`MAX_MASK_STEPS`] steps for one listing. +//! [`crate::file_access::MAX_LISTED`] names; a mask matches `*` and `?`, without regard to case +//! on Windows and macOS, in at most [`MAX_MASK_STEPS`] steps for one listing. //! - A path longer than [`MAX_PATH_CHARS`] characters is refused before it is split into names. -//! - Writing (`open` with `w`, `e` or `a`, `write`, `copy`, `remove`, `rename`, `create` and the -//! property setters), the file and folder dialogs and `execute` are not available: they return -//! `false` or `null` and set `error`. `execute` is counted in the report's `fileExecutes`. +//! - A script writes only in its run's temporary folder (`Folder.temp`, made when it is first +//! named and deleted when the run ends), its own data folder (`Folder.userData`: for a script run +//! from a file a folder of its own beside the settings, kept between runs, and for a script given +//! as text a folder inside the temporary one), and the files and folders a person granted it. +//! Its own folder is only read. The automation write roots apply as well, and the folder that +//! holds the settings, with the Scripts and Plug-ins folders, is kept out of every grant but the +//! script's data folder. +//! - In the app, `File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' +//! `openDlg`, `saveDlg` and `selectDlg` wait for the person, who picks a file or a folder and then +//! allows the script that one, once or always, or denies it ([`ScriptPicker`]). A picked file is +//! granted for reading (open) or for reading and writing (save), and a picked folder for reading +//! and writing with everything inside it. A `filter` that is a function is called with each file +//! picked, and the files it refuses are left out of what the dialog gives. Always keeps the grant in the grants file beside the +//! settings, for that script file with that text (its SHA-256): a changed or moved script has none, +//! and a kept grant whose path now leads elsewhere through a link is not used. +//! The grant also holds the SHA-256 of each source the run evaluated (a file `$.evalFile` ran, a +//! string given to `eval` or `Function`), up to the run's end: a later run that evaluates other +//! code, or whose named engine holds code its earlier runs compiled that the grant was not kept +//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and +//! [`NO_PICKER`]. +//! - The commands a script runs with `vc.run` read and write only in the places above and in the +//! files of the open documents ([`crate::file_access::ScriptGate`]). +//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most +//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at +//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an +//! ASCII or ISO-8859-1 file refuses a character it cannot hold, BINARY writes each character's low +//! byte) and `writeln` adds the `lineFeed`'s line end. `copy` replaces a file that is there, +//! `remove` deletes at once and takes a folder only when it is empty, `rename` takes a name without +//! a folder and refuses one in use, and `length` and `readonly` change a file (on Unix, clearing +//! `readonly` gives back the write bits the run cleared, or else the owner's). Each object that has +//! a file open holds its own bytes, so what `length` adds and what `copy` writes count once for the +//! file and once more for each such object. `write` joins its values only for an open file and +//! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the +//! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed. +//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`. +//! `execute` is counted in the report's `fileExecutes`. //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; @@ -49,6 +83,9 @@ use crate::file_access::{ScriptRead, ScriptScope}; /// The most bytes of one file a script opens. pub const MAX_FILE_BYTES: usize = 8 << 20; +/// The most files a run remembers the bytes counted for, so opening one again counts only what it +/// grew by; a file past them counts in full each time it is opened. +const MAX_CHARGED: usize = 4096; /// The most bytes of files one run opens, all of them counted together. pub const MAX_RUN_BYTES: usize = 32 << 20; /// The most entries `getFiles` gives. @@ -69,36 +106,659 @@ pub(crate) const NOT_FOUND: &str = "Script file does not exist"; pub(crate) const READ_FAILED: &str = "Script file could not be read"; pub(crate) const LISTING_TOO_LARGE: &str = "Script folder has more than 2,048 entries"; pub(crate) const BAD_MODE: &str = "Script file open mode must be r, w, e or a"; -pub(crate) const NO_WRITES: &str = "Script file writing is not available"; -pub(crate) const NO_PICKER: &str = "Script file dialogs are not available"; +pub(crate) const NO_PICKER: &str = "Script file dialogs need a person to answer them"; pub(crate) const NO_EXECUTE: &str = "Script files cannot be opened in another application"; pub(crate) const NO_WEB: &str = "Script file access is unavailable on the web"; pub(crate) const TOO_MANY_OPEN: &str = "Script has 256 files open"; pub(crate) const PATH_TOO_LONG: &str = "Script file path exceeds 32,767 characters"; pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many steps to match"; +pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; +pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; +pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; +pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; +pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; +pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; +pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases"; +pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed"; +pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed"; +pub(crate) const NOT_SAVED: &str = "Script file permission could not be saved"; +pub(crate) const NO_ALWAYS: &str = "Script file permission can be kept only for a script run from a file"; const OVER_RUN_BYTES: &str = "the script opened more file data than one run may open (32 MiB)"; +const OVER_RUN_WRITES: &str = "the script wrote more file data than one run may write (32 MiB)"; +/// The most grants the grants file keeps. +pub const MAX_STORED_GRANTS: usize = 4096; +/// The most bytes of the grants file that are read. +const MAX_STORE_BYTES: usize = 4 << 20; +/// The name of the grants file, beside the folder of the scripts' data folders. +pub const GRANTS_FILE: &str = "Script Grants.json"; +/// The most distinct sources a run evaluates whose SHA-256 is kept; past them no kept grant is in +/// force for the rest of the run, and the run's grants keep the sources counted before. +pub const MAX_RUN_CODE: usize = 256; + +/// The SHA-256 of `units`, source text a script evaluated, as UTF-16 code units in little-endian +/// order. +pub(crate) fn code_hash(units: &[u16]) -> String { + let bytes: Vec = units.iter().flat_map(|u| u.to_le_bytes()).collect(); + vectorcraft_plugins::permissions::sha256_hex(&bytes) +} /// The id of the next file a script opens. Ids are unique across runs, so a `File` that a named /// engine kept from an earlier run does not name a file a later run opened. static NEXT_HANDLE: AtomicU32 = AtomicU32::new(1); -/// The script's file state: its scope, where `Folder.current` starts, the files it has open and how -/// much it has read. +/// The number in the name of the next run's temporary folder. +static NEXT_TEMP: AtomicU32 = AtomicU32::new(1); + +/// Which file dialog a script opened. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PickerKind { + /// `File.openDialog` and `openDlg`: a file to read. + Open, + /// `File.saveDialog` and `saveDlg`: a file to write, which may not exist yet. + Save, + /// `Folder.selectDialog` and `selectDlg`: a folder to read and write. + Folder, +} + +impl PickerKind { + /// The kind's name: `open`, `save` or `folder`. + pub fn id(self) -> &'static str { + match self { + Self::Open => "open", + Self::Save => "save", + Self::Folder => "folder", + } + } +} + +/// A file dialog a running script waits at: the person picks a file or a folder, then allows the +/// script that one, once or always, or denies it ([`PickAnswer`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScriptPicker { + pub kind: PickerKind, + /// The script's prompt, empty when it gave none. + pub prompt: String, + /// An open dialog that may pick more than one file. + pub multiple: bool, + /// The file or folder the dialog starts at, when the script's object gave one. + pub start: Option, + /// The file types the dialog shows, from the script's filter ([`dialog_filters`]): each one's + /// name and extensions (`*` for every file). Empty: every file. + pub filters: Vec<(String, Vec)>, + /// Whether the grant can be kept for later runs: the script was run from a file, and the app + /// has a settings folder for the grants file. + pub can_always: bool, +} + +/// The answer to a [`ScriptPicker`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PickAnswer { + /// Cancel or Deny: the script gets `null`. + Deny, + /// The paths picked, allowed for this run, or with `always` for later runs of the same script too. + Allow { paths: Vec, always: bool }, +} + +/// What a run's `File` and `Folder` objects start with. +#[derive(Clone, Debug, Default)] +pub(crate) struct Setup { + /// The run is in the app, where a person answers its file dialogs. + pub framed: bool, + /// The file the script was read from. + pub script: Option, + /// The script's text with the files it includes, whose SHA-256 the grants it keeps are for. + pub source: String, + /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). + pub data_dir: Option, + /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source + /// ([`code_hash`] for evaluated code), and whether there was more than it keeps. + pub engine_code: (Vec, bool), +} + +/// A grant the grants file keeps that is in force for the run: the real path, whether it may be +/// written, whether it is a folder's, and the evaluated code the script ran in the run that kept it. +struct Stored { + path: std::path::PathBuf, + write: bool, + folder: bool, + code: std::collections::BTreeSet, +} + +/// The script's file state: where it reads and writes, where `Folder.current` starts, the files it +/// has open, how much it has read and written, and the file dialog it waits at. pub(crate) struct Disk { scope: ScriptScope, + /// Where the script writes: its temporary and data folders and what was granted for writing. + writes: ScriptScope, home: String, start: String, open: HashMap, temps: u32, bytes: usize, + /// The most bytes counted in `bytes` for each file read, by its real path ([`Disk::charge_read`]). + charged: HashMap, + written: usize, + framed: bool, + /// The script's file with its links followed, and the SHA-256 of its text. + script: Option<(std::path::PathBuf, String)>, + /// The SHA-256 of the script's text with the files it includes, also for a script given as + /// text, which its named engine keeps as code the engine holds. + own: String, + data_dir: Option, + /// The folder that holds the settings, with its links followed, which no grant reaches. + fenced: Option, + /// The run's temporary folder and the script's data folder, with their links followed, once made. + temp: Option, + user_data: Option, + /// The file dialog the script waits at. + pub(crate) picker: Option, + /// The error that ended the run when a dialog's answer could not reach the script. + pub(crate) failed: Option, + /// The files written since the host last took them ([`Disk::take_written`]). + wrote: Vec, + /// The places granted at the start (the script's own folder) and by the run itself (its + /// temporary and data folders and what a person allowed in a dialog), each with whether it + /// may be written and whether it is a folder: a withdrawn kept grant leaves these in force. + held: Vec<(std::path::PathBuf, bool, bool)>, + /// The kept grants in force: each is withdrawn once the run evaluates code it was not kept for. + stored: Vec, + /// The SHA-256 of each source other than the script itself that the run's code may run: what + /// it evaluated ([`code_hash`]) and what its named engine kept from earlier runs. + ran: std::collections::BTreeSet, + /// The run evaluated more distinct sources than [`MAX_RUN_CODE`]: no kept grant is in force. + ran_too_much: bool, + /// The grants this run kept with Always (path, write, folder), and how many sources `ran` held + /// when they were last written to the grants file. + kept: Vec<(std::path::PathBuf, bool, bool)>, + recorded: usize, + /// The write bits setting `readonly` cleared from each file in this run, by its device and + /// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back. + #[cfg(unix)] + cleared: HashMap<(u64, u64), u32>, +} + +impl Drop for Disk { + fn drop(&mut self) { + // The run's end has flushed these already and reported what it could not write. + let _ = self.flush_all(); + if let Some(temp) = self.temp.take() { + let _ = std::fs::remove_dir_all(temp); + } + } } impl Disk { /// The state of a run whose own files are read in `scope`. - pub(crate) fn new(scope: &ScriptScope) -> Self { + pub(crate) fn new(scope: &ScriptScope, setup: Setup) -> Self { let home = home_folder(); let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); - Self { scope: scope.clone(), home, start, open: HashMap::new(), temps: 0, bytes: 0 } + let web = cfg!(target_arch = "wasm32"); + let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok()); + let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()); + let script = script.map(|p| (p, own.clone())); + let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned); + let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect(); + let mut d = Self { + scope: scope.clone(), + writes: ScriptScope::default(), + home, + start, + open: HashMap::new(), + temps: 0, + bytes: 0, + charged: HashMap::new(), + written: 0, + framed: setup.framed, + script, + own, + data_dir: setup.data_dir, + fenced: fenced.clone(), + temp: None, + user_data: None, + picker: None, + failed: None, + wrote: Vec::new(), + held, + stored: Vec::new(), + ran: std::collections::BTreeSet::new(), + ran_too_much: setup.engine_code.1, + kept: Vec::new(), + recorded: 0, + #[cfg(unix)] + cleared: HashMap::new(), + }; + for hash in setup.engine_code.0 { + let _ = d.saw(hash); + } + if let Some(f) = fenced { + let own = d.scope.roots().to_vec(); + d.scope.fence(f.clone(), &own); + d.writes.fence(f, &[]); + } + if d.framed { + for g in d.stored() { + for (scope, granted) in [(&mut d.writes, g.write), (&mut d.scope, true)] { + match (granted, g.folder) { + (false, _) => {} + (true, true) => scope.add(g.path.clone()), + (true, false) => scope.add_file(g.path.clone()), + } + } + d.stored.push(g); + } + d.withdraw(); + } + d + } + + /// Notes that the run evaluates the source `units` (`eval`, `Function`, `$.evalFile`), before + /// it runs: the kept grants that were not kept for it are withdrawn. + pub(crate) fn saw_code(&mut self, units: &[u16]) { + if self.saw(code_hash(units)) { + self.withdraw(); + } + } + + /// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new. + fn saw(&mut self, hash: String) -> bool { + if self.ran_too_much || self.ran.contains(&hash) || self.own == hash { + return false; + } + if self.ran.len() >= MAX_RUN_CODE { + self.ran_too_much = true; + } else { + self.ran.insert(hash); + } + true + } + + /// What the run's code may run, for its named engine to keep: each source's SHA-256 (the + /// script's own included, also for a script given as text) and whether there was more than + /// [`MAX_RUN_CODE`]. + pub(crate) fn code(&self) -> (Vec, bool) { + (std::iter::once(self.own.clone()).chain(self.ran.iter().cloned()).collect(), self.ran_too_much) + } + + /// Withdraws each kept grant whose run did not evaluate every source this run has: its place + /// is no longer read or written, unless the run holds it some other way, and files opened for + /// writing there are written now and take no more writes. + fn withdraw(&mut self) { + let (ran, all) = (&self.ran, self.ran_too_much); + let (stay, gone): (Vec, Vec) = std::mem::take(&mut self.stored).into_iter().partition(|g| !all && ran.is_subset(&g.code)); + self.stored = stay; + if gone.is_empty() { + return; + } + for g in &gone { + let held = |write: bool| { + self.held.iter().any(|(p, w, f)| *p == g.path && *f == g.folder && (*w || !write)) + || self.stored.iter().any(|s| s.path == g.path && s.folder == g.folder && (s.write || !write)) + }; + if !held(false) { + self.scope.remove(&g.path, g.folder); + } + if g.write && !held(true) { + self.writes.remove(&g.path, g.folder); + } + } + let ids: Vec = + self.open.iter().filter(|(_, o)| o.target.as_deref().is_some_and(|t| !self.writes.allows(t))).map(|(id, _)| *id).collect(); + for id in ids { + let written = self.flush(id).is_ok(); + if let Some(o) = self.open.get_mut(&id) { + // Changes that could not be written stay, so the run's end tries them again and + // reports the file when it still cannot. + o.withdrawn = true; + if written { + o.target = None; + } + } + } + } + + /// Writes the evaluated code this run ran into the grants it kept with Always, so a later run + /// of the same script that evaluates the same code keeps them in force. A grant that cannot be + /// updated keeps the code it was kept with. + pub(crate) fn record_code(&mut self) { + if self.kept.is_empty() || self.ran_too_much || self.ran.len() == self.recorded { + return; + } + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; + let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); + let mut grants = read_store(&store); + for g in &mut grants { + let ours = g["script"] == *script + && g["sha256"] == *hash + && self.kept.iter().any(|(p, w, f)| g["path"] == *shown(p) && g["write"] == *w && g["folder"] == *f); + if ours { + g["code"] = serde_json::json!(code); + } + } + if write_store(&store, grants).is_ok() { + self.recorded = self.ran.len(); + } + } + + /// The gate for a command the script runs: the places it reads and writes now, and the files of + /// the open documents, `documents`. + pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents } + } + + /// The files written since this was last asked, to name in the report. + pub(crate) fn take_written(&mut self) -> Vec { + std::mem::take(&mut self.wrote) + } + + fn wrote(&mut self, real: &Path) { + let shown = crate::cmd::findfiles::plain(real.to_path_buf()).to_string_lossy().into_owned(); + if !self.wrote.contains(&shown) { + self.wrote.push(shown); + } + } + + /// Grants the real path `real`, a folder with everything in it (`folder`) or a file, for + /// reading, and with `write` for writing too. + fn grant(&mut self, real: std::path::PathBuf, write: bool, folder: bool) { + let scopes = if write { vec![&mut self.writes, &mut self.scope] } else { vec![&mut self.scope] }; + for scope in scopes { + if folder { scope.add(real.clone()) } else { scope.add_file(real.clone()) } + } + self.held.push((real, write, folder)); + } + + /// The run's temporary folder, made the first time it is asked for; `None` when it cannot be + /// made, when the automation write roots do not take it, and on the web. + fn temp_dir(&mut self) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + if self.temp.is_none() { + let base = std::env::temp_dir(); + let made = (0..64).find_map(|_| { + let n = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); + let dir = base.join(format!("VectorCraft Script {}-{n}", std::process::id())); + crate::file_access::check_write(&dir.to_string_lossy()).ok()?; + std::fs::create_dir(&dir).ok().and_then(|()| std::fs::canonicalize(&dir).ok()) + })?; + self.grant(made.clone(), true, true); + self.temp = Some(made); + } + self.temp.clone().map(crate::cmd::findfiles::plain) + } + + /// The script's data folder, made the first time it is asked for: for a script run from a file, + /// a folder named by the SHA-256 of its path in the data folder, and otherwise a folder in the + /// run's temporary folder. `None` when that folder is a link, cannot be made, or is outside the + /// automation write roots. + fn user_data_dir(&mut self) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + if self.user_data.is_none() { + let dir = match (&self.script, &self.data_dir) { + (Some((path, _)), Some(data)) => { + let key = vectorcraft_plugins::permissions::sha256_hex(path.to_string_lossy().as_bytes()); + data.join(key.get(..16).unwrap_or(&key)) + } + _ => self.temp_dir()?.join("userData"), + }; + crate::file_access::check_write(&dir.to_string_lossy()).ok()?; + // Each missing folder above it that is made on the way must be inside the write roots too. + for missing in dir.ancestors().skip(1).take_while(|a| !a.as_os_str().is_empty() && std::fs::symlink_metadata(a).is_err()) { + crate::file_access::check_write(&missing.to_string_lossy()).ok()?; + } + // The data folder that holds the folder, and then the folder, are folders where they are + // named, not links; the folder is made only once the data folder is checked. + let direct = |d: &Path| -> Option { + let (parent, name) = (std::fs::canonicalize(d.parent()?).ok()?, d.file_name()?); + let real = std::fs::canonicalize(d).ok()?; + (real == parent.join(name) && std::fs::symlink_metadata(d).is_ok_and(|m| m.is_dir())).then_some(real) + }; + std::fs::create_dir_all(dir.parent()?).ok()?; + direct(dir.parent()?)?; + std::fs::create_dir_all(&dir).ok()?; + let real = direct(&dir)?; + self.scope.fence_open(real.clone()); + self.writes.fence_open(real.clone()); + self.grant(real.clone(), true, true); + self.user_data = Some(real); + } + self.user_data.clone().map(crate::cmd::findfiles::plain) + } + + /// The grants file, beside the scripts' data folders. + fn store_path(&self) -> Option { + self.data_dir.as_ref().map(|d| d.with_file_name(GRANTS_FILE)) + } + + /// The grants the grants file keeps for this script with this text: each path, whether it may + /// be written, whether it is a folder, and the evaluated code it was kept for. A grant whose + /// path no longer is its own real path is left out. + fn stored(&self) -> Vec { + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Vec::new() }; + let script = shown(script); + read_store(&store) + .into_iter() + .filter(|g| g["script"] == *script && g["sha256"] == *hash) + .filter_map(|g| { + let code = g["code"].as_array()?.iter().map(|c| c.as_str().map(str::to_string)).collect::>()?; + let (write, folder) = (g["write"].as_bool()?, g["folder"].as_bool()?); + // The grant stays on the real path it was kept for: a path that now leads elsewhere, + // through a link put in its place or in a folder above it, is not granted. + let saved = g["path"].as_str()?; + let path = real_of(Path::new(saved)).filter(|real| shown(real) == saved)?; + Some(Stored { path, write, folder, code }) + }) + .filter(|g| self.fenced.as_ref().is_none_or(|f| !crate::file_access::path_inside(&g.path, f))) + .collect() + } + + /// Adds grants of `paths` (with `write`, folders when `folder`) for this script to the grants + /// file, with the code the run has evaluated so far, written whole to a file beside it that then + /// takes its place. + fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; + let mut grants = read_store(&store); + let script = shown(script); + let code: Vec<&String> = self.ran.iter().collect(); + for p in paths { + let path = shown(p); + grants + .retain(|g| !(g["script"] == *script && g["sha256"] == *hash && g["path"] == *path && g["write"] == write && g["folder"] == folder)); + grants.push(serde_json::json!({"script": script, "sha256": hash, "code": code, "path": path, "write": write, "folder": folder})); + } + if grants.len() > MAX_STORED_GRANTS { + return Err(NOT_SAVED); + } + write_store(&store, grants).map_err(|_| NOT_SAVED) + } + + /// The paths a person picked in the dialog the script waits at, allowed (`always`: kept for + /// later runs too), or denied; → what the dialog's call gives the script (a path, a list of + /// paths for an open dialog that picks more than one, `null`, or `{error}`), `None` when no + /// dialog waits. + pub(crate) fn answer(&mut self, answer: PickAnswer) -> Option { + let picker = self.picker.take()?; + let PickAnswer::Allow { paths, always } = answer else { return Some(Data::Null) }; + Some(self.allow(&picker, &paths, always).unwrap_or_else(error)) + } + + fn allow(&mut self, picker: &ScriptPicker, paths: &[String], always: bool) -> Result { + let wanted = if picker.multiple { paths.len().min(MAX_ENTRIES) } else { 1 }; + let mut reals = Vec::new(); + for p in paths.iter().take(wanted) { + reals.push(self.picked(picker.kind, p)?); + } + if reals.is_empty() { + return Ok(Data::Null); + } + let (write, folder) = (picker.kind != PickerKind::Open, picker.kind == PickerKind::Folder); + if always { + self.keep(&reals, write, folder)?; + self.kept.extend(reals.iter().map(|r| (r.clone(), write, folder))); + self.recorded = self.ran.len(); + } + let mut picked = Vec::new(); + for real in reals { + picked.push(Data::String(self.pathname(&shown(&real), &self.start, false).fs())); + self.grant(real, write, folder); + } + Ok(match picked.len() { + 1 if !picker.multiple => picked.swap_remove(0), + _ => Data::Array(picked), + }) + } + + /// The real path of `path`, which a person picked in a dialog of `kind`: a file that is there + /// (open), a folder that is there (folder), or a file whose folder is there (save). A network or + /// device path, and a place in the folder that holds the settings, are refused. + fn picked(&self, kind: PickerKind, path: &str) -> Result { + let p = self.checked(path)?; + if ScriptScope::refused_by_name(p) { + return Err(ACCESS_DENIED); + } + let real = match kind { + PickerKind::Save if std::fs::symlink_metadata(p).is_err() => { + let (Some(dir), Some(name)) = (p.parent(), p.file_name()) else { return Err(ACCESS_DENIED) }; + std::fs::canonicalize(dir).map_err(|_| NOT_FOUND)?.join(name) + } + _ => std::fs::canonicalize(p).map_err(|_| NOT_FOUND)?, + }; + match kind { + PickerKind::Folder if !real.is_dir() => return Err(NOT_FOUND), + PickerKind::Open if !real.is_file() => return Err(NOT_REGULAR), + PickerKind::Save if real.is_dir() => return Err(NOT_REGULAR), + _ => {} + } + if self.fenced.as_ref().is_some_and(|f| crate::file_access::path_inside(&real, f)) + && !self.user_data.as_ref().is_some_and(|u| crate::file_access::path_inside(&real, u)) + { + return Err(PROTECTED); + } + Ok(real) + } + + /// The real path writing to `path` writes, or why it may not ([`ScriptScope::target`]). + fn target(&self, path: &str, follow: bool) -> Result { + let p = self.checked(path)?; + match self.writes.target(p, follow) { + Ok(real) => Ok(real), + Err(ScriptRead::Failed(_)) => Err(WRITE_FAILED), + Err(_) => Err(ACCESS_DENIED), + } + } + + /// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`]. + fn charge_write(&mut self, n: usize) -> Result<(), HostError> { + self.written = self.written.saturating_add(n); + if self.written > MAX_RUN_BYTES { + return Err(HostError::Abort(OVER_RUN_WRITES.to_string())); + } + Ok(()) + } + + /// Opens the file at `path` for writing in `mode` (`w`, `e` or `a`). + fn open_write(&mut self, path: &str, encoding: &str, mode: &str) -> Result { + let fail = |m: &str| Err(HostError::Error(m.to_string())); + if self.open.len() >= MAX_OPEN { + return fail(TOO_MANY_OPEN); + } + let real = match self.target(path, true) { + Ok(real) => real, + Err(m) => return fail(m), + }; + let meta = std::fs::metadata(&real).ok(); + if meta.as_ref().is_some_and(|m| !m.is_file()) { + return fail(NOT_REGULAR); + } + if mode == "e" && meta.is_none() { + return fail(NOT_FOUND); + } + // Changes other open objects hold for the file are written before it is opened again, so + // they do not later replace what this one writes. + let ids: Vec = self.open.iter().filter(|(_, o)| o.target.as_deref() == Some(real.as_path())).map(|(id, _)| *id).collect(); + if let Err(m) = ids.iter().try_for_each(|id| self.flush(*id)) { + return fail(m); + } + let bytes = if mode == "w" || meta.is_none() { + // An encoding that is not one is refused before the file is emptied. + if Open::new(Vec::new(), encoding).is_none() { + return Err(HostError::Error(UNDECODABLE.to_string())); + } + if std::fs::File::create(&real).is_err() { + return fail(WRITE_FAILED); + } + self.wrote(&real); + Vec::new() + } else { + if meta.as_ref().is_some_and(|m| m.len() > MAX_FILE_BYTES as u64) { + return fail(TOO_LARGE); + } + // The bytes kept are read under the rules for reading. + let bytes = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { + Ok((at, bytes)) if at == real => bytes, + Ok(_) | Err(ScriptRead::Refused) => return fail(ACCESS_DENIED), + Err(ScriptRead::TooLarge) => return fail(TOO_LARGE), + Err(ScriptRead::Missing) => return fail(NOT_FOUND), + Err(ScriptRead::Failed(_)) => return fail(READ_FAILED), + }; + if bytes.len() > MAX_FILE_BYTES { + return fail(TOO_LARGE); + } + self.charge_read(&real, bytes.len())?; + bytes + }; + let mut file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; + if mode == "a" { + file.pos = file.bytes.len(); + } + file.read_from = Some(real.clone()); + file.target = Some(real); + Ok(self.insert(file)) + } + + fn insert(&mut self, file: Open) -> u32 { + let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + while id == 0 || self.open.contains_key(&id) { + id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + } + self.open.insert(id, file); + id + } + + /// Writes the open file `id`'s bytes to its file when it has changed. `Err` when it could not. + fn flush(&mut self, id: u32) -> Result<(), &'static str> { + let Some(file) = self.open.get_mut(&id) else { return Ok(()) }; + let Some(real) = file.target.clone().filter(|_| file.dirty) else { return Ok(()) }; + // A link put in the file's place, or in place of a folder above it, since it was opened is + // not written through. + let moved = real.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c != p)); + if moved || std::fs::symlink_metadata(&real).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(ACCESS_DENIED); + } + // The file stays changed until its bytes are written, so the run's end tries it again. + std::fs::write(&real, &file.bytes).map_err(|_| WRITE_FAILED)?; + file.dirty = false; + self.wrote(&real); + Ok(()) + } + + /// Writes every open file that has changed: at the end of the run. → the files that could not + /// be written, as the report gives them. + pub(crate) fn flush_all(&mut self) -> Vec { + // In the order the files were opened, so the object opened last writes a file last. + let mut ids: Vec = self.open.keys().copied().collect(); + ids.sort_unstable(); + let mut failed = Vec::new(); + for id in ids { + if self.flush(id).is_err() + && let Some(real) = self.open.get(&id).and_then(|o| o.target.as_deref()) + { + failed.push(shown(real)); + } + } + failed } /// The path `text` names from the folder `base`, a platform path; `text`'s URI escapes are @@ -150,30 +810,131 @@ impl Disk { if entry.len > MAX_FILE_BYTES as u64 { return fail(TOO_LARGE); } - if self.bytes.saturating_add(entry.len as usize) > MAX_RUN_BYTES { - return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); - } - let bytes = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { - Ok((_, bytes)) => bytes, + let (real, bytes) = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { + Ok(read) => read, Err(ScriptRead::TooLarge) => return fail(TOO_LARGE), Err(ScriptRead::Missing) => return fail(NOT_FOUND), Err(ScriptRead::Refused) => return fail(ACCESS_DENIED), Err(ScriptRead::Failed(_)) => return fail(READ_FAILED), }; - if self.bytes.saturating_add(bytes.len()) > MAX_RUN_BYTES { + self.charge_read(&real, bytes.len())?; + let mut file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; + file.read_from = Some(real); + Ok(self.insert(file)) + } + + /// Counts `n` bytes read from the file `real` in the run, which ends past [`MAX_RUN_BYTES`]. A + /// file opened again once no open object holds it counts only the bytes past the most read from + /// it before; while another object holds it, all of them count, as each holds its own copy. + fn charge_read(&mut self, real: &Path, n: usize) -> Result<(), HostError> { + let held = self.open.values().any(|o| o.read_from.as_deref() == Some(real)); + let before = if held { 0 } else { self.charged.get(real).copied().unwrap_or(0) }; + let more = n.saturating_sub(before); + if self.bytes.saturating_add(more) > MAX_RUN_BYTES { return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); } - self.bytes += bytes.len(); - let file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; - let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); - while id == 0 || self.open.contains_key(&id) { - id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + self.bytes += more; + if !held && n > before && (self.charged.contains_key(real) || self.charged.len() < MAX_CHARGED) { + self.charged.insert(real.to_path_buf(), n); } - self.open.insert(id, file); - Ok(id) + Ok(()) } } +/// The real path `real` as the grants file and the report give it. +fn shown(real: &Path) -> String { + crate::cmd::findfiles::plain(real.to_path_buf()).to_string_lossy().into_owned() +} + +/// The path `p` with its links followed; for a missing file whose folder is there, that folder's +/// real path and the file's name. +fn real_of(p: &Path) -> Option { + std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?))) +} + +/// The path `p` with its links followed, also when it is not there yet: the real path of the +/// nearest folder above it that is there, and the names below that folder. +fn real_or_planned(p: &Path) -> Option { + let mut names = Vec::new(); + let mut at = p; + loop { + if let Ok(real) = std::fs::canonicalize(at) { + return Some(names.iter().rev().fold(real, |real, name| real.join(name))); + } + names.push(at.file_name()?); + at = at.parent()?; + } +} + +/// The first `max` bytes of the file at `real`, and one more when it has more. +fn read_head(real: &Path, max: usize) -> std::io::Result> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(real)?.take(max as u64 + 1).read_to_end(&mut bytes)?; + Ok(bytes) +} + +/// The grants the grants file at `store` holds; none when it is missing or cannot be read. +fn read_store(store: &Path) -> Vec { + let Ok(bytes) = read_head(store, MAX_STORE_BYTES) else { return Vec::new() }; + if bytes.len() > MAX_STORE_BYTES { + return Vec::new(); + } + let Ok(v) = serde_json::from_slice::(&bytes) else { return Vec::new() }; + if v["version"] != 1 { + return Vec::new(); + } + let valid = |g: &serde_json::Value| { + g["script"].is_string() + && g["sha256"].is_string() + && g["code"].as_array().is_some_and(|c| c.iter().all(serde_json::Value::is_string)) + && g["path"].is_string() + && g["write"].is_boolean() + && g["folder"].is_boolean() + }; + v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default() +} + +/// Writes `grants` as the grants file at `store`: to a file beside it, which then takes its place. +/// `Err`, with the file left as it was, when the grants take more than [`MAX_STORE_BYTES`]. +fn write_store(store: &Path, grants: Vec) -> std::io::Result<()> { + let text = serde_json::to_vec_pretty(&serde_json::json!({"version": 1, "grants": grants})).map_err(std::io::Error::other)?; + if text.len() > MAX_STORE_BYTES { + return Err(std::io::Error::other("the grants file would be too large")); + } + if let Some(dir) = store.parent() { + std::fs::create_dir_all(dir)?; + } + let part = store.with_extension("json.part"); + std::fs::write(&part, text)?; + // `rename` replaces a grants file that is there, on Windows too (`MOVEFILE_REPLACE_EXISTING`). + std::fs::rename(&part, store).inspect_err(|_| { + let _ = std::fs::remove_file(&part); + }) +} + +/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of +/// its text, the path and whether it may be written (`script.grants`). +pub(crate) fn stored_grants(data_dir: &Path) -> Vec { + read_store(&data_dir.with_file_name(GRANTS_FILE)) +} + +/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path +/// `path`, of both when both are given and of every grant when neither is (`script.grants.revoke`). +/// → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result { + let store = data_dir.with_file_name(GRANTS_FILE); + let grants = read_store(&store); + let before = grants.len(); + let kept: Vec = + grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + let removed = before - kept.len(); + if removed > 0 { + write_store(&store, kept)?; + } + Ok(removed) +} + /// Whether paths are read as Windows reads them. const WINDOWS: bool = cfg!(windows); @@ -188,21 +949,20 @@ fn home_folder() -> String { std::env::var(var).unwrap_or_else(|_| if WINDOWS { r"C:\".to_string() } else { "/".to_string() }) } -/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none. -/// On the web every one is `null`, and no platform folder is looked up. -fn locations(home: &str) -> Data { +/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none: +/// `temp` and `user_data` are the run's own. On the web every one is `null`, and no platform folder +/// is looked up. +fn locations(home: &str, temp: Option, user_data: Option) -> Data { if cfg!(target_arch = "wasm32") { return Data::Object(PLACES.iter().map(|k| (k.to_string(), Data::Null)).collect()); } let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); let join = |a: &str, b: &str| Path::new(a).join(b).to_string_lossy().into_owned(); let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_string_lossy().into_owned())); - let temp = temp_folder().to_string_lossy().into_owned(); - let (user_data, app_data, common, system, trash) = if WINDOWS { - (env("APPDATA"), env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) + let (app_data, common, system, trash) = if WINDOWS { + (env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) } else if cfg!(target_os = "macos") { ( - Some(join(home, "Library/Application Support")), Some("/Library/Application Support".to_string()), Some("/Library/Application Support".to_string()), Some("/System".to_string()), @@ -210,7 +970,7 @@ fn locations(home: &str) -> Data { ) } else { let data = env("XDG_DATA_HOME").unwrap_or_else(|| join(home, ".local/share")); - (Some(data.clone()), Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) + (Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) }; let s = |v: Option| v.map_or(Data::Null, Data::String); let places = vec![ @@ -221,7 +981,7 @@ fn locations(home: &str) -> Data { ("myDocuments", Some(join(home, "Documents"))), ("startup", exe), ("system", system), - ("temp", Some(temp)), + ("temp", temp), ("trash", trash), ("userData", user_data), ]; @@ -231,7 +991,8 @@ fn locations(home: &str) -> Data { /// The names [`locations`] gives. const PLACES: [&str; 10] = ["appData", "appPackage", "commonFiles", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; -/// The folder for temporary files: the platform's, or on the web the root, where nothing is read. +/// The folder for temporary files when the run's own cannot be made: the platform's, or on the web +/// the root, where nothing is read. fn temp_folder() -> std::path::PathBuf { if cfg!(target_arch = "wasm32") { std::path::PathBuf::from("/") } else { std::env::temp_dir() } } @@ -395,31 +1156,44 @@ fn decode(s: &str) -> String { String::from_utf8(out).unwrap_or_else(|_| s.to_string()) } +/// Do file names match a mask without regard to case: on Windows and macOS, whose file systems +/// usually do not tell names apart by case. Elsewhere case matters. +const MASK_IGNORES_CASE: bool = cfg!(any(windows, target_os = "macos")); + /// A `getFiles` mask, where `*` stands for any run of characters and `?` for one, without regard -/// to case, read once for a whole listing. +/// to case where the file system does not tell names apart by case ([`MASK_IGNORES_CASE`]), read +/// once for a whole listing. struct Mask { - /// The mask in lower case, each run of `*` written as one. + /// The mask, in lower case when case does not matter, each run of `*` written as one. chars: Vec, /// How many of its characters are not `*`: a name with fewer characters does not match. fixed: usize, + /// Names are compared without regard to case. + fold: bool, } impl Mask { fn new(mask: &str) -> Self { + Self::with_case(mask, MASK_IGNORES_CASE) + } + + /// The mask `mask`, which compares names without regard to case when `fold`. + fn with_case(mask: &str, fold: bool) -> Self { let mut chars: Vec = Vec::new(); - for c in mask.to_lowercase().chars() { + let text = if fold { mask.to_lowercase() } else { mask.to_string() }; + for c in text.chars() { if !(c == '*' && chars.last() == Some(&'*')) { chars.push(c); } } let fixed = chars.iter().filter(|c| **c != '*').count(); - Self { chars, fixed } + Self { chars, fixed, fold } } /// Does `name` match, taking a step from `steps` for each character compared? `None` when the /// steps run out first. fn matches(&self, name: &str, steps: &mut usize) -> Option { - let n: Vec = name.to_lowercase().chars().collect(); + let n: Vec = if self.fold { name.to_lowercase().chars().collect() } else { name.chars().collect() }; if n.len() < self.fixed { return Some(false); } @@ -427,7 +1201,7 @@ impl Mask { } } -/// Does `n` match the lower-case mask `m`? `None` when `steps` run out first. +/// Does `n` match the mask `m`, both in the same case? `None` when `steps` run out first. fn matched(m: &[char], n: &[char], steps: &mut usize) -> Option { let (mut i, mut j, mut star, mut mark) = (0usize, 0usize, None, 0usize); while j < n.len() { @@ -488,6 +1262,30 @@ impl Encoding { }) } + /// `text` in this encoding; `None` when a character has no form in it. BINARY writes each + /// character's low byte. + fn encode(self, text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len()); + for c in text.chars() { + let code = u32::from(c); + match self { + Self::Utf8 => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()), + Self::Ascii if code < 0x80 => out.push(code as u8), + Self::Binary => out.push((code & 0xFF) as u8), + Self::Latin1 if code <= 0xFF => out.push(code as u8), + Self::Cp1252 if code < 0x80 || (0xA0..=0xFF).contains(&code) => out.push(code as u8), + Self::Cp1252 => out.push(0x80 + CP1252_HIGH.iter().position(|h| u32::from(*h) == code)? as u8), + Self::Utf16Le | Self::Utf16Be => { + for unit in c.encode_utf16(&mut [0; 2]) { + out.extend_from_slice(&if self == Self::Utf16Le { unit.to_le_bytes() } else { unit.to_be_bytes() }); + } + } + Self::Ascii | Self::Latin1 => return None, + } + } + Some(out) + } + fn name(self) -> &'static str { match self { Self::Utf8 => "UTF-8", @@ -501,12 +1299,20 @@ impl Encoding { } } -/// An opened file: its bytes, the byte position and the encoding it is read in. +/// An opened file: its bytes, the byte position and the encoding it is read in; for a file opened +/// for writing, the real path its bytes are written to and whether they changed since. struct Open { bytes: Vec, pos: usize, encoding: Encoding, name: String, + target: Option, + /// The real path of the file the object was opened on, whose bytes it holds. + read_from: Option, + dirty: bool, + /// The grant the file was opened under was withdrawn while its changes could not be written: + /// they are written again when the run ends, and the object takes no more writes. + withdrawn: bool, } impl Open { @@ -526,7 +1332,28 @@ impl Open { } else { (Encoding::Cp1252, 0) }; - Some(Self { bytes, pos, encoding, name: encoding.name().to_string() }) + Some(Self { bytes, pos, encoding, name: encoding.name().to_string(), target: None, read_from: None, dirty: false, withdrawn: false }) + } + + /// Writes `text` at the position, over what is there and past the end, when it takes at most + /// `left` bytes; → the bytes written. + fn write(&mut self, text: &str, left: usize) -> Result { + if self.target.is_none() || self.withdrawn { + return Err(NOT_WRITABLE); + } + let bytes = self.encoding.encode(text).ok_or(UNENCODABLE)?; + if bytes.len() > left { + return Err(OVER_RUN_WRITES); + } + let end = self.pos.saturating_add(bytes.len()); + if end.max(self.bytes.len()) > MAX_FILE_BYTES { + return Err(TOO_LARGE); + } + let over = end.min(self.bytes.len()); + self.bytes.splice(self.pos..over, bytes.iter().copied()); + self.pos = end; + self.dirty = true; + Ok(bytes.len()) } /// The character at byte `at` and its length in bytes; `Ok(None)` at the end, `Err` where the @@ -661,12 +1488,22 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem::Function(Rc::new(move |a| { let h = super::current(&l)?; bump(&h.counts.file_calls); - let r = f(&h, &a)?; + let r = f(&h, &a); + h.note_written(h.disk.borrow_mut().take_written()); + let r = r?; h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; Ok(r) })) } +/// `Ok(true)`, or `{error}` for a failure. +fn done(r: Result<(), &'static str>) -> Data { + match r { + Ok(()) => Data::Bool(true), + Err(m) => error(m), + } +} + fn handle(a: &[Data]) -> u32 { arg_number(a, 0).filter(|n| n.is_finite() && *n >= 0.0 && *n <= f64::from(u32::MAX)).map_or(0, |n| n as u32) } @@ -720,16 +1557,384 @@ fn stat(host: &Host, a: &[Data]) -> Result { }) } +/// `open(path, encoding, mode)`: `r` reads, `w`, `e` and `a` write. fn open(host: &Host, a: &[Data]) -> Result { - match host.disk.borrow_mut().open_file(&arg_text(a, 0), &arg_text(a, 1)) { + let (path, encoding, mode) = (arg_text(a, 0), arg_text(a, 1), arg_text(a, 2)); + let mut disk = host.disk.borrow_mut(); + let opened = match mode.as_str() { + "w" | "e" | "a" => disk.open_write(&path, &encoding, &mode), + _ => disk.open_file(&path, &encoding), + }; + match opened { Ok(id) => Ok(Data::Object(vec![("id".into(), Data::Number(f64::from(id)))])), Err(HostError::Error(m)) => Ok(error(&m)), Err(e) => Err(e), } } +/// Closes the open file, writing what changed: `true`, `false` when it was not open, or `{error}` +/// when it could not be written. A file that could not be written is kept for the run's end to +/// write again. fn close(host: &Host, a: &[Data]) -> Result { - Ok(Data::Bool(host.disk.borrow_mut().open.remove(&handle(a)).is_some())) + let mut disk = host.disk.borrow_mut(); + let id = handle(a); + Ok(match disk.flush(id) { + Err(m) => error(m), + Ok(()) => Data::Bool(disk.open.remove(&id).is_some()), + }) +} + +/// `write(id, text)`. A write past the run's limit ends the run and leaves the file as it was. +fn write(host: &Host, a: &[Data]) -> Result { + let text = arg_text(a, 1); + let mut disk = host.disk.borrow_mut(); + let left = MAX_RUN_BYTES.saturating_sub(disk.written); + let r = match disk.open.get_mut(&handle(a)) { + Some(file) => file.write(&text, left), + None => Err(NOT_OPEN), + }; + match r { + Ok(n) => { + disk.charge_write(n)?; + Ok(Data::Bool(true)) + } + Err(OVER_RUN_WRITES) => Err(HostError::Abort(OVER_RUN_WRITES.to_string())), + Err(m) => Ok(error(m)), + } +} + +/// `copy(from, to)`: the file `from` to `to`, replacing a file that is there. +fn copy(host: &Host, a: &[Data]) -> Result { + let (from, to) = (arg_text(a, 0), arg_text(a, 1)); + let mut disk = host.disk.borrow_mut(); + let source = match disk.stat(&from) { + Ok(Some(e)) if e.file => disk.checked(&from).ok().and_then(|p| disk.scope.locate(p).ok()), + Ok(Some(_)) => return Ok(error(NOT_REGULAR)), + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + }; + let Some(source) = source else { return Ok(error(ACCESS_DENIED)) }; + let target = match disk.target(&to, true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) { + return Ok(error(NOT_REGULAR)); + } + // A file copied onto itself, by its own name or by another link to it, is already its copy once + // its open objects are written, and copying could empty it. + let one = |t: &std::fs::Metadata| std::fs::metadata(&source).is_ok_and(|s| same_file((&source, &s), (&target, t))); + let itself = real_of(&target).is_some_and(|t| t == source) || std::fs::metadata(&target).is_ok_and(|t| one(&t)); + // The source's open objects write what they hold first, so the copy has it. + let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(source.as_path())).map(|(id, _)| *id).collect(); + if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { + return Ok(error(m)); + } + let n = std::fs::metadata(&source).map_or(0, |m| m.len()); + if n > MAX_FILE_BYTES as u64 { + return Ok(error(TOO_LARGE)); + } + // The target's open objects each take a copy of the bytes, which count as written too, as does + // the copy itself when it is written. + let holders = disk.open.values().filter(|o| o.target.as_deref() == Some(target.as_path())).count(); + disk.charge_write(usize::try_from(n).unwrap_or(usize::MAX).saturating_mul(holders.saturating_add(usize::from(!itself))))?; + let r = if itself { Ok(n) } else { std::fs::copy(&source, &target) }; + if !itself && (r.is_ok() || target.exists()) { + disk.wrote(&target); + } + // Open objects of the target hold the copy, so closing them does not write their older bytes. + if r.is_ok() && disk.open.values().any(|o| o.target.as_deref() == Some(target.as_path())) { + let copied = read_head(&target, MAX_FILE_BYTES).unwrap_or_default(); + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.bytes.clone_from(&copied); + file.pos = file.pos.min(copied.len()); + file.dirty = false; + } + } + Ok(done(r.map(drop).map_err(|_| WRITE_FAILED))) +} + +/// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. +fn remove(host: &Host, a: &[Data]) -> Result { + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), false) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = match std::fs::symlink_metadata(&target) { + Err(_) => Err(NOT_FOUND), + Ok(m) if m.is_dir() => std::fs::remove_dir(&target) + .map_err(|_| if std::fs::read_dir(&target).is_ok_and(|mut d| d.next().is_some()) { NOT_EMPTY } else { WRITE_FAILED }), + Ok(m) => std::fs::remove_file(&target).map_err(|_| WRITE_FAILED).inspect(|()| { + // A file made later in its place, which may take its inode, gets none of its write bits. + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if m.nlink() <= 1 { + disk.cleared.remove(&(m.dev(), m.ino())); + } + } + #[cfg(not(unix))] + let _ = m; + }), + }; + if r.is_ok() { + // Other open objects of the file drop their changes and take no more writes, so neither + // their close nor the run's end makes the file again. + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.dirty = false; + file.target = None; + } + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path. +fn rename(host: &Host, a: &[Data]) -> Result { + let (path, name) = (arg_text(a, 0), arg_text(a, 1)); + let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':'))); + if bad || name.contains('\0') { + return Ok(error(BAD_NAME)); + } + let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) }; + let mut disk = host.disk.borrow_mut(); + let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) { + (Ok(f), Ok(t)) => (f, t), + (Err(m), _) | (_, Err(m)) => return Ok(error(m)), + }; + let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) }; + // A folder that holds the settings folder is not moved, also when its name is given in another + // case where case does not matter. + let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept)); + if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) { + return Ok(error(ACCESS_DENIED)); + } + // A name that differs in case alone may name the same file, which then takes the new name. + if let Ok(there) = std::fs::symlink_metadata(&to) + && !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there))) + { + return Ok(error(NAME_TAKEN)); + } + if std::fs::rename(&from, &to).is_err() { + return Ok(error(WRITE_FAILED)); + } + // Open objects of the file, or of files in the folder, write to the new path. + for file in disk.open.values_mut() { + if let Some(rest) = file.target.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); + } + } + disk.wrote(&to); + Ok(Data::Object(vec![("fs".into(), Data::String(new))])) +} + +/// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on +/// Windows by volume and file index, with links followed; elsewhere by the paths with their links +/// followed, which give the name as the file system keeps it. +fn same_file(a: (&Path, &std::fs::Metadata), b: (&Path, &std::fs::Metadata)) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + a.1.dev() == b.1.dev() && a.1.ino() == b.1.ino() + } + #[cfg(windows)] + { + ::same_file::is_same_file(a.0, b.0).unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + matches!((std::fs::canonicalize(a.0), std::fs::canonicalize(b.0)), (Ok(x), Ok(y)) if x == y) + } +} + +/// `create(path)`: the folder, with the folders above it that are missing. +fn create(host: &Host, a: &[Data]) -> Result { + let disk = host.disk.borrow(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + // Each missing folder above it that is made on the way must be a place the script may write too. + let outside = target.ancestors().skip(1).take_while(|a| !a.as_os_str().is_empty() && std::fs::symlink_metadata(a).is_err()).any(|a| { + !disk.writes.allows(a) || crate::file_access::check_write(&crate::cmd::findfiles::plain(a.to_path_buf()).to_string_lossy()).is_err() + }); + if outside { + return Ok(error(ACCESS_DENIED)); + } + Ok(done(std::fs::create_dir_all(&target).map_err(|_| WRITE_FAILED))) +} + +/// `setLength(path, length)`: the file cut or padded with zero bytes to `length` bytes. +fn set_length(host: &Host, a: &[Data]) -> Result { + let n = arg_number(a, 1).filter(|n| n.is_finite() && *n >= 0.0).map_or(0, |n| n as u64); + if n > MAX_FILE_BYTES as u64 { + return Ok(error(TOO_LARGE)); + } + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = match std::fs::metadata(&target) { + Err(_) => Err(NOT_FOUND), + Ok(m) if !m.is_file() => Err(NOT_REGULAR), + Ok(m) => { + // Each open object of the file holds its own bytes, so what each one grows by counts too. + let len = usize::try_from(n).unwrap_or(usize::MAX); + let held = disk + .open + .values() + .filter(|o| o.target.as_deref() == Some(target.as_path())) + .fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); + disk.charge_write(usize::try_from(n.saturating_sub(m.len())).unwrap_or(usize::MAX).saturating_add(held))?; + // The file's open objects write what they hold first, and then hold the new length. + let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); + ids.iter() + .try_for_each(|id| disk.flush(*id)) + .and_then(|()| std::fs::OpenOptions::new().write(true).open(&target).and_then(|f| f.set_len(n)).map_err(|_| WRITE_FAILED)) + } + }; + if r.is_ok() { + let len = usize::try_from(n).unwrap_or(usize::MAX); + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.bytes.resize(len, 0); + file.pos = file.pos.min(len); + } + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `setReadonly(path, readonly)`. +fn set_readonly(host: &Host, a: &[Data]) -> Result { + let on = matches!(a.get(1), Some(Data::Bool(true))); + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = std::fs::metadata(&target).map_err(|_| NOT_FOUND).and_then(|m| { + let mut p = m.permissions(); + // On Unix setting it clears every write bit; clearing it gives back the bits this run + // cleared from the file, or else the owner's write bit. + #[cfg(unix)] + let (back, file) = { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let (mode, file) = (p.mode(), (m.dev(), m.ino())); + // Saved bits are given back only to a file that is still without write bits. + let saved = disk.cleared.get(&file).copied().filter(|_| mode & 0o222 == 0); + let back = if on { mode & 0o222 } else { saved.unwrap_or(0o200) }; + p.set_mode(if on { mode & !0o222 } else { mode | back }); + (back, file) + }; + #[cfg(not(unix))] + p.set_readonly(on); + std::fs::set_permissions(&target, p).map_err(|_| WRITE_FAILED)?; + #[cfg(unix)] + if !on { + disk.cleared.remove(&file); + } else if back != 0 && (disk.cleared.len() < MAX_ENTRIES || disk.cleared.contains_key(&file)) { + disk.cleared.insert(file, back); + } + Ok(()) + }); + if r.is_ok() { + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `pick(kind, prompt, multiple, start)`: the file dialog of `kind` (`open`, `save` or `folder`), +/// which the run waits at in the app; elsewhere `{error}`. +fn pick(host: &Host, a: &[Data]) -> Result { + let kind = match arg_text(a, 0).as_str() { + "open" => PickerKind::Open, + "save" => PickerKind::Save, + _ => PickerKind::Folder, + }; + if cfg!(target_arch = "wasm32") { + return Ok(error(NO_WEB)); + } + let mut disk = host.disk.borrow_mut(); + if !disk.framed { + return Ok(error(NO_PICKER)); + } + if !host.can_wait.get() { + let name = match kind { + PickerKind::Open => "File.openDialog", + PickerKind::Save => "File.saveDialog", + PickerKind::Folder => "Folder.selectDialog", + }; + return Err(HostError::Error(format!( + "{name}: a file 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" + ))); + } + let prompt = super::dialogs::cut_to(&arg_text(a, 1), super::dialogs::MAX_MESSAGE_BYTES).to_string(); + let start = Some(arg_text(a, 3)).filter(|s| !s.is_empty() && !too_long(s)); + let can_always = disk.script.is_some() && disk.data_dir.is_some(); + let multiple = kind == PickerKind::Open && matches!(a.get(2), Some(Data::Bool(true))); + let filters = if kind == PickerKind::Folder { Vec::new() } else { dialog_filters(&arg_text(a, 4)) }; + disk.picker = Some(ScriptPicker { kind, prompt, multiple, start, filters, can_always }); + Err(HostError::Wait) +} + +/// The most file types a dialog's filter gives, and the most extensions of one. +const MAX_FILTERS: usize = 32; +/// The most characters of a dialog's filter that are read. +const MAX_FILTER_CHARS: usize = 4096; + +/// The file types of a dialog's `filter`, a string such as `"JavaScript:*.jsx;All files:*.*"`: +/// each `name:pattern` starts a type, a pattern without a name adds to the type before it (the +/// first one starts a type named by the patterns), and patterns are separated by `,` or `;`. A +/// `*.ext` pattern gives the extension `ext`, and `*` and `*.*` give `*`, every file; other patterns +/// are left out, and so is a type left without extensions. Only types that give every file: none +/// (every file). +pub(crate) fn dialog_filters(filter: &str) -> Vec<(String, Vec)> { + let filter: String = filter.chars().take(MAX_FILTER_CHARS).collect(); + let mut out: Vec<(String, Vec)> = Vec::new(); + // Whether the last type was started by a pattern without a name, and is named by its patterns. + let mut unnamed = false; + for piece in filter.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { + let (name, pattern) = match piece.split_once(':') { + Some((n, p)) => (Some(n.trim()), p.trim()), + None => (None, piece), + }; + let ext = match pattern { + "*" | "*.*" => Some("*".to_string()), + p => p + .strip_prefix("*.") + .filter(|e| !e.is_empty() && e.len() <= 32 && e.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))) + .map(str::to_string), + }; + match (name, out.last_mut()) { + (Some(n), _) => { + out.push((if n.is_empty() { pattern.to_string() } else { n.to_string() }, Vec::new())); + unnamed = false; + } + (None, None) => { + out.push((pattern.to_string(), Vec::new())); + unnamed = true; + } + (None, Some((name, _))) if unnamed && ext.is_some() && name.len() < 256 => { + name.push(';'); + name.push_str(pattern); + } + (None, Some(_)) => {} + } + if let (Some(ext), Some((_, exts))) = (ext, out.last_mut()) + && exts.len() < MAX_FILTERS + && !exts.contains(&ext) + { + exts.push(ext); + } + } + out.retain(|(_, exts)| !exts.is_empty()); + out.truncate(MAX_FILTERS); + if out.iter().all(|(_, exts)| exts.iter().all(|e| e == "*")) { + return Vec::new(); + } + out } fn read(host: &Host, a: &[Data]) -> Result { @@ -849,15 +2054,24 @@ fn execute(host: &Host, _: &[Data]) -> Result { Ok(error(NO_EXECUTE)) } +/// A name for a new file in the run's temporary folder. fn temp_name(host: &Host, _: &[Data]) -> Result { let mut disk = host.disk.borrow_mut(); disk.temps += 1; let name = format!("vc{:05}.tmp", disk.temps); - Ok(Data::String(temp_folder().join(name).to_string_lossy().into_owned())) + let dir = disk.temp_dir().unwrap_or_else(temp_folder); + Ok(Data::String(dir.join(name).to_string_lossy().into_owned())) } -fn locations_of(host: &Host, _: &[Data]) -> Result { - Ok(locations(&host.disk.borrow().home)) +/// `locations(place)`: the folders [`locations`] gives. The run's temporary folder and the script's +/// data folder are made only when `place` names them. +fn locations_of(host: &Host, a: &[Data]) -> Result { + let place = arg_text(a, 0); + let mut disk = host.disk.borrow_mut(); + let shown = |p: Option| p.map(|p| p.to_string_lossy().into_owned()); + let temp = if place == "temp" { shown(disk.temp_dir()) } else { None }; + let user_data = if place == "userData" { shown(disk.user_data_dir()) } else { None }; + Ok(locations(&disk.home, temp, user_data)) } fn encode_text(_: &Host, a: &[Data]) -> Result { @@ -890,9 +2104,10 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr let value = |s: &str| HostItem::Value(Data::String(s.to_string())); let text = HostItem::Object(vec![ ("notOpen".into(), value(NOT_OPEN)), - ("noWrites".into(), value(NO_WRITES)), - ("noPicker".into(), value(NO_PICKER)), ("badMode".into(), value(BAD_MODE)), + ("noAlias".into(), value(NO_ALIAS)), + ("noHidden".into(), value(NO_HIDDEN)), + ("tooLarge".into(), value(TOO_LARGE)), ]); let system = if WINDOWS { "Windows" @@ -903,6 +2118,7 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr }; let items = vec![ ("text".into(), text), + ("maxWrite".into(), HostItem::Value(Data::Number(MAX_FILE_BYTES as f64))), ("system".into(), value(system)), ("lineFeed".into(), value(if WINDOWS { "Windows" } else { "Unix" })), ("current".into(), unchecked(start_folder)), @@ -927,6 +2143,14 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("list".into(), call(link, list)), ("resolve".into(), call(link, resolve)), ("execute".into(), call(link, execute)), + ("write".into(), call(link, write)), + ("copy".into(), call(link, copy)), + ("remove".into(), call(link, remove)), + ("rename".into(), call(link, rename)), + ("create".into(), call(link, create)), + ("setLength".into(), call(link, set_length)), + ("setReadonly".into(), call(link, set_readonly)), + ("pick".into(), call(link, pick)), ]; realm.define_file_classes(items) } @@ -985,7 +2209,7 @@ mod tests { #[test] fn masks_match_stars_and_question_marks_without_case() { - let matches = |mask: &str, name: &str| Mask::new(mask).matches(name, &mut { usize::MAX }) == Some(true); + let matches = |mask: &str, name: &str| Mask::with_case(mask, true).matches(name, &mut { usize::MAX }) == Some(true); assert!(matches("*.JSX", "a.jsx")); assert!(matches("a?c*", "abcdef")); assert!(!matches("*.txt", "a.jsx")); @@ -995,6 +2219,17 @@ mod tests { assert!(!matches("?", "")); } + #[test] + fn masks_match_case_where_the_file_system_tells_names_apart_by_case() { + let matches = |mask: &str, name: &str| Mask::with_case(mask, false).matches(name, &mut { usize::MAX }) == Some(true); + assert!(!matches("*.JSX", "a.jsx")); + assert!(matches("*.JSX", "a.JSX")); + assert!(matches("A?c*", "Abcdef")); + assert!(!matches("A?c*", "abcdef")); + assert_eq!(MASK_IGNORES_CASE, cfg!(any(windows, target_os = "macos"))); + assert_eq!(Mask::new("*.JSX").matches("a.jsx", &mut { usize::MAX }), Some(MASK_IGNORES_CASE)); + } + #[test] fn masks_stop_when_their_steps_run_out() { let mask = Mask::new(&format!("*{}b", "a".repeat(100))); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 53f6e18f75..8b4a0294d2 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -37,7 +37,8 @@ //! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the //! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`. //! -//! `File` and `Folder` read files inside the script's own folder ([`files`]). +//! `File` and `Folder` read files inside the script's own folder, and write in the run's temporary +//! folder, the script's data folder and what a person allowed it in a file dialog ([`files`]). //! //! A script with `#targetengine name` runs in that named engine, which the session keeps with the //! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each @@ -102,6 +103,31 @@ pub const MAX_ARGS_BYTES: usize = 1 << 20; const SLICE_HOST_CALLS: u32 = 256; /// The bytes that may cross between a script and the host in one run. const MAX_BRIDGE_BYTES: u64 = 4 << 30; +/// The most files a run's report names in `written`; past them the report has `writtenMore`. +pub const MAX_WRITTEN: usize = 4096; + +/// The files a run wrote, as its report names them: at most [`MAX_WRITTEN`], each once, in the +/// order they were first written, and whether it wrote more. +#[derive(Default)] +struct Written { + paths: Vec, + seen: std::collections::HashSet, + more: bool, +} + +impl Written { + fn add(&mut self, path: String) { + if self.seen.contains(&path) { + return; + } + if self.paths.len() >= MAX_WRITTEN { + self.more = true; + return; + } + self.seen.insert(path.clone()); + self.paths.push(path); + } +} /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; @@ -255,9 +281,29 @@ struct KeptMap { struct KeptMaps { maps: std::collections::VecDeque, bytes: usize, + /// The SHA-256 of each source the engine's runs compiled (their scripts and what they + /// evaluated), at most [`MAX_ENGINE_CODE`], and whether there were more: a later run's kept file + /// grants are in force only for code they were kept for ([`files::Disk`]). + code: std::collections::BTreeSet, + code_full: bool, } +/// The most sources whose SHA-256 a named engine keeps. +pub const MAX_ENGINE_CODE: usize = 1024; + impl KeptMaps { + /// Adds the sources `code` (and whether a run had more than it counted) to the engine's code. + fn keep_code(&mut self, (code, more): (Vec, bool)) { + self.code_full |= more; + for hash in code { + if self.code.len() >= MAX_ENGINE_CODE && !self.code.contains(&hash) { + self.code_full = true; + } else { + self.code.insert(hash); + } + } + } + fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option>) { let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len()); let limit = kept_map_bytes(); @@ -696,7 +742,7 @@ struct Host { waiting: Cell, log: RefCell>, log_bytes: Cell, - written: RefCell>, + written: RefCell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, name: Arc, @@ -813,6 +859,7 @@ impl Host { return; } let mut kept = kept.borrow_mut(); + kept.keep_code(self.disk.borrow().code()); kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone())); for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() { match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) { @@ -884,6 +931,35 @@ impl Host { Some(left) } + /// Adds `paths`, files the script's `File` and `Folder` objects wrote, to the report's `written`. + fn note_written(&self, paths: Vec) { + let mut written = self.written.borrow_mut(); + for path in paths { + written.add(path); + } + } + + /// Adds `writtenMore: true` to `report` when the run wrote more files than its `written` names. + fn more_written(&self, report: &mut Value) { + if self.written.borrow().more + && let Some(o) = report.as_object_mut() + { + o.insert("writtenMore".into(), json!(true)); + } + } + + /// Writes the files the script left open and adds every file written to the report's `written`. + /// → the files it could not write. + fn flush_files(&self) -> Vec { + let mut disk = self.disk.borrow_mut(); + let failed = disk.flush_all(); + disk.record_code(); + let paths = disk.take_written(); + drop(disk); + self.note_written(paths); + failed + } + fn over(&self, limit: &str) -> HostError { HostError::Abort(limit.to_string()) } @@ -1100,13 +1176,13 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - let r = s.execute(id, params); + // The command reads and writes only where the script's own files may, and the open documents' files. + let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); + let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); for path in crate::file_access::finish_recording_writes(r.is_ok()) { - if !written.contains(&path) { - written.push(path); - } + written.add(path); } drop(written); match r { @@ -1664,6 +1740,32 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' + /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no + /// longer waits. + pub fn script_picker(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.disk.borrow().picker.clone())).flatten() + } + + /// Gives the file dialog the running script waits at its answer: the paths the person picked + /// and allowed, or a denial. The next [`Session::script_pump`] goes on from the call. → false + /// when no file dialog waits. + pub fn script_pick(&mut self, answer: files::PickAnswer) -> bool { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false }; + with_job(k, |j| { + let Some(data) = j.host.disk.borrow_mut().answer(answer) else { return false }; + j.host.note_written(j.host.disk.borrow_mut().take_written()); + if let Err(e) = j.realm.answer(data) { + j.host.disk.borrow_mut().failed = Some(e); + } + true + }) + .unwrap_or(false) + } + /// The name of the running script. pub fn script_name(&self) -> Option { self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone())) @@ -1790,7 +1892,17 @@ impl Session { realm.set_limits(limits); realm } - None => Realm::with_options(options, limits), + None => { + let mut realm = Realm::with_options(options, limits); + // Code the run evaluates withdraws the kept file grants not kept for it, before it runs. + let l = link.clone(); + realm.observe_code(move |units| { + if let Ok(h) = current(&l) { + h.disk.borrow_mut().saw_code(units); + } + }); + realm + } }; realm.share_interrupt(&self.script_stop); realm.set_data_limits(DataLimits::default()); @@ -1810,7 +1922,7 @@ impl Session { waiting: Cell::new(false), log: RefCell::new(Vec::new()), log_bytes: Cell::new(0), - written: RefCell::new(Vec::new()), + written: RefCell::new(Written::default()), run: self.script_runs, name: console::line_name(&name), console: RefCell::default(), @@ -1819,7 +1931,20 @@ impl Session { commands: RefCell::default(), run_nanos: Cell::new(0), dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers), - disk: RefCell::new(files::Disk::new(files.scope())), + disk: RefCell::new(files::Disk::new( + files.scope(), + files::Setup { + framed: self.script_frames, + script: request.file.clone(), + // The text with its included files, so a changed included file asks again. + source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()), + data_dir: self.script_data_dir.clone(), + engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| { + let m = m.borrow(); + (m.code.iter().cloned().collect(), m.code_full) + }), + }, + )), files: RefCell::new(files), script_map: RefCell::default(), eval_maps: RefCell::default(), @@ -1902,14 +2027,16 @@ impl Session { self.script_gone(key, console::Ending::Internal); return Some(Err(EngineError::Other(JOB_GONE.to_string()))); }; - if let Some(e) = job.host.dialogs.take_failure() { + let picker_failed = job.host.disk.borrow_mut().failed.take(); + if let Some(e) = job.host.dialogs.take_failure().or(picker_failed) { return Some(self.script_failed(job, &e)); } // A canceled request ends a sleep or a wait at this pump. if vectorcraft_doc::cancel::check().is_err() { self.script_stop.set(); } - if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() { + let picking = job.host.disk.borrow().picker.is_some(); + if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting() || picking) && !self.script_stop.is_set() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); self.script_key = Some(key); return None; @@ -1949,6 +2076,9 @@ impl Session { fn script_failed(&mut self, job: Job, e: &RunError) -> Result { job.host.dialogs.stopped(); + job.host.disk.borrow_mut().picker = None; + // The run fails already; a file it could not write is left out of `written`. + let _ = job.host.flush_files(); let fuel_left = job.realm.fuel_left(); let (e, file) = located(&job.host, &job.realm, e); let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); @@ -1966,6 +2096,12 @@ impl Session { /// Makes the working copy the session's state: one undo step for each document whose art /// changed, nothing for the others. fn script_commit(&mut self, mut job: Job) -> Result { + let unwritten = job.host.flush_files(); + if !unwritten.is_empty() { + let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", ")); + let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 }; + return self.script_failed(job, &e); + } // The working copy goes into the session; `job.world` holds the state before the run. job.world.swap(self); self.prefs = merged_prefs(&job.world.start_prefs, &self.prefs, &job.world.choices.prefs); @@ -2029,11 +2165,12 @@ impl Session { "ok": true, "name": job.name, "changed": changed_names, - "written": *host.written.borrow(), + "written": host.written.borrow().paths, "log": *host.log.borrow(), "fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(), "hostCalls": host.calls.get(), }); + host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); @@ -2060,6 +2197,7 @@ impl Session { const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; const INVALID_RESULT: &str = "the script left a document that cannot be kept"; +const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written"; const JOB_GONE: &str = "the script's run is no longer available"; const HISTORY_LOST: &str = "a failed command changed undo steps that could not be put back, so the script was stopped"; // Text a script reads from the errors it catches, or that ends its run with its name and place. @@ -2088,12 +2226,13 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue "name": name, "line": e.line, "column": e.column, - "written": *host.written.borrow(), + "written": host.written.borrow().paths, "log": *host.log.borrow(), "fuelLeft": fuel_left, "fuelUsed": fuel_used, "hostCalls": host.calls.get(), }); + host.more_written(&mut report); if let (Some(file), Some(o)) = (file, report.as_object_mut()) { o.insert("file".into(), json!(file)); } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 3e9ae56423..865d822652 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -90,6 +90,7 @@ impl Session { plugin_dir: None, scripts_dir: None, new_doc_profile_dir: None, + script_data_dir: None, plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e056ea2f7c..0d09bd2796 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1,6 +1,7 @@ //! `File` and `Folder` in a script: their classes and names, reading inside the script's own folder, -//! the paths refused before anything is looked up, the read limits, and the parts that write, which -//! are not available. +//! the paths refused before anything is looked up, the read limits, writing in the run's temporary +//! folder, the script's data folder and what a person allowed in a file dialog, and the grants kept +//! for a script. use std::path::{Path, PathBuf}; @@ -267,10 +268,12 @@ fn script_file_oversize_refused_before_read() { #[test] fn script_files_read_at_most_32_mib_in_a_run() { let base = folder("total"); - write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + for i in 0..5 { + write(&base.join(format!("main/seven{i}.bin")), &vec![b'a'; 7 << 20]); + } let mut s = Session::new(); let main = base.join("main/main.jsx"); - write(&main, b"var f = new File('seven.bin'); for (var i = 0; i < 5; i++) { f.open('r'); vc.log(i); }"); + write(&main, b"for (var i = 0; i < 5; i++) { new File('seven' + i + '.bin').open('r'); vc.log(i); }"); let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})); assert!(e.is_err(), "the fifth open passes 32 MiB"); let report = s.script_report().unwrap(); @@ -279,6 +282,23 @@ fn script_files_read_at_most_32_mib_in_a_run() { let _ = std::fs::remove_dir_all(base); } +/// A file opened again once its objects closed counts only once toward the 32 MiB a run reads, and +/// a file open in two objects at once counts for each. +#[test] +fn script_file_opened_again_counts_once_toward_the_run_limit() { + let base = folder("reopencount"); + write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write(&main, b"var f = new File('seven.bin'); for (var i = 0; i < 8; i++) { f.open('r'); f.close(); } vc.log('again');"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["again"])); + write(&main, b"for (var i = 0; i < 5; i++) { new File('seven.bin').open('r'); vc.log(i); }"); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects hold five copies"); + assert_eq!(s.script_report().unwrap()["log"], json!([0, 1, 2, 3])); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_files_have_at_most_256_open() { let base = folder("open"); @@ -311,7 +331,9 @@ fn script_folder_getfiles_stays_inside_scope() { try { d.getFiles(function () { throw new Error('stop'); }); } catch (e) { vc.log(e.message); }\n\ vc.log([new Folder('nope').getFiles(), d.getFiles('*.jsx')[0] instanceof File]);", ); - assert_eq!(log, json!([["C.JSX", "a.jsx", "main.jsx"], ["sub"], [["b.txt"], 5, null, DENIED], "stop", [null, true]])); + // Where case does not matter to the file system, the mask matches without regard to case. + let jsx = if cfg!(any(windows, target_os = "macos")) { json!(["C.JSX", "a.jsx", "main.jsx"]) } else { json!(["a.jsx", "main.jsx"]) }; + assert_eq!(log, json!([jsx, ["sub"], [["b.txt"], 5, null, DENIED], "stop", [null, true]])); let many = base.join("main/many"); for i in 0..=crate::script::files::MAX_ENTRIES { write(&many.join(format!("{i:04}.txt")), b""); @@ -393,23 +415,28 @@ fn script_file_encoding_binary_ascii() { let _ = std::fs::remove_dir_all(base); } +/// A script's own folder is only read: writing there, and anywhere it was not given, is refused, +/// and with nobody to ask its file dialogs give `null`. Aliases and `execute` are not available. #[test] -fn script_file_writes_dialogs_and_execute_are_not_available() { +fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { let base = folder("writes"); write(&base.join("main/keep.txt"), b"keep"); + let outside = base.join("outside.txt").to_string_lossy().into_owned(); let r = run( &base, - "var f = new File('keep.txt'); var n = new File('new.txt');\n\ - var out = [n.open('w'), n.error, f.open('a'), f.open('e'), f.open('x'), f.error, f.write('x'), f.remove(), f.copy('c.txt'), f.rename('r.txt')];\n\ - out.push(new Folder('made').create(), f.openDlg(), f.error, File.openDialog(), Folder.selectDialog(), f.execute(), f.error);\n\ - f.hidden = true; out.push(f.error, f.hidden); f.error = ''; out.push(f.error);\n\ - vc.log(out);", + &format!( + "var f = new File('keep.txt'); var n = new File('new.txt'); var o = new File({outside:?});\n\ + var out = [n.open('w'), n.error, f.open('a'), f.open('e'), f.open('x'), f.error, f.remove(), f.copy('c.txt'), f.rename('r.txt'), o.open('w')];\n\ + out.push(new Folder('made').create(), f.openDlg(), f.error, File.openDialog(), Folder.selectDialog(), f.execute(), f.error);\n\ + f.hidden = true; out.push(f.error, f.hidden, f.createAlias('l'), f.error); f.error = ''; out.push(f.error);\n\ + vc.log(out);" + ), ); assert_eq!( r["log"], json!([[ false, - "Script file writing is not available", + DENIED, false, false, false, @@ -420,20 +447,1222 @@ fn script_file_writes_dialogs_and_execute_are_not_available() { false, false, null, - "Script file dialogs are not available", + "Script file dialogs need a person to answer them", null, null, false, "Script files cannot be opened in another application", - "Script file writing is not available", + "Script file hidden setting cannot be changed", false, + false, + "Script files cannot make aliases", "" ]]) ); assert_eq!(r["hostCallCounts"]["fileExecutes"], 1); - assert!(r["hostCallCounts"]["fileCalls"].as_u64().unwrap() > 0); + assert_eq!(r["written"], json!([])); assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); assert!(!base.join("main/new.txt").exists() && !base.join("main/made").exists() && !base.join("main/c.txt").exists()); + assert!(!Path::new(&outside).exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn with_data(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run_in(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// `Folder.userData` is the script's own folder, kept between runs, and `Folder.temp` the run's, +/// deleted when it ends. `write` joins its values, `writeln` adds the `lineFeed`'s line end, and a +/// byte order mark is written as the script writes it. +#[test] +fn script_files_write_in_the_temporary_and_data_folders() { + let base = folder("userdata"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var out = [], u = new File(Folder.userData.fsName + '/notes.txt');\n\ + out.push(u.open('w'), u.write('a', 1, true), u.writeln('b'), u.close());\n\ + u.lineFeed = 'Windows'; out.push(u.open('a'), u.writeln('c'), u.close());\n\ + u.open('r'); out.push(u.read()); u.close();\n\ + var t = new File(Folder.temp.fsName + '/t.txt'); out.push(t.open('w'), t.write('\\uFEFFx'), t.close(), t.length);\n\ + var m = new File(); out.push(m.open('w'), m.parent.fsName === Folder.temp.fsName);\n\ + vc.log(out); vc.log(u.fsName); vc.log(Folder.temp.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, "a1trueb\nc\r\n", true, true, true, 4, true, true])); + let notes = PathBuf::from(r["log"][1].as_str().unwrap()); + let temp = PathBuf::from(r["log"][2].as_str().unwrap()); + assert_eq!(std::fs::read(¬es).unwrap(), b"a1trueb\nc\r\n"); + assert!(notes.starts_with(std::fs::canonicalize(base.join("settings/Script Data")).unwrap()), "{notes:?}"); + assert!(!temp.exists(), "the run's temporary folder is deleted when it ends"); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(written.contains(¬es.to_string_lossy().as_ref()), "{written:?}"); + let again = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/notes.txt'); u.open('r'); vc.log(u.read());").unwrap(); + assert_eq!(again["log"], json!(["a1trueb\nc\r\n"]), "a script's data folder is kept between runs"); + let _ = std::fs::remove_dir_all(base); +} + +/// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a +/// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and +/// `readonly`. +#[test] +fn script_file_modes_encodings_and_changes() { + let base = folder("changes"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + var e = new File(d + '/missing.txt'); out.push(e.open('e'), e.error);\n\ + var a = new File(d + '/a.txt'); a.encoding = 'ASCII'; out.push(a.open('w'), a.write('caf\\u00e9'), a.error, a.write('cafe'), a.close(), a.length);\n\ + var b = new File(d + '/b.bin'); b.encoding = 'BINARY'; b.open('w'); b.write('\\u0141B'); b.close();\n\ + b.encoding = 'BINARY'; b.open('r'); out.push(b.read()); b.close();\n\ + out.push(a.copy(d + '/b.bin'), new File(d + '/b.bin').length);\n\ + var f = new Folder(d + '/x/y'); out.push(f.create(), f.exists);\n\ + var x = new Folder(d + '/x'); out.push(x.remove(), x.error, f.remove(), f.exists);\n\ + out.push(a.rename('b.bin'), a.error, a.rename('c.txt'), a.name, a.exists, new File(d + '/a.txt').exists);\n\ + a.length = 2; out.push(a.length); a.length = 6; out.push(a.length);\n\ + a.readonly = true; out.push(a.readonly); a.readonly = false; out.push(a.readonly);\n\ + out.push(a.remove(), a.exists);\n\ + vc.log(out);", + ); + assert_eq!( + r["log"], + json!([[ + false, + "Script file does not exist", + true, + false, + "Script file cannot encode the text", + true, + true, + 4, + "AB", + true, + 4, + true, + true, + false, + "Script folder is not empty", + true, + false, + false, + "Script file name is already in use", + true, + "c.txt", + true, + false, + 2, + 6, + true, + false, + true, + false + ]]) + ); + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `length` while the file is open changes what the open file holds, so closing it keeps +/// the new length. +#[test] +fn script_file_length_changes_reach_an_open_file() { + let base = folder("openlength"); + let r = run( + &base, + "var o = new File(Folder.temp.fsName + '/l.txt'); o.open('w'); o.write('abc');\n\ + new File(o.fsName).length = 1; o.write('d'); o.close();\n\ + o.open('r'); vc.log([o.read(), o.length]); o.close();", + ); + assert_eq!(r["log"], json!([["ad", 2]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file is kept as it was when `open('w')` is given an encoding that is not one and when it is +/// copied onto itself, and the changes an open file holds stay to be written when writing them fails. +#[test] +fn script_file_writes_keep_what_they_cannot_change() { + let base = folder("keeps"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + var k = new File(d + '/k.txt'); k.open('w'); k.write('keep'); k.close();\n\ + k.encoding = 'nope'; out.push(k.open('w'), k.error);\n\ + k.encoding = 'UTF-8'; k.open('r'); out.push(k.read()); k.close();\n\ + out.push(k.copy(k.fsName), k.length);\n\ + var w = new File(d + '/w.txt'); w.open('w'); w.write('abc'); new File(w.fsName).readonly = true;\n\ + var q = new File(w.fsName); q.length = 1; out.push(q.error);\n\ + new File(w.fsName).readonly = false; out.push(w.close()); w.open('r'); out.push(w.read()); w.close();\n\ + vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file cannot be decoded", "keep", true, 4, "Script file could not be written", true, "abc"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file whose `close` could not write it stays to be written when the run ends. +#[test] +fn script_file_close_that_cannot_write_keeps_the_changes() { + let base = folder("closefail"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/c.txt'); u.open('w'); u.write('kept');\n\ + new File(u.fsName).readonly = true; var out = [u.close(), u.error]; new File(u.fsName).readonly = false;\n\ + vc.log(out); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, "Script file could not be written"])); + assert_eq!(std::fs::read(r["log"][1].as_str().unwrap()).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// `changePath` on an object whose changes could not be written gives false with `error` set, and +/// the object keeps its path. +#[test] +fn script_file_change_path_that_cannot_write_keeps_the_path() { + let base = folder("changepathfail"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/p.txt'); u.open('w'); u.write('kept'); var was = u.fsName;\n\ + new File(was).readonly = true; var out = [u.changePath(Folder.userData.fsName + '/q.txt'), u.error, u.fsName == was];\n\ + new File(was).readonly = false; vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, "Script file could not be written", true])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file opened again after a `close` that could not write it keeps what was written after it was +/// opened again, and the earlier changes do not replace it when the run ends. +#[test] +fn script_file_opened_again_after_a_failed_close_keeps_the_later_text() { + let base = folder("reopen"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/r.txt'); u.open('w'); u.write('old');\n\ + new File(u.fsName).readonly = true; var out = [u.close()]; new File(u.fsName).readonly = false;\n\ + out.push(u.open('w'), u.write('new'), u.close()); vc.log(out); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, true, true, true])); + assert_eq!(std::fs::read(r["log"][1].as_str().unwrap()).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); +} + +/// A write that would pass the run's 32 MiB of writing ends the run, and its text is not written. +#[test] +fn script_file_write_past_the_run_limit_is_not_written() { + let base = folder("runlimit"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var t = 'x'; while (t.length < 4194304) t += t;\n\ + var f = new File(Folder.userData.fsName + '/f.bin'); f.encoding = 'UTF-16';\n\ + for (var k = 0; k < 4; k++) { f.open('w'); f.write(t); f.close(); }\n\ + var g = new File(Folder.userData.fsName + '/g.txt'); vc.log(g.fsName); g.open('w'); g.write('over');", + ); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + assert_eq!(std::fs::read(report["log"][0].as_str().unwrap()).unwrap(), b"", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `remove` and `rename` of a file that is open elsewhere: a removed file is not written again when +/// the run ends, a renamed one is written under its new name, and an object whose own changes could +/// not be written does not remove or rename its file. +#[test] +fn script_file_remove_and_rename_of_an_open_file() { + let base = folder("openmove"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, out = [];\n\ + var a = new File(d + '/a.txt'); a.open('w'); a.write('a'); out.push(new File(a.fsName).remove());\n\ + var b = new File(d + '/b.txt'); b.open('w'); b.write('b'); var c = new File(b.fsName); out.push(c.rename('c.txt'), b.close());\n\ + var e = new File(d + '/e.txt'); e.open('w'); e.write('e'); new File(e.fsName).readonly = true;\n\ + out.push(e.remove(), e.error, e.exists); new File(e.fsName).readonly = false;\n\ + vc.log(out); vc.log(d);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([true, true, true, false, "Script file could not be written", true])); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert!(!d.join("a.txt").exists() && !d.join("b.txt").exists()); + assert_eq!(std::fs::read(d.join("c.txt")).unwrap(), b"b"); + assert_eq!(std::fs::read(d.join("e.txt")).unwrap(), b"e", "the run's end writes the changes the failed close kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a file that is open copies what the open file holds, and an object that has the target +/// open then holds the copy. +#[test] +fn script_file_copy_of_an_open_file_has_its_changes() { + let base = folder("copyopen"); + let r = run( + &base, + "var d = Folder.temp.fsName, f = new File(d + '/f.txt'); f.open('w'); f.write('new');\n\ + var out = [f.copy(d + '/g.txt')]; var g = new File(d + '/g.txt'); g.open('r'); out.push(g.read()); g.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, "new"]])); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('copied'); s.close();\n\ + var t = new File(d + '/t.txt'); t.open('w'); t.write('old'); var out = [s.copy(t.fsName), t.close()];\n\ + t.open('r'); out.push(t.read()); t.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, "copied"]]), "an open target holds the copy"); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant that would make the grants file larger than it may be read is not kept, and the grants +/// file keeps the grants it had. +#[test] +fn script_file_grants_file_stays_within_its_size_limit() { + let base = folder("bigstore"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let store = base.join("settings/Script Grants.json"); + let grants = + |path: String| json!({"version": 1, "grants": [{"script": "x", "sha256": "y", "code": [], "path": path, "write": false, "folder": false}]}); + let empty = serde_json::to_vec_pretty(&grants(String::new())).unwrap().len(); + let full = serde_json::to_vec_pretty(&grants("p".repeat((4 << 20) - 64 - empty))).unwrap(); + write(&store, &full); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + start_framed(&mut s, &base, "var f = File.saveDialog('p'); vc.log(f === null ? null : f.fsName);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let _ = pump_to_picker(&mut s).unwrap(); + assert_eq!(std::fs::read(&store).unwrap(), full, "the grants file is left as it was"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a file over 8 MiB is refused, as opening one is. +#[test] +fn script_file_copy_is_held_to_the_file_limit() { + let base = folder("bigcopy"); + write(&base.join("main/big.bin"), &vec![0u8; 8 * 1024 * 1024 + 1]); + let r = run(&base, "var b = new File('big.bin'); vc.log([b.copy(Folder.temp.fsName + '/b.bin'), b.error]);"); + assert_eq!(r["log"], json!([[false, "Script file exceeds 8 MiB"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's 32 MiB of writes counts what setting `length` adds to each object the file is open in, +/// as each holds its own bytes. +#[test] +fn script_file_length_counts_the_growth_of_every_open_object() { + let base = folder("lengthheld"); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write( + &main, + b"var p = Folder.temp.fsName + '/l.bin'; var w = new File(p); w.open('w'); w.close();\n\ + var all = []; for (var i = 0; i < 5; i++) { var f = new File(p); f.open('e'); all.push(f); }\n\ + vc.log('open'); new File(p).length = 7 * 1024 * 1024; vc.log('grown');", + ); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects grow by 7 MiB each"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!(["open"])); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` onto another name of the same file, a hard link, keeps the file's bytes, and what the +/// source's open object holds is in the file when `copy` returns. +#[test] +fn script_file_copy_onto_a_hard_link_of_itself_keeps_the_file() { + let base = folder("copylink"); + let picked = base.join("picked"); + write(&picked.join("a.txt"), b"keep"); + std::fs::hard_link(picked.join("a.txt"), picked.join("b.txt")).unwrap(); + let mut s = Session::new(); + start_framed( + &mut s, + &base, + "var p = Folder.selectDialog('p'); var a = new File(p.fsName + '/a.txt'), b = new File(p.fsName + '/b.txt');\n\ + a.open('w'); a.write('new'); var out = [a.copy(b.fsName)]; b.open('r'); out.push(b.read()); b.close(); a.close(); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, "new"]])); + assert_eq!(std::fs::read(picked.join("a.txt")).unwrap(), b"new"); + assert_eq!(std::fs::read(picked.join("b.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's 32 MiB of writes counts the copy each open object of `copy`'s target takes. +#[test] +fn script_file_copy_counts_the_bytes_each_open_object_of_the_target_takes() { + let base = folder("copyheld"); + write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write( + &main, + b"var t = Folder.temp.fsName + '/t.bin'; var w = new File(t); w.open('w'); w.close();\n\ + var all = []; for (var i = 0; i < 5; i++) { var f = new File(t); f.open('e'); all.push(f); }\n\ + vc.log('open'); vc.log(new File('seven.bin').copy(t));", + ); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects take 7 MiB each"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!(["open"])); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `write` joins its values only for an open file, and stops joining once the text is longer than +/// any file a script writes: the values after that are not turned into text. +#[test] +fn script_file_write_stops_joining_past_the_file_limit() { + let base = folder("writejoin"); + let r = run( + &base, + "var seen = 0, late = { toString: function () { seen++; return 'x'; } };\n\ + var f = new File(Folder.temp.fsName + '/j.txt'); var closed = [f.write(late), seen];\n\ + var s = new Array((1 << 20) + 1).join('x'), a = []; for (var k = 0; k < 17; k++) a.push(s); a.push(late);\n\ + f.open('w'); var big = f.write.apply(f, a); vc.log([closed, big, f.error, seen, f.write('ok'), f.close(), f.length]);", + ); + assert_eq!(r["log"], json!([[[false, 0], false, "Script file exceeds 8 MiB", 0, true, true, 2]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The report names at most 4,096 files a run wrote, each once, and says when it wrote more. +#[test] +fn script_reports_name_at_most_4096_written_files() { + let base = folder("manywritten"); + let r = run( + &base, + "var d = Folder.temp.fsName; for (var k = 0; k < 4100; k++) { var f = new File(d + '/' + k + '.txt'); f.open('w'); f.close(); f.open('w'); f.close(); }", + ); + let written = r["written"].as_array().unwrap(); + assert_eq!(written.len(), crate::script::MAX_WRITTEN, "{}", written.len()); + assert_eq!(written.iter().filter_map(Value::as_str).collect::>().len(), written.len()); + assert_eq!(r["writtenMore"], true); + let few = run(&base, "var f = new File(Folder.temp.fsName + '/one.txt'); f.open('w'); f.close();"); + assert_eq!((few["written"].as_array().map(Vec::len), few.get("writtenMore")), (Some(1), None)); + let _ = std::fs::remove_dir_all(base); +} + +/// A kept grant stays on the real path it was kept for: when a link to another folder takes the +/// granted folder's place, the next run is not granted the folder the link leads to. +#[cfg(unix)] +#[test] +fn script_file_grants_do_not_follow_a_link_put_in_the_granted_place() { + let base = folder("grantlink"); + let granted = base.join("picked/granted"); + write(&granted.join("s.txt"), b"mine"); + write(&base.join("away/s.txt"), b"secret"); + let text = format!( + "var t = new File({:?}), u = new File({:?});\n\ + if (t.open('r')) vc.log(['kept', t.read()]); else if (u.open('r')) vc.log(['away', u.read()]);\n\ + else vc.log(Folder.selectDialog('p') ? 'asked' : null);", + granted.join("s.txt").to_string_lossy(), + base.join("away/s.txt").to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![granted.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", "mine"]])); + std::fs::rename(&granted, base.join("picked/moved")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &granted).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "the run asks again instead of reading where the link leads"); + s.script_pick(crate::script::files::PickAnswer::Deny); + let _ = pump_to_picker(&mut s); + let _ = std::fs::remove_dir_all(base); +} + +/// A folder granted in a file dialog cannot have a folder in it renamed when that folder holds the +/// settings folder. +#[test] +fn script_file_rename_does_not_move_the_settings_folder() { + let base = folder("moveup"); + let mut s = Session::new(); + s.attach_script_data(base.join("cfg/settings/Script Data")); + std::fs::create_dir_all(base.join("cfg/settings")).unwrap(); + start_framed(&mut s, &base, "var p = Folder.selectDialog('p'); var c = new Folder(p.fsName + '/cfg'); vc.log([c.rename('cfg2'), c.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED]])); + assert!(base.join("cfg/settings").is_dir()); + let _ = std::fs::remove_dir_all(base); +} + +/// Where case does not matter, a folder named in another case is still the folder that holds the +/// settings folder, or the settings folder itself: it is not renamed or removed. +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() { + let base = folder("moveupcase"); + let mut s = Session::new(); + s.attach_script_data(base.join("cfg/settings/Script Data")); + std::fs::create_dir_all(base.join("cfg/settings")).unwrap(); + start_framed( + &mut s, + &base, + "var p = Folder.selectDialog('p'); var c = new Folder(p.fsName + '/CFG'), d = new Folder(p.fsName + '/cfg/SETTINGS');\n\ + vc.log([c.rename('cfg2'), c.error, d.rename('s2'), d.error, d.remove(), d.error]);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED, false, DENIED, false, DENIED]])); + assert!(base.join("cfg/settings").is_dir()); + let _ = std::fs::remove_dir_all(base); +} + +/// Where case matters, a rename to a name that differs in case alone does not replace the other file. +#[cfg(target_os = "linux")] +#[test] +fn script_file_rename_keeps_a_file_that_differs_in_case() { + let base = folder("casename"); + let r = run( + &base, + "var d = Folder.temp.fsName, a = new File(d + '/a.txt'), b = new File(d + '/A.txt');\n\ + a.open('w'); a.write('a'); a.close(); b.open('w'); b.write('B'); b.close();\n\ + var out = [a.rename('A.txt'), a.error]; b.open('r'); out.push(b.read()); b.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file name is already in use", "B"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A script's data folder that is a link is not used: the folder it leads to is not granted. +#[cfg(unix)] +#[test] +fn script_data_folder_that_is_a_link_is_not_granted() { + let base = folder("datalink"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let data = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::remove_dir(&data).unwrap(); + std::fs::create_dir_all(base.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &data).unwrap(); + let text = format!( + "var d = Folder.userData; var w = new File({:?}); vc.log([d === null, w.open('w'), w.error]);", + base.join("away/x.txt").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false, DENIED]])); + assert!(!base.join("away/x.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A data folder that is a link is not used: no script's `Folder.userData` is made in the folder it +/// leads to. +#[cfg(unix)] +#[test] +fn script_data_folders_in_a_data_folder_that_is_a_link_are_not_granted() { + let base = folder("datadirlink"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let key = PathBuf::from(r["log"][0].as_str().unwrap()).file_name().unwrap().to_owned(); + let data = base.join("settings/Script Data"); + std::fs::remove_dir_all(&data).unwrap(); + std::fs::create_dir_all(base.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &data).unwrap(); + let text = format!( + "var d = Folder.userData; var w = new File({:?}); vc.log([d === null, w.open('w'), w.error]);", + base.join("away").join(&key).join("x.txt").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false, DENIED]])); + assert!(!base.join("away").join(&key).exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// An open file whose folder was replaced by a link before it was written is not written through +/// the link. +#[cfg(unix)] +#[test] +fn script_files_are_not_written_through_a_link_put_in_place_of_their_folder() { + let base = folder("parentlink"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("away")).unwrap(); + // The run opens and changes `sub/f.txt` in its data folder and waits on a file dialog, while + // another program puts a link to `away` in place of `sub`. + start_framed( + &mut s, + &base, + "var d = Folder.userData.fsName, f = new File(d + '/sub/f.txt');\n\ + var before = [new Folder(d + '/sub').create(), f.open('w'), f.write('x')];\n\ + File.openDialog('p'); vc.log([before, f.close(), f.error]);", + ); + assert!(pump_to_picker(&mut s).is_none()); + let data = std::fs::read_dir(base.join("settings/Script Data")).unwrap().next().unwrap().unwrap().path(); + std::fs::rename(data.join("sub"), data.join("old")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), data.join("sub")).unwrap(); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + // The file stays unwritten, so the run's end fails the run as for any file it could not write. + let e = pump_to_picker(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("left open files that could not be written"), "{e}"); + assert!(!base.join("away/f.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix, `readonly` clears the write bits and clearing it gives the file the bits it had. +#[cfg(unix)] +#[test] +fn script_file_readonly_keeps_the_other_permissions() { + use std::os::unix::fs::PermissionsExt; + let base = folder("modes"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/m.txt'); u.open('w'); u.close(); vc.log(u.fsName);").unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap(); + let text = format!( + "Folder.userData; var u = new File({:?}); u.readonly = true; var a = u.readonly; u.readonly = false; vc.log([a, u.readonly]);", + path.to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false]])); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o640); + let _ = std::fs::remove_dir_all(base); +} + +/// Clearing `readonly` gives back every write bit that setting it cleared in the run, also after a +/// rename, and only the owner's write bit for a file that was read-only before the run. +#[cfg(unix)] +#[test] +fn script_file_readonly_gives_back_the_write_bits_it_cleared() { + use std::os::unix::fs::PermissionsExt; + let base = folder("modesback"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/m.txt'); u.open('w'); u.close(); vc.log(u.fsName);").unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o662)).unwrap(); + let toggle = format!( + "Folder.userData; var u = new File({:?}); u.readonly = true; var a = u.readonly; var b = u.rename('n.txt');\n\ + u.readonly = false; vc.log([a, b, u.readonly]); u.rename('m.txt');", + path.to_string_lossy() + ); + let r = run_in(&mut s, &base, &toggle).unwrap(); + assert_eq!(r["log"], json!([[true, true, false]])); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o662); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444)).unwrap(); + let clear = format!("Folder.userData; var u = new File({:?}); u.readonly = false;", path.to_string_lossy()); + run_in(&mut s, &base, &clear).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644); + let _ = std::fs::remove_dir_all(base); +} + +/// Opening a file to append or edit reads it, so the automation read roots apply as well as the +/// write roots. +#[test] +fn script_file_append_and_edit_need_the_read_roots() { + let base = folder("appendroots"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + let roots = AutomationRoots::new(&[&base.join("main")], &[&base]).unwrap(); + let r = confine(roots.as_ref(), || { + run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/w.txt'), out = [u.open('w'), u.write('kept'), u.close()];\n\ + out.push(u.open('a'), u.error, u.open('e'), u.error); vc.log(out);", + ) + }) + .unwrap(); + assert_eq!(r["log"], json!([[true, true, true, false, DENIED, false, DENIED]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A script run from a folder that holds the settings folder reads its own files there, but no file +/// in the settings folder. +#[test] +fn script_files_in_a_folder_above_the_settings_folder_do_not_reach_it() { + let base = folder("above"); + let mut s = Session::new(); + s.attach_script_data(base.join("main/settings/Script Data")); + write(&base.join("main/settings/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + write(&base.join("main/own.txt"), b"own"); + let r = run_in( + &mut s, + &base, + "var a = new File('own.txt'), g = new File('settings/Script Grants.json');\n\ + var out = [a.open('r'), a.read()]; a.close(); out.push(g.open('r'), g.error, g.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([[true, "own", false, DENIED, false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The settings folder is kept out of every grant also before it has been made. +#[test] +fn script_file_grants_never_reach_a_settings_folder_not_made_yet() { + let base = folder("unmade"); + let mut s = with_data(&base); + assert!(!base.join("settings").exists()); + start_framed(&mut s, &base, "var o = new Folder(Folder.userData.parent.parent.fsName); var f = o.selectDlg('p'); vc.log([f, o.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + let settings = base.join("settings").to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![settings], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[null, "Script file access to the app's own folders is not allowed"]])); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// Files left open are written when the run ends in the order they were opened, so of two objects +/// that hold the same file, the one opened last decides what it holds. +#[test] +fn script_files_left_open_are_written_in_the_order_they_were_opened() { + let base = folder("flushorder"); + let mut s = with_data(&base); + let text = "var p = Folder.userData.fsName + '/two.txt'; var a = new File(p), b = new File(p);\n\ + a.open('w'); b.open('w'); a.write('first'); b.write('second'); vc.log(p);"; + for _ in 0..16 { + let r = run_in(&mut s, &base, text).unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap_or_default()); + assert_eq!(std::fs::read(&path).unwrap(), b"second", "{r}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Removing a file leaves the other objects that have it open without the file: they take no more +/// writes, and closing them does not make it again. +#[test] +fn script_file_remove_detaches_the_other_open_objects() { + let base = folder("removeopen"); + let mut s = with_data(&base); + let text = "var p = Folder.userData.fsName + '/gone.txt'; var a = new File(p), b = new File(p);\n\ + a.open('w'); a.write('x'); a.close(); b.open('e');\n\ + var removed = a.remove(); var w = b.write('y'); var e = b.error; b.close();\n\ + vc.log([removed, w, e, new File(p).exists]);"; + let r = run_in(&mut s, &base, text).unwrap(); + assert_eq!(r["log"], json!([[true, false, "Script file is not open for writing", false]]), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A run that ends with a changed file open that cannot be written fails and names the file. +#[test] +fn script_files_left_open_that_cannot_be_written_fail_the_run() { + let base = folder("unwritten"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/ro.txt'); u.open('w'); u.write('x'); new File(u.fsName).readonly = true; vc.log(u.fsName);", + ); + let report = s.script_report().unwrap(); + let path = PathBuf::from(report["log"][0].as_str().unwrap_or_default()); + if let Ok(m) = std::fs::metadata(&path) { + let mut p = m.permissions(); + #[allow(clippy::permissions_set_readonly_false)] + p.set_readonly(false); + let _ = std::fs::set_permissions(&path, p); + } + assert!(r.is_err(), "{report}"); + let message = report["message"].as_str().unwrap(); + assert!(message.contains("the script left open files that could not be written") && message.contains("ro.txt"), "{report}"); + assert_eq!(std::fs::read(&path).unwrap(), b"", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The automation write roots apply to the run's own folders too: outside them `Folder.temp` and +/// `Folder.userData` are `null` and are not made. +#[test] +fn script_files_write_only_inside_the_automation_write_roots() { + let base = folder("writeroots"); + std::fs::create_dir_all(base.join("out")).unwrap(); + let roots = AutomationRoots::new(&[&base], &[&base.join("out")]).unwrap(); + let mut s = with_data(&base); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log([Folder.temp === null, Folder.userData === null]);")).unwrap(); + assert_eq!(r["log"], json!([[true, true]])); + assert!(!base.join("settings/Script Data").exists(), "the data folder is not made"); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's temporary folder is checked against the write roots by its own name: a write root named +/// `VectorCraft Script` in the temporary folder does not take the run's folder beside it. +#[test] +fn script_temporary_folder_is_checked_by_its_own_name() { + let base = folder("tempname"); + let named = std::env::temp_dir().join("VectorCraft Script"); + let made = std::fs::create_dir(&named).is_ok(); + let roots = AutomationRoots::new(&[&base], &[&named]).unwrap(); + let mut s = with_data(&base); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log(Folder.temp === null);")); + if made { + let _ = std::fs::remove_dir(&named); + } + assert_eq!(r.unwrap()["log"], json!([true])); + let _ = std::fs::remove_dir_all(base); +} + +/// The folders made above a script's data folder are inside the write roots too: with a write root +/// that names the data folder after the folders above it were removed, none of them is made again. +#[test] +fn script_data_folder_makes_no_folder_outside_the_write_roots() { + let base = folder("dataparent"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let data = PathBuf::from(r["log"][0].as_str().unwrap()); + let roots = AutomationRoots::new(&[&base], &[&data]).unwrap(); + std::fs::remove_dir_all(base.join("settings")).unwrap(); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log(Folder.userData === null);")).unwrap(); + assert_eq!(r["log"], json!([true])); + assert!(!base.join("settings").exists(), "no folder above the write root is made"); + let _ = std::fs::remove_dir_all(base); +} + +/// `create` makes no folder outside the places the script may write: when the folders above its data +/// folder were removed during the run, a folder in the data folder is not made, and neither are they. +#[test] +fn script_folder_create_makes_no_folder_outside_the_grants() { + let base = folder("createabove"); + let mut s = with_data(&base); + start_framed(&mut s, &base, "var d = Folder.userData.fsName; File.openDialog('p'); var f = new Folder(d + '/a'); vc.log([f.create(), f.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + std::fs::remove_dir_all(base.join("settings")).unwrap(); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED]])); + assert!(!base.join("settings").exists(), "no folder above the data folder is made"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file a script wrote stays written after its run fails, and the report names it. +#[test] +fn script_files_written_before_a_failure_are_named() { + let base = folder("failwrite"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/left.txt'); u.open('w'); u.write('left'); throw new Error('late');"); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + let written: Vec = report["written"].as_array().unwrap().iter().filter_map(Value::as_str).map(PathBuf::from).collect(); + assert_eq!(written.len(), 1, "{report}"); + assert_eq!(std::fs::read(&written[0]).unwrap(), b"left", "the open file is written when the run ends"); + let _ = std::fs::remove_dir_all(base); +} + +/// Pumps the run in the app until it ends or waits at a file dialog (`None`). +fn pump_to_picker(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_picker().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Starts `main/main.jsx` in `base` with the text `text`, in the app. +fn start_framed(s: &mut Session, base: &Path, text: &str) { + s.script_frames = true; + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); +} + +/// The filter of an open or save dialog gives the file types the dialog shows; an open dialog with +/// `multiSelect` takes every file picked and gives them as a list. +#[test] +fn script_file_dialogs_show_the_filters_file_types_and_open_several_files() { + use crate::script::files::dialog_filters; + let f = |types: &[(&str, &[&str])]| -> Vec<(String, Vec)> { + types.iter().map(|(n, e)| (n.to_string(), e.iter().map(|e| e.to_string()).collect())).collect() + }; + assert_eq!(dialog_filters("JavaScript files:*.jsx;All files:*.*"), f(&[("JavaScript files", &["jsx"]), ("All files", &["*"])])); + assert_eq!(dialog_filters("Images:*.png,*.JPG , Text:*.txt"), f(&[("Images", &["png", "JPG"]), ("Text", &["txt"])])); + assert_eq!(dialog_filters("*.svg;*.ai"), f(&[("*.svg;*.ai", &["svg", "ai"])])); + assert_eq!(dialog_filters("All files:*.*"), f(&[]), "every file"); + assert_eq!(dialog_filters("Odd:a*b.txt;Bad:*.a/b;Text:*.txt"), f(&[("Text", &["txt"])]), "patterns that are not *.ext are left out"); + assert_eq!(dialog_filters(""), f(&[])); + + let base = folder("pickfilter"); + for name in ["a.txt", "b.txt"] { + write(&base.join("picked").join(name), b"x"); + } + let mut s = with_data(&base); + start_framed(&mut s, &base, "var f = File.openDialog('Pick', 'Text:*.txt;All files:*.*', true); vc.log([f.length, f[0].name, f[1].name]);"); + assert!(pump_to_picker(&mut s).is_none()); + let picker = s.script_picker().unwrap(); + assert!(picker.multiple); + assert_eq!(picker.filters, f(&[("Text", &["txt"]), ("All files", &["*"])])); + let paths = ["a.txt", "b.txt"].iter().map(|n| base.join("picked").join(n).to_string_lossy().into_owned()).collect(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[2, "a.txt", "b.txt"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A dialog's `filter` that is a function is called with each file picked, and the files it gives a +/// false value for are left out: a list keeps the rest, and one file, or a list left empty, gives +/// `null`. The dialog shows every file. A save dialog takes the same filter. +#[test] +fn script_file_dialogs_leave_out_the_files_a_filter_function_refuses() { + let base = folder("pickfilterfn"); + for name in ["a.txt", "b.svg", "c.txt"] { + write(&base.join("picked").join(name), b"x"); + } + let paths = |names: &[&str]| -> Vec { names.iter().map(|n| base.join("picked").join(n).to_string_lossy().into_owned()).collect() }; + let text = "var seen = [];\n\ + function txt(f) { seen.push(f instanceof File ? f.name : null); return f.name.slice(-4) === '.txt'; }\n\ + var many = File.openDialog('Pick', txt, true);\n\ + vc.log([many.length, many[0].name, many[1].name]);\n\ + vc.log(File.openDialog('Pick one', txt));\n\ + vc.log(File.openDialog('Pick svg', txt, true));\n\ + var saved = File.saveDialog('Save', txt);\n\ + vc.log(saved && saved.name);\n\ + vc.log(new File('x.txt').saveDlg('Save svg', txt));\n\ + vc.log(seen);"; + let mut s = with_data(&base); + start_framed(&mut s, &base, text); + for picked in [&["a.txt", "b.svg", "c.txt"][..], &["b.svg"], &["b.svg"], &["c.txt"], &["b.svg"]] { + assert!(pump_to_picker(&mut s).is_none()); + assert_eq!(s.script_picker().unwrap().filters, Vec::<(String, Vec)>::new(), "every file is shown"); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: paths(picked), always: false })); + } + let r = pump_to_picker(&mut s).unwrap().unwrap(); + let seen = ["a.txt", "b.svg", "c.txt", "b.svg", "b.svg", "c.txt", "b.svg"]; + assert_eq!(r["log"], json!([[2, "a.txt", "c.txt"], null, null, "c.txt", null, seen])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file a person allows always is kept for that script with that text: a later run reads it +/// without asking, and a run of changed text asks again. A file allowed once is not kept. +#[test] +fn script_file_dialog_grants_are_kept_for_the_same_script_text() { + let base = folder("grants"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let text = format!( + "var target = new File({:?});\n\ + if (target.open('r')) {{ vc.log(['kept', target.read()]); target.close(); }}\n\ + else {{ vc.log(['asked', target.error]); var f = File.saveDialog('Save it'); if (f) {{ f.open('w'); f.write('hi'); vc.log(f.close()); }} else vc.log(null); }}", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + let picker = s.script_picker().unwrap(); + assert_eq!((picker.kind, picker.prompt.as_str(), picker.can_always), (crate::script::files::PickerKind::Save, "Save it", true)); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["asked", DENIED], true])); + assert_eq!(std::fs::read(&out).unwrap(), b"hi"); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"].as_array().unwrap().len(), 1, "{grants}"); + assert_eq!(grants["grants"][0]["write"], true); + + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["kept", "hi"]]), "the same script text keeps its grant"); + + start_framed(&mut s, &base, &format!("{text}\n// changed")); + assert!(pump_to_picker(&mut s).is_none(), "changed text has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["asked", DENIED], null])); + + let once = "var g = File.openDialog('Read it'); vc.log(g.fsName === null ? null : g.open('r') && g.read());"; + start_framed(&mut s, &base, once); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["hi"])); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1, "a file allowed once is not kept"); + + // A run that waits at a dialog keeps the grants it started with, so they are not revoked under it. + start_framed(&mut s, &base, once); + assert!(pump_to_picker(&mut s).is_none()); + let busy = s.execute("script.grants.revoke", &json!({"all": true})); + assert!(matches!(busy, Err(crate::EngineError::Busy)), "{busy:?}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert!(pump_to_picker(&mut s).is_some(), "the run ends"); + + let removed = s.execute("script.grants.revoke", &json!({"path": out.to_string_lossy()})).unwrap(); + assert_eq!(removed["removed"], 1); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + assert!(s.execute("script.grants.revoke", &json!({})).is_err()); + assert!(!base.join("settings/Script Grants.json.part").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant is kept for the script's text with the files it includes: a changed included file asks +/// again. +#[test] +fn script_file_grants_are_kept_for_the_included_files_too() { + let base = folder("grantinclude"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + write(&out, b"hi"); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;\n"); + let text = format!( + "#include \"lib.jsxinc\"\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["kept"])); + write(&base.join("main/lib.jsxinc"), b"var lib = 2;\n"); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a changed included file has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// A kept grant is in force only while the run evaluates code the run that kept it evaluated: a +/// file `$.evalFile` runs, or a string given to `eval` or `Function`, that differs withdraws it +/// before that code runs. +#[test] +fn script_file_grants_are_kept_for_the_code_the_script_evaluates() { + let base = folder("granteval"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;"); + write(&base.join("main/code.txt"), b"new File(p).open('r')"); + let text = format!( + "var p = {:?};\n$.evalFile('lib.jsxinc');\n\ + var c = new File('code.txt'); c.open('r'); var src = c.read(); c.close();\n\ + var one = Function('return 1')();\n\ + var before = new File(p).open('r');\n\ + var during = eval(src) && one === 1;\n\ + if (before) vc.log(['kept', during]); else vc.log(['asked', !!File.openDialog('p')]);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + let picked = || crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true }; + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(picked())); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", true]]), "the same code keeps the grant"); + write(&base.join("main/code.txt"), b"new File(p).open('r') && true"); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", false]]), "changed eval code runs without the grant"); + write(&base.join("main/code.txt"), b"new File(p).open('r')"); + write(&base.join("main/lib.jsxinc"), b"var lib = 2;"); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a changed $.evalFile file has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", false]])); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;"); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", true]])); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"][0]["code"].as_array().map(Vec::len), Some(3), "{grants}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file's grant covers that path only: a folder the script makes in the file's place, in the run +/// that was allowed the file and in later runs that keep its grant, is not read or written inside. +#[test] +fn script_file_grants_do_not_reach_into_a_folder_in_the_files_place() { + let base = folder("grantfileplace"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = "var p = File.saveDialog('p').fsName;\n\ + var gone = new File(p).remove(); var made = new Folder(p).create();\n\ + var w = new File(p + '/x.txt'); vc.log([gone, made, w.open('w'), w.error]);"; + let mut s = with_data(&base); + start_framed(&mut s, &base, text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[true, true, false, DENIED]])); + assert!(out.is_dir() && !out.join("x.txt").exists()); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"][0]["folder"], false, "{grants}"); + + let later = format!("var w = new File({:?}); vc.log([w.open('w'), w.error]);", out.join("y.txt").to_string_lossy()); + let main = base.join("main/main.jsx"); + write(&main, later.as_bytes()); + let real = std::fs::canonicalize(&main).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(later.as_bytes()); + let out_real = crate::cmd::findfiles::plain(std::fs::canonicalize(&out).unwrap()); + let kept = json!({"version": 1, "grants": [{"script": crate::cmd::findfiles::plain(real).to_string_lossy(), "sha256": hash, "code": [], "path": out_real.to_string_lossy(), "write": true, "folder": false}]}); + write(&base.join("settings/Script Grants.json"), kept.to_string().as_bytes()); + start_framed(&mut s, &base, &later); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, DENIED]]), "a kept file grant does not reach inside either"); + assert!(!out.join("y.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// The code a run evaluates after a person allowed it a file always is kept with the grant when +/// the run ends, so the next run of the same script that evaluates it keeps the grant. +#[test] +fn script_file_grants_keep_the_code_evaluated_after_the_dialog() { + let base = folder("grantlater"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "var t = new File({:?}); var kept = t.open('r');\n\ + if (!kept) File.openDialog('p');\n\ + vc.log([kept, eval('new File(t.fsName).open(\"r\")')]);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, true]])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +/// Code another script left in a named engine withdraws a script's kept grants in that engine. +#[test] +fn script_file_grants_are_withdrawn_by_code_another_script_left_in_the_engine() { + let base = folder("grantengine"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "#targetengine shared\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["kept"]), "the engine holds only this script's code"); + let other = base.join("main/other.jsx"); + write(&other, b"#targetengine shared\nvar otherWasHere = 1;"); + s.script_frames = false; + s.execute("script.run", &json!({"path": other.to_string_lossy()})).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "another script's code is in the engine, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// Code a script given as text left in a named engine withdraws a script's kept grants in that +/// engine, as a file script's code does. +#[test] +fn script_file_grants_are_withdrawn_by_code_a_text_script_left_in_the_engine() { + let base = folder("grantenginetext"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "#targetengine shared\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + s.script_frames = false; + s.execute("script.run", &json!({"source": "#targetengine shared\nvar textWasHere = 1;"})).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a text script's code is in the engine, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file opened for writing under a kept grant that new code withdraws takes no more writes, and +/// changes that cannot be written then fail the run when it ends. +#[test] +fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { + let base = folder("grantwithdrawn"); + let dir = base.join("picked"); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("out.txt"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('w')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ f.write('a'); new File(f.fsName).readonly = true; eval('1'); vc.log(['wrote', f.write('b'), f.error]); }}", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap(); + let report = s.script_report().unwrap(); + if let Ok(m) = std::fs::metadata(&out) { + let mut p = m.permissions(); + #[allow(clippy::permissions_set_readonly_false)] + p.set_readonly(false); + let _ = std::fs::set_permissions(&out, p); + } + assert!(r.is_err(), "{report}"); + assert_eq!(report["log"], json!([["wrote", false, "Script file is not open for writing"]]), "{report}"); + let message = report["message"].as_str().unwrap(); + assert!(message.contains("the script left open files that could not be written") && message.contains("out.txt"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The folder that holds the settings is kept out of every grant: a pick there gives `null` with the +/// error, a grant written into the grants file for it is not taken, and the script cannot write the +/// grants file through its data folder. +#[test] +fn script_file_grants_never_reach_the_settings_folder() { + let base = folder("protected"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("settings/Scripts")).unwrap(); + let inside = base.join("settings/Scripts/x.txt"); + write(&inside, b"secret"); + let text = format!( + "var o = new File('x.txt'); var f = o.saveDlg('p'); vc.log([f, o.error]);\n\ + var g = new File(Folder.userData.parent.parent.fsName + '/Script Grants.json'); vc.log([g.open('w'), g.error]);\n\ + var h = new File({:?}); vc.log([h.open('r'), h.error]);", + inside.to_string_lossy() + ); + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + let real = std::fs::canonicalize(&main).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(text.as_bytes()); + let settings = crate::cmd::findfiles::plain(std::fs::canonicalize(base.join("settings")).unwrap()); + let forged = json!({"version": 1, "grants": [{"script": crate::cmd::findfiles::plain(real).to_string_lossy(), "sha256": hash, "code": [], "path": settings.to_string_lossy(), "write": true, "folder": true}]}); + write(&base.join("settings/Script Grants.json"), forged.to_string().as_bytes()); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![inside.to_string_lossy().into_owned()], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + let protected = "Script file access to the app's own folders is not allowed"; + assert_eq!(r["log"], json!([[null, protected], [false, DENIED], [false, DENIED]])); + assert_eq!(std::fs::read(&inside).unwrap(), b"secret"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file dialog inside a built-in's callback throws in the app, where it cannot wait. +#[test] +fn script_file_dialog_in_a_callback_throws() { + let base = folder("callback"); + let mut s = Session::new(); + start_framed(&mut s, &base, "[1].forEach(function () { File.openDialog(); });"); + let r = pump_to_picker(&mut s).unwrap(); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + assert!(report["message"].as_str().unwrap().contains("File.openDialog: a file dialog cannot open inside a callback"), "{report}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index d272fea167..0a4037a0d8 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -245,10 +245,46 @@ fn files_are_checked_before_they_are_read() { let _ = std::fs::remove_dir_all(&dir); } +/// A new empty folder for test `name`. +fn fresh_folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder +/// `dir` there once. +fn start_allowed(s: &mut Session, dir: &std::path::Path, source: &str) { + s.script_frames = true; + assert_eq!(run(s, &format!("Folder.selectDialog('Folder');\n{source}")).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + let paths = vec![dir.to_string_lossy().into_owned()]; + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false })); + return; + } + assert!(s.script_pump().is_none(), "the run waits at its folder dialog"); + } + panic!("the run did not open its folder dialog"); +} + +/// Runs `source` in the app as [`start_allowed`] starts it, to its end. +fn run_allowed(s: &mut Session, dir: &std::path::Path, source: &str) -> Result { + start_allowed(s, dir, source); + let r = loop { + if let Some(r) = s.script_pump() { + break r; + } + }; + s.script_frames = false; + r +} + #[test] fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { - let path = std::env::temp_dir().join(format!("vc-script-batch-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("batch"); + let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); let source = format!( @@ -257,24 +293,90 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { {{command: 'document.export', params: {{path: {p:?}, format: 'svg'}}}},\ {{command: 'no.such', params: {{}}}}]}}); }} catch (e) {{ vc.log(e.name); }}" ); - let r = run(&mut s, &source).unwrap(); + let r = run_allowed(&mut s, &dir, &source).unwrap(); assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay"); assert!(path.exists()); assert_eq!(r["written"], json!([p]), "{r}"); - let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir_all(&dir); } #[test] fn an_export_that_fails_names_no_file() { - let path = std::env::temp_dir().join(format!("vc-script-no-folder-{}", std::process::id())).join("out.svg"); + let dir = fresh_folder("no-folder"); + let path = dir.join("missing").join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); let source = format!("try {{ vc.run('document.export', {{path: {p:?}, format: 'svg'}}); }} catch (e) {{ vc.log(e.name); }}"); - let r = run(&mut s, &source).unwrap(); + let r = run_allowed(&mut s, &dir, &source).unwrap(); assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!path.exists()); assert_eq!(r["written"], json!([]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The commands a script runs read and write only where its `File` and `Folder` objects may (its +/// temporary folder and what a person allowed it, here), and the files of the open documents. +#[test] +fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { + let dir = fresh_folder("gate"); + let (inside, outside) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let call = |id: &str, path: &std::path::Path| { + let p = path.to_string_lossy().into_owned(); + let format = if id == "document.export" { ", format: 'svg'" } else { "" }; + format!( + "try {{ vc.run('{id}', {{path: {p:?}{format}}}); vc.log('ok'); }} catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) + }; + let mut s = two_docs(); + let r = run(&mut s, &call("document.export", &outside.join("a.svg"))).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "a script given as text writes nowhere: {r}"); + assert!(!outside.join("a.svg").exists()); + let source = format!("{}{}", call("document.export", &inside.join("b.svg")), call("document.export", &outside.join("c.svg"))); + let r = run_allowed(&mut s, &inside, &source).unwrap(); + assert_eq!(r["log"], json!(["ok", "denied"]), "{r}"); + assert!(inside.join("b.svg").exists() && !outside.join("c.svg").exists()); + let r = run(&mut s, "var t = Folder.temp.fsName + '/t.svg'; vc.run('document.export', {path: t, format: 'svg'}); vc.log(new File(t).exists);") + .unwrap(); + assert_eq!(r["log"], json!([true]), "the run's temporary folder: {r}"); + let own = outside.join("own.svg"); + s.execute("document.save", &json!({"path": own.to_string_lossy()})).unwrap(); + std::fs::copy(&own, outside.join("copy.svg")).unwrap(); + let source = format!( + "vc.run('shape.rectangle', {{x: 1, y: 1, width: 1, height: 1}});\n{}{}{}{}", + call("document.save", &own), + call("document.open", &own), + call("document.open", &outside.join("copy.svg")), + call("document.save", &outside.join("other.svg")) + ); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}"); + assert!(!outside.join("other.svg").exists()); + std::fs::remove_file(&own).unwrap(); + let r = run(&mut s, &call("document.save", &own)).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); + assert!(own.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A command a script runs does not save into the app's own libraries; the same command run +/// outside a script does. +#[test] +fn a_scripts_commands_do_not_save_into_the_apps_libraries() { + let dir = fresh_folder("gate-library"); + let user = dir.join("user"); + let mut s = two_docs(); + s.swatch_libraries.set_user_dir(Some(user.to_string_lossy().into_owned())); + let source = "try { vc.run('swatch.library.save', {user: true, name: 'Mine'}); vc.log('ok'); } \ + catch (e) { vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }"; + let r = run(&mut s, source).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "{r}"); + assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder"); + s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap(); + assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -341,17 +443,18 @@ fn a_command_whose_result_cannot_cross_is_put_back() { #[test] fn an_abandoned_run_reports_the_files_it_wrote() { - let path = std::env::temp_dir().join(format!("vc-script-abandon-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("abandon"); + let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); - paused(&mut s, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}")); - assert!(path.exists(), "the first slice exported"); + start_allowed(&mut s, &dir, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}")); + assert!(s.script_pump().is_none()); + assert!(path.exists(), "the slice after the dialog exported"); assert!(s.script_abandon()); let report = s.script_report().unwrap(); assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}"); assert!(s.script_failure_text().unwrap().contains(&p)); - let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -881,19 +984,19 @@ fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { #[test] fn a_file_saved_before_a_failure_stays_written_and_is_named() { - let path = std::env::temp_dir().join(format!("vc-script-save-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("save"); + let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); let before = state(&s); let source = format!("vc.run('file.saveAs', {{path: {p:?}}}); vc.run('shape.rectangle', {{x:1,y:1,width:1,height:1}}); throw new Error('later');"); - let e = run(&mut s, &source).unwrap_err().to_string(); + let e = run_allowed(&mut s, &dir, &source).unwrap_err().to_string(); assert!(path.exists()); assert!(e.contains(&p), "{e}"); assert_eq!(s.script_report().unwrap()["written"], json!([p])); assert_eq!(state(&s), before, "the document does not keep the new path"); - let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_dir_all(&dir); } /// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope @@ -918,16 +1021,13 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() { } }; let mut s = two_docs(); - s.script_frames = true; let confined_target = outside.join("confined.svg"); - let started = crate::file_access::confine(Some(&roots), || run(&mut s, &export(&confined_target))).unwrap(); - assert_eq!(started["running"], true); + crate::file_access::confine(Some(&roots), || start_allowed(&mut s, &dir, &export(&confined_target))); let r = crate::file_access::unconfined(|| finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["Error"]), "a confined caller's run stays confined: {r}"); assert!(!confined_target.exists()); let user_target = outside.join("user.svg"); - let started = crate::file_access::unconfined(|| run(&mut s, &export(&user_target))).unwrap(); - assert_eq!(started["running"], true); + crate::file_access::unconfined(|| start_allowed(&mut s, &dir, &export(&user_target))); let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}"); assert!(user_target.exists()); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 301b1235a4..92db4e6502 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -478,6 +478,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe units.extend(MID.encode_utf16()); units.extend_from_slice(&body.flat()); units.extend(TAIL.encode_utf16()); + interp.observe_code(&units); interp.source_units = interp.source_units.saturating_add(units.len()); let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len())); let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() }; @@ -557,6 +558,7 @@ fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult> { Ok((this_run && matches!(h, Value::Number(n) if n >= 0.0)).then_some(h)) } -/// Closes the object's open file, if it has one. -fn close_open(i: &mut Interp, o: ObjId) -> JsResult<()> { +/// Closes the object's open file, if it has one, which writes what the script wrote to it. → false +/// after setting `error` when that could not be written. +fn close_open(i: &mut Interp, o: ObjId) -> JsResult { + let mut written = true; if let Some(h) = is_open(i, o)? { - host(i, "close", &[h])?; + let r = host(i, "close", &[h])?; + written = outcome(i, o, &r)?; } - set_slot(i, o, HANDLE, Value::Number(-1.0)) + set_slot(i, o, HANDLE, Value::Number(-1.0))?; + Ok(written) } fn date(i: &mut Interp, ms: Value) -> JsResult { @@ -375,7 +385,10 @@ fn get_relative_uri(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsR fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, _) = this_path(i, &this, "changePath")?; - close_open(i, o)?; + // An object whose changes could not be written keeps its path; `error` says why. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } let p = parse(i, &arg(args, 0))?; let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; set_slot(i, o, PATH, fs)?; @@ -409,30 +422,282 @@ fn to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult { - let (o, _) = this_path(i, &this, "write")?; - let m = message(i, "noWrites")?; +/// Whether the host's answer `r` is not `{error}`; when it is, the object's `error` is set to it. +fn outcome(i: &mut Interp, o: ObjId, r: &Value) -> JsResult { + let error = i.rooted(std::slice::from_ref(r), |i| field(i, r, "error"))?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(false); + } + Ok(true) +} + +/// Calls the host function `name` with the object's path and `args`. → whether it did the work. +fn path_call(i: &mut Interp, this: &Value, what: &str, name: &str, args: &[Value]) -> JsResult { + let (o, path) = this_path(i, this, what)?; + let mut all = vec![path]; + all.extend_from_slice(args); + let r = i.rooted(&all, |i| host(i, name, &all))?; + Ok(Value::Bool(outcome(i, o, &r)?)) +} + +/// `createAlias`: not available, so it sets `error` and returns `false`. +fn create_alias(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "createAlias")?; + let m = message(i, "noAlias")?; set_slot(i, o, ERROR, m)?; Ok(Value::Bool(false)) } -/// A setter that writes: it sets `error` and changes nothing. -fn no_writes_setter(i: &mut Interp, this: Value, args: &[Value], construct: bool) -> JsResult { - no_writes(i, this, args, construct)?; +/// Setting `hidden`: not available, so it sets `error` and changes nothing. +fn set_hidden(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "hidden")?; + let m = message(i, "noHidden")?; + set_slot(i, o, ERROR, m)?; Ok(Value::Undefined) } -/// A dialog method: it sets `error` and returns `null`. -fn no_picker(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - let (o, _) = this_path(i, &this, "dialog")?; - let m = message(i, "noPicker")?; - set_slot(i, o, ERROR, m)?; - Ok(Value::Null) +/// `remove()`: the file, or the folder when it is empty, deleted at once. +fn remove(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "remove")?; + // A file whose changes could not be written is not removed; `error` says why. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } + path_call(i, &this, "remove", "remove", &[]) } -fn null_static(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Ok(Value::Null) +/// `rename(name)`: the object's file or folder named `name`, in the same folder; the object takes +/// the new path. +fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "rename")?; + let name = Value::String(i.to_str(&arg(args, 0))?); + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } + let r = i.rooted(&[path.clone(), name.clone()], |i| host(i, "rename", &[path.clone(), name.clone()]))?; + if !outcome(i, o, &r)? { + return Ok(Value::Bool(false)); + } + let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; + set_slot(i, o, PATH, fs)?; + Ok(Value::Bool(true)) +} + +/// `copy(target)`: the file copied to `target`, a path or a `File`, replacing a file there. +fn copy(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "copy")?; + let p = parse(i, &arg(args, 0))?; + let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; + i.rooted(std::slice::from_ref(&fs), |i| path_call(i, &this, "copy", "copy", std::slice::from_ref(&fs))) +} + +/// `Folder.prototype.create()`: the folder, with the folders above it that are missing. +fn create(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + path_call(i, &this, "create", "create", &[]) +} + +/// Setting `length`: the file cut, or filled with zero bytes, to that many bytes. +fn set_length(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "length")?; + let n = i.to_number(&arg(args, 0))?; + if !n.is_finite() || n < 0.0 { + return Err(i.throw(ErrorType::Range, "File.length: the length must be a finite number, 0 or more")); + } + path_call(i, &this, "length", "setLength", &[Value::Number(n.floor())])?; + Ok(Value::Undefined) +} + +/// Setting `readonly`. +fn set_readonly(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "readonly")?; + let on = arg(args, 0).truthy(); + path_call(i, &this, "readonly", "setReadonly", &[Value::Bool(on)])?; + Ok(Value::Undefined) +} + +/// The line end the object's `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF for +/// anything else, without regard to case. +fn line_end(i: &Interp, o: ObjId) -> JsResult<&'static str> { + Ok(match slot(i, o, LINE_FEED)? { + Value::String(s) => match s.to_rust_string().to_ascii_lowercase().as_str() { + "windows" => "\r\n", + "macintosh" => "\r", + _ => "\n", + }, + _ => "\n", + }) +} + +/// `write(...values)` and, with `line`, `writeln(...values)`: the values as `String(value)` gives +/// them, written at the position of the object's open file. The values are joined only for an open +/// file, and only while the text stays within twice the host's `maxWrite` UTF-16 code units: each +/// character takes at least one byte and at most two code units, so a longer text cannot fit in a +/// file, and the write sets `error` to the host's `tooLarge` and returns `false`. +fn write_values(i: &mut Interp, this: &Value, args: &[Value], what: &str, line: bool) -> JsResult { + let (o, _) = this_path(i, this, what)?; + let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) }; + let c = classes(i)?; + let max = match i.get_value(&Value::Object(c.host), &key("maxWrite"))? { + Value::Number(n) if n.is_finite() && n >= 0.0 => (n as usize).saturating_mul(2), + _ => usize::MAX, + }; + let mut text = String::new(); + let mut units = 0usize; + for a in args { + i.use_fuel()?; + let s = i.to_str(a)?; + units = units.saturating_add(s.len()); + if units > max { + let m = message(i, "tooLarge")?; + set_slot(i, o, ERROR, m)?; + return Ok(Value::Bool(false)); + } + text.push_str(&s.to_rust_string()); + } + if line { + text.push_str(line_end(i, o)?); + } + i.reserve_heap(string_bytes(text.len()))?; + let text = Value::str(&text); + let r = i.rooted(&[h.clone(), text.clone()], |i| host(i, "write", &[h.clone(), text.clone()]))?; + Ok(Value::Bool(outcome(i, o, &r)?)) +} + +fn write(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + write_values(i, &this, args, "write", false) +} + +fn writeln(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + write_values(i, &this, args, "writeln", true) +} + +// ---- file dialogs ---- + +/// The file dialogs, made from script code so the run can wait at the host's `pick` until the +/// person answers: `ask` gives `pick`'s arguments and `wrap` turns its answer into objects. A +/// `filter` that is a function is called with each file picked, and the files it gives a false +/// value for are left out; when none is left, the dialog gives `null`. +const DIALOGS: &str = "(function (ask, pick, wrap) { + var isArray = Array.isArray; + function kept(files, filter) { + if (files === null || typeof filter !== 'function') return files; + if (!isArray(files)) return filter(files) ? files : null; + var out = []; + for (var k = 0; k < files.length; k++) if (filter(files[k])) out[out.length] = files[k]; + return out.length ? out : null; + } + function dialog(kind, self, prompt, multi, filter) { var a = ask(kind, self, prompt, multi, filter); return kept(wrap(kind, self, pick(a[0], a[1], a[2], a[3], a[4])), filter); } + return [ + function openDialog(prompt, filter, multiSelect) { return dialog('open', null, prompt, multiSelect, filter); }, + function saveDialog(prompt, filter) { return dialog('save', null, prompt, false, filter); }, + function openDlg(prompt, filter, multiSelect) { return dialog('open', this, prompt, multiSelect, filter); }, + function saveDlg(prompt, filter) { return dialog('save', this, prompt, false, filter); }, + function selectDialog(prompt) { return dialog('folder', null, prompt, false, null); }, + function selectDlg(prompt) { return dialog('folder', this, prompt, false, null); } + ]; +})"; + +/// `ask(kind, self, prompt, multi, filter)`: `[kind, prompt, multi, start, filter]`, the arguments +/// of the host's `pick`, where `start` is the path of `self` (a `File` or `Folder`, or `null` for the +/// class's own dialog) and `filter` the file types, a string, or `""` for any other value. `self` +/// must be a `File` or `Folder` when it is not `null`. +fn ask(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let kind = arg(args, 0); + let start = match arg(args, 1) { + Value::Null => Value::str(""), + s => this_path(i, &s, "dialog")?.1, + }; + let prompt = match arg(args, 2) { + Value::Undefined | Value::Null => Value::str(""), + p => Value::String(i.to_str(&p)?), + }; + let multi = Value::Bool(arg(args, 3).truthy()); + let filter = match arg(args, 4) { + f @ Value::String(_) => f, + _ => Value::str(""), + }; + i.rooted(&[kind.clone(), start.clone(), prompt.clone(), filter.clone()], |i| { + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES)?; + let proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto))); + i.rooted(&[Value::Object(out)], |i| { + for (at, v) in [kind.clone(), prompt.clone(), multi.clone(), start.clone(), filter.clone()].into_iter().enumerate() { + put_at(i, out, at as f64, v)?; + } + Ok(Value::Object(out)) + }) + }) +} + +/// `wrap(kind, self, answer)`: the `File` (a `Folder` for a folder dialog) for each path `pick` +/// gave, an array of them for a list, `null` for `null`, and `null` after setting `self`'s `error` +/// for `{error}`. +fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let c = classes(i)?; + let proto = if matches!(arg(args, 0), Value::String(s) if s.to_rust_string() == "folder") { c.folder_proto } else { c.file_proto }; + let answer = arg(args, 2); + match &answer { + Value::String(_) => return instance(i, proto, answer.clone()), + Value::Object(_) => {} + _ => return Ok(Value::Null), + } + let error = i.rooted(std::slice::from_ref(&answer), |i| field(i, &answer, "error"))?; + if matches!(error, Value::String(_)) { + if let Some(o) = arg(args, 1).as_object() + && matches!(slot(i, o, PATH)?, Value::String(_)) + { + set_slot(i, o, ERROR, error)?; + } + return Ok(Value::Null); + } + i.rooted(std::slice::from_ref(&answer), |i| { + let length = i.get_value(&answer, &key("length"))?; + let n = i.to_number(&length)?; + i.reserve_heap(OBJECT_BYTES)?; + let array_proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(array_proto))); + i.rooted(&[Value::Object(out)], |i| { + let mut at = 0.0; + while at < n { + i.use_fuel()?; + let fs = i.get_value(&answer, &crate::value::number_to_str(at).flat())?; + let item = i.rooted(std::slice::from_ref(&fs), |i| instance(i, proto, fs.clone()))?; + put_at(i, out, at, item)?; + at += 1.0; + } + Ok(Value::Object(out)) + }) + }) +} + +/// Defines the file dialogs on `File`, `Folder` and their prototypes. +fn dialogs(i: &mut Interp, file: ObjId, file_proto: ObjId, folder: ObjId, folder_proto: ObjId) -> JsResult<()> { + let units = i.encode_source(DIALOGS).map_err(|e| i.compile_error_to_abrupt(e))?; + let code = i.compile_source(&units, false, CodeKind::Eval).map_err(|e| i.compile_error_to_abrupt(e))?; + let make = i.run_global(code, true)?; + let c = classes(i)?; + let pick = i.rooted(std::slice::from_ref(&make), |i| i.get_value(&Value::Object(c.host), &key("pick")))?; + let ask = native(i, "ask", ask, 5, NativeKind::Plain, false)?; + let made = i.rooted(&[make.clone(), pick.clone(), Value::Object(ask)], |i| { + let wrap = native(i, "wrap", wrap, 3, NativeKind::Plain, false)?; + i.call(&make, &Value::Undefined, &[Value::Object(ask), pick.clone(), Value::Object(wrap)]) + })?; + let on = [ + (file, "openDialog"), + (file, "saveDialog"), + (file_proto, "openDlg"), + (file_proto, "saveDlg"), + (folder, "selectDialog"), + (folder_proto, "selectDlg"), + ]; + i.rooted(std::slice::from_ref(&made), |i| { + for (at, (target, name)) in on.into_iter().enumerate() { + let f = i.get_value(&made, &crate::value::number_to_str(at as f64).flat())?; + data(i, target, name, f, HIDDEN)?; + } + Ok(()) + }) } fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { @@ -530,19 +795,18 @@ fn open(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult Value::Undefined => "r".to_string(), m => i.to_str(&m)?.to_rust_string().to_lowercase(), }; - let refusal = match mode.as_str() { - "r" => None, - "w" | "e" | "a" => Some("noWrites"), - _ => Some("badMode"), - }; - if let Some(name) = refusal { - let m = message(i, name)?; + if !matches!(mode.as_str(), "r" | "w" | "e" | "a") { + let m = message(i, "badMode")?; set_slot(i, o, ERROR, m)?; return Ok(Value::Bool(false)); } - close_open(i, o)?; + // The object's earlier changes are written first; when they cannot be, it does not open again. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } let encoding = slot(i, o, ENCODING)?; - let r = host(i, "open", &[path, encoding])?; + let mode = Value::str(&mode); + let r = host(i, "open", &[path, encoding, mode])?; let (error, id) = i.rooted(std::slice::from_ref(&r), |i| Ok((field(i, &r, "error")?, field(i, &r, "id")?)))?; if matches!(error, Value::String(_)) { set_slot(i, o, ERROR, error)?; @@ -559,8 +823,7 @@ fn close(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if opened(i, o)?.is_none() { return Ok(Value::Bool(false)); } - close_open(i, o)?; - Ok(Value::Bool(true)) + Ok(Value::Bool(close_open(i, o)?)) } fn read(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -669,7 +932,7 @@ fn set_current(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult`: a new `Folder` for the host's location `place`, or `null`. fn place(i: &mut Interp, place: &str) -> JsResult { - let all = host(i, "locations", &[])?; + let all = host(i, "locations", &[Value::str(place)])?; let fs = i.rooted(std::slice::from_ref(&all), |i| field(i, &all, place))?; if !matches!(fs, Value::String(_)) { return Ok(Value::Null); @@ -735,8 +998,8 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "changePath", change_path, 1)?; method(i, proto, "resolve", resolve, 0)?; method(i, proto, "execute", execute, 0)?; - method(i, proto, "remove", no_writes, 0)?; - method(i, proto, "rename", no_writes, 1)?; + method(i, proto, "remove", remove, 0)?; + method(i, proto, "rename", rename, 1)?; method(i, ctor, "encode", encode, 1)?; method(i, ctor, "decode", decode, 1)?; method(i, ctor, "isEncodingAvailable", encoding_available, 1)?; @@ -744,10 +1007,10 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { data(i, ctor, "fs", system, HIDDEN) } -fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { - accessor(i, proto, "length", length, Some(no_writes_setter))?; - accessor(i, proto, "hidden", hidden, Some(no_writes_setter))?; - accessor(i, proto, "readonly", readonly, Some(no_writes_setter))?; +fn file_members(i: &mut Interp, proto: ObjId) -> JsResult<()> { + accessor(i, proto, "length", length, Some(set_length))?; + accessor(i, proto, "hidden", hidden, Some(set_hidden))?; + accessor(i, proto, "readonly", readonly, Some(set_readonly))?; accessor(i, proto, "creator", four_question_marks, None)?; accessor(i, proto, "type", four_question_marks, None)?; accessor(i, proto, "eof", eof, None)?; @@ -760,21 +1023,15 @@ fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "readch", read_char, 0)?; method(i, proto, "seek", seek, 2)?; method(i, proto, "tell", tell, 0)?; - method(i, proto, "write", no_writes, 1)?; - method(i, proto, "writeln", no_writes, 1)?; - method(i, proto, "copy", no_writes, 1)?; - method(i, proto, "createAlias", no_writes, 1)?; - method(i, proto, "openDlg", no_picker, 0)?; - method(i, proto, "saveDlg", no_picker, 0)?; - method(i, ctor, "openDialog", null_static, 0)?; - method(i, ctor, "saveDialog", null_static, 0) + method(i, proto, "write", write, 1)?; + method(i, proto, "writeln", writeln, 1)?; + method(i, proto, "copy", copy, 1)?; + method(i, proto, "createAlias", create_alias, 1) } fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "getFiles", get_files, 1)?; - method(i, proto, "create", no_writes, 0)?; - method(i, proto, "selectDlg", no_picker, 0)?; - method(i, ctor, "selectDialog", null_static, 0)?; + method(i, proto, "create", create, 0)?; accessor(i, ctor, "current", get_current, Some(set_current))?; for (place, get) in PLACES.into_iter().zip(PLACE_GETTERS) { accessor(i, ctor, place, get, None)?; @@ -814,8 +1071,9 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul constructor(i, "Folder", folder, folder_proto)?; common(i, file, file_proto)?; common(i, folder, folder_proto)?; - file_members(i, file, file_proto)?; - folder_members(i, folder, folder_proto) + file_members(i, file_proto)?; + folder_members(i, folder, folder_proto)?; + dialogs(i, file, file_proto, folder, folder_proto) }) } @@ -847,7 +1105,7 @@ mod tests { ("parent", Data::String("/".into())), ]) }; - let messages = ["notOpen", "noWrites", "noPicker", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); + let messages = ["notOpen", "badMode", "noAlias", "noHidden"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); let stat = move |a: Vec| -> Result { let dir = text(&a, 0) == "/d"; Ok(obj(vec![("exists", Data::Bool(dir)), ("dir", Data::Bool(dir))])) diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index fbb5e4fc90..375312f497 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -412,7 +412,12 @@ impl Interp { Ok(units) => self.prepare_source(units.len().saturating_sub(floor)), Err(_) => Ok(()), }; - rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval))) + rest.map(|()| { + units.and_then(|units| { + self.observe_code(&units); + self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval) + }) + }) }); let code = code.and_then(|c| c); self.source_tag = tag; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index de252c6c64..afd300c807 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -638,6 +638,24 @@ fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unkn assert_eq!(r.error_source(), 0, "a syntax error is in the script"); } +#[test] +fn the_code_observer_sees_every_source_evaluated_at_run_time() { + let mut r = realm(10_000_000); + let seen = Rc::new(RefCell::new(Vec::::new())); + let s = seen.clone(); + r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units))); + let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap(); + assert_eq!(out, JsValue::Number(49.0)); + let want = ["1 + 1", "2", "(function anonymous(a\n) {\nreturn a\n})", "40 + 2"]; + assert_eq!(*seen.borrow(), want, "the script's own text is not observed"); + seen.borrow_mut().clear(); + r.run("eval(7); Function.prototype.toString.call(f)").unwrap(); + assert!(seen.borrow().is_empty(), "eval of a value that is not a string compiles nothing"); +} + #[test] fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { let mut r = realm(10_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 22a365b615..2cbc5ae9cf 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -162,6 +162,9 @@ pub(crate) struct Frame { /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. +pub(crate) type CodeObserver = Rc; + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -230,6 +233,9 @@ pub(crate) struct Interp { pub(crate) source_tag: u32, /// The sources [`crate::HostItem::Evaluator`] functions have given in this realm. pub(crate) evaluated: u32, + /// Called with the source text given to `eval`, `Function` and evaluator functions, before it + /// is compiled ([`crate::Realm::observe_code`]). + pub(crate) code_observer: Option, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, /// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is @@ -468,6 +474,7 @@ impl Interp { data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, + code_observer: None, error_tag: crate::realm::UNKNOWN_SOURCE, thrown_mark: None, finally_marks: Vec::new(), @@ -2422,6 +2429,13 @@ impl Interp { crate::to_utf16(text, &self.remaining_source_options()).map_err(CompileError::Syntax) } + /// Gives `units`, source a script evaluates at run time, to the realm's code observer. + pub(crate) fn observe_code(&self, units: &[u16]) { + if let Some(f) = &self.code_observer { + f(units); + } + } + /// Parses and compiles source for eval code or a script, counting it against the source /// limit. pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result, CompileError> { @@ -2460,6 +2474,7 @@ impl Interp { self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?; self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; + self.observe_code(&units); let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 077f3b19b6..fbef8911c2 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -457,10 +457,12 @@ impl Realm { /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, - /// `encode`, `decode`, `encodingAvailable`, `current` and `locations`, with the values `system` - /// and `lineFeed` and the messages `text.notOpen`, `text.noWrites`, `text.noPicker` and - /// `text.badMode`. Each object keeps its path, its `error` text, its open file's id, its - /// encoding and its line feed in properties that are not enumerable. + /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file + /// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and + /// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`, + /// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error` + /// text, its open file's id, its encoding and its line feed in properties that are not + /// enumerable. pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { match crate::file_classes::install(&mut self.interp, items) { Ok(()) => Ok(()), @@ -532,6 +534,14 @@ impl Realm { self.interp.date_host.offset = std::rc::Rc::new(offset); } + /// Calls `observe` with the text of each source the realm's scripts evaluate at run time, before + /// it is compiled: a string given to `eval` (direct or indirect), the parameters and body + /// `Function` joins, and a source an evaluator host function + /// ([`crate::HostItem::Evaluator`]) gives. Replaces an earlier observer. + pub fn observe_code(&mut self, observe: impl Fn(&[u16]) + 'static) { + self.interp.code_observer = Some(std::rc::Rc::new(observe)); + } + /// Collects garbage now and returns the heap's estimated size in bytes afterwards. pub fn collect_garbage(&mut self) -> usize { self.interp.collect_garbage(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 67e67ac444..193e35b8dd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -177,6 +177,8 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + script_picked: Vec::new(), + script_picked_left_out: false, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 197f8faaaa..8140dca6d6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -422,6 +422,7 @@ registry! { ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, + ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -671,6 +672,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::NOTICE_KIND { script_run::notice_cancel(app, &d); } + if d.kind == script_run::PICKER_KIND { + script_run::picker_cancel(app, &d); + } // Toolbar-only Flare options start no preview and must not cancel a gesture // that was already active before opening them. The generic parameter dialog has a spec // without a preview, yet previews some commands (Grid Repeat Options) when asked to. diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 8f5e3b1093..f8baa7b7de 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -13,10 +13,22 @@ //! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer. //! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert. //! Stop ends the run and puts back everything it did. +//! +//! A script's file dialog (kind `scriptFiles`: `File.openDialog`, `File.saveDialog`, +//! `Folder.selectDialog` and the objects' `openDlg`, `saveDlg` and `selectDlg`) has the fields +//! `kind` (open, save or folder), `prompt` and `canAlways`, and takes `answer`: `once`, `always` +//! (only with `canAlways`), `deny` or `stop`. Only the person at the keyboard answers `once` or +//! `always`: from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input they are refused, and the +//! dialog stays open; `deny` and `stop` are taken from automation too. The paths it allows are the +//! ones Choose… picked in the host's file dialog, at most 2,048; `ui.dialog.set` cannot set them, +//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape, +//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny. +//! `selectDlg` opens the host's folder picker in its own folder. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; use super::{DialogAction, DialogSpec}; @@ -32,6 +44,19 @@ pub const GROWTH_KIND: &str = "scriptGrowth"; pub const CLOSE_KIND: &str = "scriptClose"; /// The dialog kind of a script's `alert`, `confirm` and `prompt`. pub const NOTICE_KIND: &str = "scriptDialog"; +/// The dialog kind of a script's file dialogs. +pub const PICKER_KIND: &str = "scriptFiles"; + +pub(super) const PICKER_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Script File Access").into(), + body_with_actions: Some(picker_body), + confirm: picker_confirm, + ok: None, + inputs: |_| &["answer"], + min_width: 420.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec { heading: notice_heading, @@ -171,7 +196,7 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); if app.ui.dialog.is_some() { return; } @@ -192,6 +217,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { if !app.session.script_running() { app.ui.dialog = None; } else if app.session.script_dialog().is_none() + && app.session.script_picker().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); @@ -327,6 +353,192 @@ fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result = match p.kind { + PickerKind::Open if several => crate::picks::open_files(app, &pick), + PickerKind::Open => crate::picks::open(app, &pick).into_iter().collect(), + PickerKind::Save => crate::picks::save(app, &pick).into_iter().collect(), + // `selectDlg` starts in its folder; `Folder.selectDialog` gives none. + PickerKind::Folder => match p.start.clone() { + Some(start) => crate::picks::folder_at(app, &start).into_iter().collect(), + None => crate::picks::folder(app).into_iter().collect(), + }, + }; + if !chosen.is_empty() { + let mut paths = if several { std::mem::take(&mut app.script_picked) } else { Vec::new() }; + let mut seen: std::collections::HashSet = paths.iter().cloned().collect(); + for path in chosen { + if seen.contains(&path) { + continue; + } + if paths.len() >= MAX_ENTRIES { + app.script_picked_left_out = true; + break; + } + seen.insert(path.clone()); + paths.push(path); + } + app.script_picked = paths; + } + Ok(()) + }); + // Picking a path doesn't fail. + let _ = r; +} + +/// The dialog's prompt and the access it describes come from the request the run waits at, not +/// from the dialog's fields, so `ui.dialog.set` cannot change what the person reads. +fn picker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let t = Tokens::get(ui.ctx()); + let Some((kind, prompt)) = app.session.script_picker().map(|p| (p.kind, shown_text(&p.prompt, true))) else { return DialogAction::None }; + if !prompt.is_empty() { + egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| ui.label(&prompt)); + ui.add_space(8.0); + } + ui.label(picker_request(kind)); + ui.add_space(8.0); + let paths = app.script_picked.clone(); + ui.horizontal(|ui| { + if widgets::secondary_button(ui, tl!("Choose…")).clicked() { + choose(app, d); + } + ui.add_space(8.0); + if let [path] = paths.as_slice() { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + if paths.len() > 1 { + ui.add_space(4.0); + egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, |ui| { + for path in &paths { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + } + if app.script_picked_left_out { + ui.add_space(4.0); + ui.colored_label(t.error, crate::i18n::msg(PICKED_LEFT_OUT)); + } + ui.add_space(16.0); + let chosen = !app.script_picked.is_empty(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let mut answer = None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::primary_button_enabled(ui, tl!("Allow Once"), chosen).clicked() { + answer = Some("once"); + } + ui.add_space(8.0); + if can_always { + if ui.add_enabled_ui(chosen, |ui| widgets::secondary_button(ui, tl!("Always Allow This Script"))).inner.clicked() { + answer = Some("always"); + } + ui.add_space(8.0); + } + if widgets::secondary_button(ui, tl!("Deny")).clicked() { + answer = Some("deny"); + } + // The row runs right to left: Stop goes at its left end. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, tl!("Stop")).clicked() { + answer = Some("stop"); + } + }); + }); + // Enter gives the dialog's default answer, Deny, as `ui.dialog.confirm` without an answer does, + // unless it goes to the button that has the keyboard focus (Choose…). + let unfocused = ui.ctx().memory(|m| m.focused().is_none()); + if answer.is_none() && unfocused && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + answer = Some("deny"); + } + let Some(answer) = answer else { return DialogAction::None }; + d.fields.insert("answer".into(), json!(answer)); + DialogAction::Confirm +} + +/// What the file dialog of `kind` asks the person to allow. +fn picker_request(kind: PickerKind) -> &'static str { + match kind { + PickerKind::Open => tl!("The script asks to read a file you choose."), + PickerKind::Save => tl!("The script asks to read and write a file you choose."), + PickerKind::Folder => tl!("The script asks to read and write a folder you choose, with everything in it."), + } +} + +/// The note the file dialog shows when the person picked more files than a script is given. +const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; + +/// Gives the running script the file dialog's `answer`, or Deny. +fn picker_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or("deny"); + give_pick(app, answer) +} + +/// Escape or Cancel: Deny. +pub(super) fn picker_cancel(app: &mut VectorcraftApp, _: &Dialog) { + let _ = give_pick(app, "deny"); +} + +/// Gives the running script `answer` with the paths Choose… picked. Only the person at the keyboard +/// allows access: Allow Once and Always Allow are refused, and the dialog stays open, while +/// automation sends the answer (a control or MCP request, or synthetic input) or opened the host's +/// file dialog; Deny and Stop are taken from anyone. +fn give_pick(app: &mut VectorcraftApp, answer: &str) -> Result { + let paths = app.script_picked.clone(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let given = match answer { + "stop" => None, + "deny" => Some(PickAnswer::Deny), + "once" | "always" if app.automation_asked() => return Err("Only the person at the keyboard can allow a script's file access".into()), + "once" | "always" if paths.is_empty() => return Err("choose a file or folder first, or deny".into()), + "always" if !can_always => return Err("this script's file access can be allowed only once".into()), + "once" => Some(PickAnswer::Allow { paths, always: false }), + "always" => Some(PickAnswer::Allow { paths, always: true }), + _ => return Err("`answer` for a script's file dialog must be one of: once, always, deny, stop".into()), + }; + app.script_picked.clear(); + app.script_picked_left_out = false; + match given { + None => { + app.session.script_request_stop(); + } + Some(a) => { + app.session.script_pick(a); + } + } + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PICKER_KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) +} + fn answers_for(kind: &str) -> &'static str { match kind { "confirm" => "yes, no, stop", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..f69fbaaf2d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4094,6 +4094,13 @@ axis Both И двете Show External Script Warning Показвай предупреждение за външни скриптове A Script Is Running Изпълнява се скрипт Script Alert Известие от скрипт + Script File Access Достъп на скрипт до файлове + The script asks to read a file you choose. Скриптът иска да прочете файл, който изберете. + The script asks to read and write a file you choose. Скриптът иска да чете и записва файл, който изберете. + The script asks to read and write a folder you choose, with everything in it. Скриптът иска да чете и записва папка, която изберете, с цялото ѝ съдържание. + Allow Once Разреши веднъж + Always Allow This Script Винаги разрешавай този скрипт + Deny Откажи A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..7dae2382aa 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4459,6 +4459,13 @@ imageTrace Outline Obris Show External Script Warning Prikaži upozorenje za vanjske skripte A Script Is Running Skripta se izvršava Script Alert Upozorenje skripte + Script File Access Pristup skripte datotekama + The script asks to read a file you choose. Skripta traži da pročita datoteku koju odaberete. + The script asks to read and write a file you choose. Skripta traži da čita i piše datoteku koju odaberete. + The script asks to read and write a folder you choose, with everything in it. Skripta traži da čita i piše folder koji odaberete, sa svim što je u njemu. + Allow Once Dozvoli jednom + Always Allow This Script Uvijek dozvoli ovu skriptu + Deny Odbij A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..03f88d8386 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5390,6 +5390,13 @@ digits Malayalam Malaiàlam Show External Script Warning Mostra l'avís dels scripts externs A Script Is Running S'està executant un script Script Alert Avís de l'script + Script File Access Accés de l’script als fitxers + The script asks to read a file you choose. L’script demana llegir un fitxer que trieu. + The script asks to read and write a file you choose. L’script demana llegir i escriure un fitxer que trieu. + The script asks to read and write a folder you choose, with everything in it. L’script demana llegir i escriure una carpeta que trieu, amb tot el que conté. + Allow Once Permet un cop + Always Allow This Script Permet sempre aquest script + Deny Denega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. @@ -5418,8 +5425,6 @@ digits Malayalam Malaiàlam @msg Script file could not be read No s'ha pogut llegir el fitxer de l'script @msg Script folder has more than 2,048 entries La carpeta de l'script té més de 2.048 entrades @msg Script file open mode must be r, w, e or a El mode d'obertura del fitxer de l'script ha de ser r, w, e o a -@msg Script file writing is not available L'escriptura de fitxers de l'script no està disponible -@msg Script file dialogs are not available Els quadres de diàleg de fitxers de l'script no estan disponibles @msg Script files cannot be opened in another application Els fitxers de l'script no es poden obrir en una altra aplicació @msg Script file access is unavailable on the web L'accés als fitxers de l'script no està disponible al web @msg Script has 256 files open L'script té 256 fitxers oberts @@ -5490,6 +5495,27 @@ digits Malayalam Malaiàlam @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script +@msg Script file access denied: {path} S’ha denegat l’accés de l’script als fitxers: {path} +@msg Script file access to the app's own folders is not allowed Els scripts no poden accedir a les carpetes pròpies de l’aplicació +@msg Script file cannot encode the text El fitxer de l’script no pot codificar el text +@msg Script file could not be written No s’ha pogut escriure el fitxer de l’script +@msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui +@msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi +@msg Script file name is already in use El nom del fitxer de l’script ja està en ús +@msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta +@msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer +@msg Script file permission could not be saved No s’ha pogut desar el permís de fitxers de l’script +@msg Script folder is not empty La carpeta de l’script no és buida +@msg Script files cannot make aliases Els fitxers de l’script no poden crear àlies +@msg Script file hidden setting cannot be changed No es pot canviar l’opció d’ocult del fitxer de l’script +@msg {name}: a file 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 diàleg de fitxers no es pot obrir dins d’una crida de retorn d’una funció integrada, d’un getter, d’una conversió o d’un fitxer que executa $.evalFile; crideu-lo des del codi propi de l’script +@msg the script wrote more file data than one run may write (32 MiB) l’script ha escrit més dades de fitxers de les que pot escriure una execució (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop +@msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu +@msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada +@msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora @msg Corners edits the corners of a path Cantonades edita les cantonades d’un traçat @msg could not decode image: {0} no s’ha pogut descodificar la imatge: {0} @msg Couldn't copy to the system clipboard: {e} No s’ha pogut copiar al porta-retalls del sistema: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..f57201ed46 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4521,6 +4521,13 @@ imageTrace Outline Obrys Show External Script Warning Zobrazit upozornění u externích skriptů A Script Is Running Běží skript Script Alert Upozornění skriptu + Script File Access Přístup skriptu k souborům + The script asks to read a file you choose. Skript žádá o čtení souboru, který vyberete. + The script asks to read and write a file you choose. Skript žádá o čtení a zápis souboru, který vyberete. + The script asks to read and write a folder you choose, with everything in it. Skript žádá o čtení a zápis složky, kterou vyberete, se vším, co obsahuje. + Allow Once Povolit jednou + Always Allow This Script Vždy povolit tento skript + Deny Zamítnout A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. @@ -4549,8 +4556,6 @@ imageTrace Outline Obrys @msg Script file could not be read Soubor skriptu se nepodařilo přečíst @msg Script folder has more than 2,048 entries Složka skriptu má více než 2 048 položek @msg Script file open mode must be r, w, e or a Režim otevření souboru skriptu musí být r, w, e nebo a -@msg Script file writing is not available Zápis souborů skriptu není k dispozici -@msg Script file dialogs are not available Dialogy souborů skriptu nejsou k dispozici @msg Script files cannot be opened in another application Soubory skriptu nelze otevřít v jiné aplikaci @msg Script file access is unavailable on the web Přístup k souborům skriptu není na webu k dispozici @msg Script has 256 files open Skript má otevřeno 256 souborů @@ -4621,6 +4626,27 @@ imageTrace Outline Obrys @msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována +@msg Script file access denied: {path} Přístup skriptu k souborům byl odepřen: {path} +@msg Script file access to the app's own folders is not allowed Skript nemá povolen přístup k vlastním složkám aplikace +@msg Script file cannot encode the text Soubor skriptu nemůže zakódovat text +@msg Script file could not be written Soubor skriptu nelze zapsat +@msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví +@msg Script file is not open for writing Soubor skriptu není otevřený pro zápis +@msg Script file name is already in use Název souboru skriptu se už používá +@msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky +@msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru +@msg Script file permission could not be saved Oprávnění skriptu k souborům nelze uložit +@msg Script folder is not empty Složka skriptu není prázdná +@msg Script files cannot make aliases Soubory skriptu nemohou vytvářet aliasy +@msg Script file hidden setting cannot be changed Nastavení skrytí souboru skriptu nelze změnit +@msg {name}: a file 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 souboru nelze otevřít uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; volejte jej z vlastního kódu skriptu +@msg the script wrote more file data than one run may write (32 MiB) skript zapsal více dat souborů, než smí zapsat jeden běh (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop +@msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte +@msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou +@msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice +@msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány @msg Corners edits the corners of a path Rohy upravuje rohy cesty @msg Couldn't copy to the system clipboard: {e} Nelze kopírovat do systémové schránky: {e} @msg Couldn't open {name}: {e} {name} nelze otevřít: {e} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..3fb08554b0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4213,6 +4213,13 @@ imageTrace Outline Kontur Show External Script Warning Vis advarsel om eksterne scripts A Script Is Running Et script kører Script Alert Scriptadvarsel + Script File Access Scriptadgang til filer + The script asks to read a file you choose. Scriptet beder om at læse en fil, du vælger. + The script asks to read and write a file you choose. Scriptet beder om at læse og skrive en fil, du vælger. + The script asks to read and write a folder you choose, with everything in it. Scriptet beder om at læse og skrive en mappe, du vælger, med alt indhold. + Allow Once Tillad én gang + Always Allow This Script Tillad altid dette script + Deny Afvis A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..de0e4eb16b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4135,6 +4135,13 @@ theme Appearance Erscheinungsbild Show External Script Warning Warnung bei externen Skripten anzeigen A Script Is Running Ein Skript wird ausgeführt Script Alert Skriptmeldung + Script File Access Dateizugriff des Skripts + The script asks to read a file you choose. Das Skript möchte eine Datei lesen, die Sie auswählen. + The script asks to read and write a file you choose. Das Skript möchte eine Datei lesen und schreiben, die Sie auswählen. + The script asks to read and write a folder you choose, with everything in it. Das Skript möchte einen Ordner, den Sie auswählen, mit seinem gesamten Inhalt lesen und schreiben. + Allow Once Einmal erlauben + Always Allow This Script Dieses Skript immer erlauben + Deny Ablehnen A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. @@ -4163,8 +4170,6 @@ theme Appearance Erscheinungsbild @msg Script file could not be read Die Skriptdatei konnte nicht gelesen werden @msg Script folder has more than 2,048 entries Der Skriptordner hat mehr als 2.048 Einträge @msg Script file open mode must be r, w, e or a Der Öffnungsmodus der Skriptdatei muss r, w, e oder a sein -@msg Script file writing is not available Das Schreiben von Skriptdateien ist nicht verfügbar -@msg Script file dialogs are not available Dateidialoge für Skripte sind nicht verfügbar @msg Script files cannot be opened in another application Skriptdateien können nicht in einer anderen Anwendung geöffnet werden @msg Script file access is unavailable on the web Der Zugriff auf Skriptdateien ist im Web nicht verfügbar @msg Script has 256 files open Das Skript hat 256 Dateien geöffnet @@ -4235,6 +4240,27 @@ theme Appearance Erscheinungsbild @msg there is no script engine named {name} es gibt keine Skript-Engine namens {name} @msg Running a script Skript wird ausgeführt @msg Copied the script report Skriptbericht kopiert +@msg Script file access denied: {path} Dateizugriff des Skripts verweigert: {path} +@msg Script file access to the app's own folders is not allowed Skripte dürfen nicht auf die eigenen Ordner der App zugreifen +@msg Script file cannot encode the text Skriptdatei kann den Text nicht kodieren +@msg Script file could not be written Skriptdatei konnte nicht geschrieben werden +@msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet +@msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet +@msg Script file name is already in use Name der Skriptdatei wird bereits verwendet +@msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein +@msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird +@msg Script file permission could not be saved Dateiberechtigung des Skripts konnte nicht gespeichert werden +@msg Script folder is not empty Skriptordner ist nicht leer +@msg Script files cannot make aliases Skriptdateien können keine Aliasse erstellen +@msg Script file hidden setting cannot be changed Ausgeblendet-Einstellung der Skriptdatei kann nicht geändert werden +@msg {name}: a file 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 Dateidialog kann nicht in einem Callback einer eingebauten Funktion, eines Getters, einer Umwandlung oder einer Datei geöffnet werden, die $.evalFile ausführt; rufen Sie ihn aus dem eigenen Code des Skripts auf +@msg the script wrote more file data than one run may write (32 MiB) das Skript hat mehr Dateidaten geschrieben, als ein Lauf schreiben darf (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop +@msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab +@msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden +@msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben +@msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen @msg Corners edits the corners of a path „Ecken“ bearbeitet die Ecken eines Pfads @msg Couldn't copy to the system clipboard: {e} In die Systemzwischenablage konnte nicht kopiert werden: {e} @msg Couldn't open {name}: {e} {name} konnte nicht geöffnet werden: {e} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..b4229beada 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2309,6 +2309,13 @@ axis Both Και τα δύο Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια A Script Is Running Εκτελείται ένα σενάριο Script Alert Ειδοποίηση σεναρίου + Script File Access Πρόσβαση σεναρίου σε αρχεία + The script asks to read a file you choose. Το σενάριο ζητά να διαβάσει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a file you choose. Το σενάριο ζητά να διαβάσει και να γράψει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a folder you choose, with everything in it. Το σενάριο ζητά να διαβάσει και να γράψει έναν φάκελο που θα επιλέξετε, με όλο το περιεχόμενό του. + Allow Once Να επιτραπεί μία φορά + Always Allow This Script Να επιτρέπεται πάντα αυτό το σενάριο + Deny Άρνηση A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. @@ -2337,8 +2344,6 @@ axis Both Και τα δύο @msg Script file could not be read Δεν ήταν δυνατή η ανάγνωση του αρχείου σεναρίου @msg Script folder has more than 2,048 entries Ο φάκελος σεναρίου έχει περισσότερες από 2.048 καταχωρίσεις @msg Script file open mode must be r, w, e or a Ο τρόπος ανοίγματος του αρχείου σεναρίου πρέπει να είναι r, w, e ή a -@msg Script file writing is not available Η εγγραφή αρχείων σεναρίου δεν είναι διαθέσιμη -@msg Script file dialogs are not available Τα παράθυρα διαλόγου αρχείων σεναρίου δεν είναι διαθέσιμα @msg Script files cannot be opened in another application Τα αρχεία σεναρίου δεν μπορούν να ανοίξουν σε άλλη εφαρμογή @msg Script file access is unavailable on the web Η πρόσβαση σε αρχεία σεναρίου δεν είναι διαθέσιμη στο web @msg Script has 256 files open Το σενάριο έχει 256 ανοιχτά αρχεία @@ -2409,6 +2414,27 @@ axis Both Και τα δύο @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε +@msg Script file access denied: {path} Η πρόσβαση του σεναρίου σε αρχεία απορρίφθηκε: {path} +@msg Script file access to the app's own folders is not allowed Δεν επιτρέπεται η πρόσβαση σεναρίων στους φακέλους της ίδιας της εφαρμογής +@msg Script file cannot encode the text Το αρχείο του σεναρίου δεν μπορεί να κωδικοποιήσει το κείμενο +@msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου +@msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει +@msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή +@msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη +@msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο +@msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο +@msg Script file permission could not be saved Δεν ήταν δυνατή η αποθήκευση της άδειας αρχείων του σεναρίου +@msg Script folder is not empty Ο φάκελος του σεναρίου δεν είναι κενός +@msg Script files cannot make aliases Τα αρχεία του σεναρίου δεν μπορούν να δημιουργήσουν ψευδώνυμα +@msg Script file hidden setting cannot be changed Η ρύθμιση απόκρυψης του αρχείου του σεναρίου δεν μπορεί να αλλάξει +@msg {name}: a file 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}: ένα παράθυρο διαλόγου αρχείων δεν μπορεί να ανοίξει μέσα σε callback ενσωματωμένης συνάρτησης, getter, μετατροπής ή αρχείου που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου +@msg the script wrote more file data than one run may write (32 MiB) το σενάριο έγραψε περισσότερα δεδομένα αρχείων από όσα επιτρέπεται να γράψει μία εκτέλεση (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop +@msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε +@msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά +@msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία +@msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @msg Couldn't open {name}: {e} Δεν ήταν δυνατό το άνοιγμα του {name}: {e} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..37af97bec8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4211,6 +4211,13 @@ axis Both Ambos Show External Script Warning Mostrar advertencia de scripts externos A Script Is Running Se está ejecutando un script Script Alert Aviso del script + Script File Access Acceso del script a archivos + The script asks to read a file you choose. El script pide leer un archivo que usted elija. + The script asks to read and write a file you choose. El script pide leer y escribir un archivo que usted elija. + The script asks to read and write a folder you choose, with everything in it. El script pide leer y escribir una carpeta que usted elija, con todo su contenido. + Allow Once Permitir una vez + Always Allow This Script Permitir siempre este script + Deny Denegar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. @@ -4239,8 +4246,6 @@ axis Both Ambos @msg Script file could not be read No se pudo leer el archivo de script @msg Script folder has more than 2,048 entries La carpeta de script tiene más de 2048 entradas @msg Script file open mode must be r, w, e or a El modo de apertura del archivo de script debe ser r, w, e o a -@msg Script file writing is not available La escritura de archivos de script no está disponible -@msg Script file dialogs are not available Los cuadros de diálogo de archivos de script no están disponibles @msg Script files cannot be opened in another application Los archivos de script no se pueden abrir en otra aplicación @msg Script file access is unavailable on the web El acceso a archivos de script no está disponible en la web @msg Script has 256 files open El script tiene 256 archivos abiertos @@ -4311,6 +4316,27 @@ axis Both Ambos @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script +@msg Script file access denied: {path} Acceso del script a archivos denegado: {path} +@msg Script file access to the app's own folders is not allowed El script no puede acceder a las carpetas propias de la aplicación +@msg Script file cannot encode the text El archivo del script no puede codificar el texto +@msg Script file could not be written No se pudo escribir el archivo del script +@msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda +@msg Script file is not open for writing El archivo del script no está abierto para escritura +@msg Script file name is already in use El nombre del archivo del script ya está en uso +@msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta +@msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo +@msg Script file permission could not be saved No se pudo guardar el permiso de archivos del script +@msg Script folder is not empty La carpeta del script no está vacía +@msg Script files cannot make aliases Los archivos del script no pueden crear alias +@msg Script file hidden setting cannot be changed No se puede cambiar el ajuste de oculto del archivo del script +@msg {name}: a file 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 de archivo no se puede abrir 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 the script wrote more file data than one run may write (32 MiB) el script escribió más datos de archivo de los que puede escribir una ejecución (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop +@msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue +@msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez +@msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron @msg Corners edits the corners of a path Esquinas edita las esquinas de un trazado @msg Couldn't copy to the system clipboard: {e} No se pudo copiar al portapapeles del sistema: {e} @msg Couldn't open {name}: {e} No se pudo abrir {name}: {e} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..029229411c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4435,6 +4435,13 @@ imageTrace Outline Ääriviiva Show External Script Warning Näytä ulkoisten komentosarjojen varoitus A Script Is Running Komentosarja on käynnissä Script Alert Komentosarjan ilmoitus + Script File Access Komentosarjan tiedostojen käyttö + The script asks to read a file you choose. Komentosarja pyytää lupaa lukea valitsemasi tiedoston. + The script asks to read and write a file you choose. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi tiedoston. + The script asks to read and write a folder you choose, with everything in it. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi kansion ja kaiken sen sisällön. + Allow Once Salli kerran + Always Allow This Script Salli tämä komentosarja aina + Deny Estä A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. @@ -4463,8 +4470,6 @@ imageTrace Outline Ääriviiva @msg Script file could not be read Komentosarjatiedostoa ei voitu lukea @msg Script folder has more than 2,048 entries Komentosarjakansiossa on yli 2 048 kohdetta @msg Script file open mode must be r, w, e or a Komentosarjatiedoston avaustilan on oltava r, w, e tai a -@msg Script file writing is not available Komentosarjatiedostojen kirjoittaminen ei ole käytettävissä -@msg Script file dialogs are not available Komentosarjojen tiedostovalintaikkunat eivät ole käytettävissä @msg Script files cannot be opened in another application Komentosarjatiedostoja ei voi avata toisessa sovelluksessa @msg Script file access is unavailable on the web Komentosarjatiedostojen käyttö ei ole mahdollista verkossa @msg Script has 256 files open Komentosarjalla on 256 tiedostoa auki @@ -4535,6 +4540,27 @@ imageTrace Outline Ääriviiva @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin +@msg Script file access denied: {path} Komentosarjan tiedostojen käyttö estettiin: {path} +@msg Script file access to the app's own folders is not allowed Komentosarjat eivät saa käyttää sovelluksen omia kansioita +@msg Script file cannot encode the text Komentosarjan tiedosto ei voi koodata tekstiä +@msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa +@msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö +@msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten +@msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä +@msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota +@msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle +@msg Script file permission could not be saved Komentosarjan tiedostolupaa ei voitu tallentaa +@msg Script folder is not empty Komentosarjan kansio ei ole tyhjä +@msg Script files cannot make aliases Komentosarjan tiedostot eivät voi luoda aliaksia +@msg Script file hidden setting cannot be changed Komentosarjan tiedoston piilotusasetusta ei voi muuttaa +@msg {name}: a file 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}: tiedostovalintaikkunaa ei voi avata sisäänrakennetun funktion, getterin, muunnoksen tai $.evalFile-funktion suorittaman tiedoston takaisinkutsussa; kutsu sitä komentosarjan omasta koodista +@msg the script wrote more file data than one run may write (32 MiB) komentosarja kirjoitti enemmän tiedostodataa kuin yksi suoritus saa kirjoittaa (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop +@msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä +@msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran +@msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön +@msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois @msg Corners edits the corners of a path Kulmat-toiminto muokkaa polun kulmia @msg Couldn't copy to the system clipboard: {e} Järjestelmän leikepöydälle ei voitu kopioida: {e} @msg Couldn't open {name}: {e} Tiedostoa {name} ei voitu avata: {e} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..d942ad6638 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4200,6 +4200,13 @@ axis Both Les deux Show External Script Warning Afficher l’avertissement des scripts externes A Script Is Running Un script est en cours d’exécution Script Alert Alerte de script + Script File Access Accès du script aux fichiers + The script asks to read a file you choose. Le script demande à lire un fichier que vous choisissez. + The script asks to read and write a file you choose. Le script demande à lire et écrire un fichier que vous choisissez. + The script asks to read and write a folder you choose, with everything in it. Le script demande à lire et écrire un dossier que vous choisissez, avec tout son contenu. + Allow Once Autoriser une fois + Always Allow This Script Toujours autoriser ce script + Deny Refuser A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. @@ -4228,8 +4235,6 @@ axis Both Les deux @msg Script file could not be read Le fichier de script n’a pas pu être lu @msg Script folder has more than 2,048 entries Le dossier de script contient plus de 2 048 entrées @msg Script file open mode must be r, w, e or a Le mode d’ouverture du fichier de script doit être r, w, e ou a -@msg Script file writing is not available L’écriture de fichiers de script n’est pas disponible -@msg Script file dialogs are not available Les boîtes de dialogue de fichiers de script ne sont pas disponibles @msg Script files cannot be opened in another application Les fichiers de script ne peuvent pas être ouverts dans une autre application @msg Script file access is unavailable on the web L’accès aux fichiers de script n’est pas disponible sur le web @msg Script has 256 files open Le script a 256 fichiers ouverts @@ -4300,6 +4305,27 @@ axis Both Les deux @msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name} @msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié +@msg Script file access denied: {path} Accès du script aux fichiers refusé : {path} +@msg Script file access to the app's own folders is not allowed L’accès du script aux dossiers propres à l’application n’est pas autorisé +@msg Script file cannot encode the text Le fichier du script ne peut pas encoder le texte +@msg Script file could not be written Le fichier du script n’a pas pu être écrit +@msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre +@msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture +@msg Script file name is already in use Le nom du fichier du script est déjà utilisé +@msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier +@msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier +@msg Script file permission could not be saved L’autorisation d’accès aux fichiers du script n’a pas pu être enregistrée +@msg Script folder is not empty Le dossier du script n’est pas vide +@msg Script files cannot make aliases Les fichiers du script ne peuvent pas créer d’alias +@msg Script file hidden setting cannot be changed Le réglage masqué du fichier du script ne peut pas être modifié +@msg {name}: a file 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 de fichiers ne peut pas s’ouvrir dans un rappel d’une fonction intégrée, d’un accesseur, d’une conversion ou d’un fichier exécuté par $.evalFile ; appelez-la depuis le propre code du script +@msg the script wrote more file data than one run may write (32 MiB) le script a écrit plus de données de fichiers qu’une exécution ne peut en écrire (32 Mio) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop +@msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez +@msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois +@msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté @msg Corners edits the corners of a path Angles modifie les angles d’un tracé @msg Couldn't copy to the system clipboard: {e} Impossible de copier dans le presse-papiers du système : {e} @msg Couldn't open {name}: {e} Impossible d’ouvrir {name} : {e} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..43be9c9051 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6494,6 +6494,13 @@ antiAlias Sharp शार्प Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ A Script Is Running एक स्क्रिप्ट चल रही है Script Alert स्क्रिप्ट सूचना + Script File Access स्क्रिप्ट की फ़ाइल पहुँच + The script asks to read a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने की अनुमति माँगती है। + The script asks to read and write a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने और लिखने की अनुमति माँगती है। + The script asks to read and write a folder you choose, with everything in it. स्क्रिप्ट आपका चुना हुआ फ़ोल्डर और उसकी सारी सामग्री पढ़ने और लिखने की अनुमति माँगती है। + Allow Once एक बार अनुमति दें + Always Allow This Script इस स्क्रिप्ट को हमेशा अनुमति दें + Deny अस्वीकार करें A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। @@ -6522,8 +6529,6 @@ antiAlias Sharp शार्प @msg Script file could not be read स्क्रिप्ट फ़ाइल पढ़ी नहीं जा सकी @msg Script folder has more than 2,048 entries स्क्रिप्ट फ़ोल्डर में 2,048 से अधिक प्रविष्टियाँ हैं @msg Script file open mode must be r, w, e or a स्क्रिप्ट फ़ाइल खोलने का मोड r, w, e या a होना चाहिए -@msg Script file writing is not available स्क्रिप्ट फ़ाइल लिखना उपलब्ध नहीं है -@msg Script file dialogs are not available स्क्रिप्ट फ़ाइल संवाद उपलब्ध नहीं हैं @msg Script files cannot be opened in another application स्क्रिप्ट फ़ाइलें किसी अन्य ऐप्लिकेशन में नहीं खोली जा सकतीं @msg Script file access is unavailable on the web वेब पर स्क्रिप्ट फ़ाइल पहुँच उपलब्ध नहीं है @msg Script has 256 files open स्क्रिप्ट ने 256 फ़ाइलें खोल रखी हैं @@ -6594,6 +6599,27 @@ antiAlias Sharp शार्प @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट +@msg Script file access denied: {path} स्क्रिप्ट की फ़ाइल पहुँच अस्वीकार की गई: {path} +@msg Script file access to the app's own folders is not allowed स्क्रिप्ट को ऐप के अपने फ़ोल्डरों तक पहुँचने की अनुमति नहीं है +@msg Script file cannot encode the text स्क्रिप्ट फ़ाइल टेक्स्ट को एन्कोड नहीं कर सकती +@msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी +@msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है +@msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है +@msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है +@msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए +@msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है +@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सहेजी नहीं जा सकी +@msg Script folder is not empty स्क्रिप्ट फ़ोल्डर खाली नहीं है +@msg Script files cannot make aliases स्क्रिप्ट फ़ाइलें उपनाम नहीं बना सकतीं +@msg Script file hidden setting cannot be changed स्क्रिप्ट फ़ाइल की छिपी सेटिंग बदली नहीं जा सकती +@msg {name}: a file 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 द्वारा चलाई गई फ़ाइल के callback के भीतर नहीं खुल सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें +@msg the script wrote more file data than one run may write (32 MiB) स्क्रिप्ट ने एक रन में लिखे जा सकने वाले फ़ाइल डेटा से अधिक लिखा (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop +@msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें +@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सहेजी नहीं जा सकीं: {e} +@msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है +@msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है +@msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं @msg copy needs path: the file to copy into the document's folder copy: प्रतिलिपि की जरूरत है पाथ: फ़ाइल को डॉक्यूमेंट के फ़ोल्डर में कॉपी करने के लिए @msg copy takes images only: relink placed documents where their files are copy: प्रतिलिपि केवल इमेज को लेती है: डॉक्यूमेंट्स को फिर से लिंक करें जहां उनकी फ़ाइलें हैं @msg copying a file isn't available on the web एक फ़ाइल की प्रतिलिपि वेब पर उपलब्ध नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..b3c0827878 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5015,6 +5015,13 @@ imageTrace Outline Körvonal Show External Script Warning Figyelmeztetés külső parancsfájlok előtt A Script Is Running Egy parancsfájl fut Script Alert Parancsfájl-értesítés + Script File Access Parancsfájl fájlhozzáférése + The script asks to read a file you choose. A parancsfájl egy Ön által választott fájl olvasását kéri. + The script asks to read and write a file you choose. A parancsfájl egy Ön által választott fájl olvasását és írását kéri. + The script asks to read and write a folder you choose, with everything in it. A parancsfájl egy Ön által választott mappa és teljes tartalma olvasását és írását kéri. + Allow Once Engedélyezés egyszer + Always Allow This Script A parancsfájl engedélyezése mindig + Deny Elutasítás A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. @@ -5043,8 +5050,6 @@ imageTrace Outline Körvonal @msg Script file could not be read A parancsfájlt nem sikerült beolvasni @msg Script folder has more than 2,048 entries A parancsfájlmappában 2048-nál több bejegyzés van @msg Script file open mode must be r, w, e or a A parancsfájl megnyitási módja r, w, e vagy a lehet -@msg Script file writing is not available A parancsfájlok írása nem érhető el -@msg Script file dialogs are not available A parancsfájlok fájlpárbeszédpanelei nem érhetők el @msg Script files cannot be opened in another application A parancsfájlok nem nyithatók meg másik alkalmazásban @msg Script file access is unavailable on the web A parancsfájlok elérése a weben nem érhető el @msg Script has 256 files open A parancsfájlnak 256 megnyitott fájlja van @@ -5115,6 +5120,27 @@ imageTrace Outline Körvonal @msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva +@msg Script file access denied: {path} A parancsfájl fájlhozzáférése megtagadva: {path} +@msg Script file access to the app's own folders is not allowed A parancsfájlok nem férhetnek hozzá az alkalmazás saját mappáihoz +@msg Script file cannot encode the text A parancsfájl fájlja nem tudja kódolni a szöveget +@msg Script file could not be written A parancsfájl fájlját nem sikerült írni +@msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia +@msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva +@msg Script file name is already in use A parancsfájl fájljának neve már használatban van +@msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen +@msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg +@msg Script file permission could not be saved A parancsfájl fájlengedélyét nem sikerült menteni +@msg Script folder is not empty A parancsfájl mappája nem üres +@msg Script files cannot make aliases A parancsfájl fájljai nem hozhatnak létre álneveket +@msg Script file hidden setting cannot be changed A parancsfájl fájljának rejtett beállítása nem módosítható +@msg {name}: a file 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}: fájlpárbeszédpanel nem nyílhat meg beépített függvény, getter, átalakítás vagy a $.evalFile által futtatott fájl visszahívásán belül; hívja meg a parancsfájl saját kódjából +@msg the script wrote more file data than one run may write (32 MiB) a parancsfájl több fájladatot írt, mint amennyit egy futás írhat (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop +@msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el +@msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető +@msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti +@msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak @msg Corners edits the corners of a path a Sarkok parancs egy útvonal sarkait szerkeszti @msg could not decode image: {0} a kép nem dekódolható: {0} @msg Couldn't copy to the system clipboard: {e} Nem sikerült a rendszer vágólapjára másolni: {e} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..b9b0d3e474 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4213,6 +4213,13 @@ imageTrace Outline Kontur Show External Script Warning Tampilkan Peringatan Skrip Eksternal A Script Is Running Skrip Sedang Berjalan Script Alert Peringatan Skrip + Script File Access Akses Berkas Skrip + The script asks to read a file you choose. Skrip meminta izin untuk membaca berkas yang Anda pilih. + The script asks to read and write a file you choose. Skrip meminta izin untuk membaca dan menulis berkas yang Anda pilih. + The script asks to read and write a folder you choose, with everything in it. Skrip meminta izin untuk membaca dan menulis folder yang Anda pilih, beserta seluruh isinya. + Allow Once Izinkan Sekali + Always Allow This Script Selalu Izinkan Skrip Ini + Deny Tolak A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..0958a77ece 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4262,6 +4262,13 @@ axis Both Entrambi Show External Script Warning Mostra avviso per gli script esterni A Script Is Running È in esecuzione uno script Script Alert Avviso dello script + Script File Access Accesso dello script ai file + The script asks to read a file you choose. Lo script chiede di leggere un file che scegli. + The script asks to read and write a file you choose. Lo script chiede di leggere e scrivere un file che scegli. + The script asks to read and write a folder you choose, with everything in it. Lo script chiede di leggere e scrivere una cartella che scegli, con tutto il suo contenuto. + Allow Once Consenti una volta + Always Allow This Script Consenti sempre questo script + Deny Nega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. @@ -4290,8 +4297,6 @@ axis Both Entrambi @msg Script file could not be read Impossibile leggere il file di script @msg Script folder has more than 2,048 entries La cartella di script contiene più di 2.048 voci @msg Script file open mode must be r, w, e or a La modalità di apertura del file di script deve essere r, w, e oppure a -@msg Script file writing is not available La scrittura dei file di script non è disponibile -@msg Script file dialogs are not available Le finestre di dialogo dei file di script non sono disponibili @msg Script files cannot be opened in another application I file di script non possono essere aperti in un'altra applicazione @msg Script file access is unavailable on the web L'accesso ai file di script non è disponibile sul web @msg Script has 256 files open Lo script ha 256 file aperti @@ -4362,6 +4367,27 @@ axis Both Entrambi @msg there is no script engine named {name} non esiste un motore di script chiamato {name} @msg Running a script Esecuzione di uno script @msg Copied the script report Rapporto dello script copiato +@msg Script file access denied: {path} Accesso dello script ai file negato: {path} +@msg Script file access to the app's own folders is not allowed L'accesso dello script alle cartelle dell'app non è consentito +@msg Script file cannot encode the text Il file dello script non può codificare il testo +@msg Script file could not be written Impossibile scrivere il file dello script +@msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda +@msg Script file is not open for writing Il file dello script non è aperto in scrittura +@msg Script file name is already in use Il nome del file dello script è già in uso +@msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella +@msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file +@msg Script file permission could not be saved Impossibile salvare il permesso sui file dello script +@msg Script folder is not empty La cartella dello script non è vuota +@msg Script files cannot make aliases I file dello script non possono creare alias +@msg Script file hidden setting cannot be changed L'impostazione nascosto del file dello script non può essere modificata +@msg {name}: a file 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 dei file non può aprirsi in un callback di una funzione integrata, di un getter, di una conversione o di un file eseguito da $.evalFile; chiamala dal codice dello script stesso +@msg the script wrote more file data than one run may write (32 MiB) lo script ha scritto più dati di file di quanti ne possa scrivere un'esecuzione (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop +@msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega +@msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta +@msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script +@msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi @msg Corners edits the corners of a path Angoli modifica gli angoli di un tracciato @msg Couldn't copy to the system clipboard: {e} Impossibile copiare negli appunti di sistema: {e} @msg Couldn't open {name}: {e} Impossibile aprire {name}: {e} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..c42b5453fb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5016,6 +5016,13 @@ swatch Bright Violet ビビッドバイオレット Show External Script Warning 外部スクリプトの警告を表示 A Script Is Running スクリプトの実行中 Script Alert スクリプトの通知 + Script File Access スクリプトのファイルアクセス + The script asks to read a file you choose. スクリプトが、選択したファイルの読み取りを求めています。 + The script asks to read and write a file you choose. スクリプトが、選択したファイルの読み書きを求めています。 + The script asks to read and write a folder you choose, with everything in it. スクリプトが、選択したフォルダーとその中身すべての読み書きを求めています。 + Allow Once 今回のみ許可 + Always Allow This Script このスクリプトを常に許可 + Deny 拒否 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 @@ -5044,8 +5051,6 @@ swatch Bright Violet ビビッドバイオレット @msg Script file could not be read スクリプトファイルを読み込めませんでした @msg Script folder has more than 2,048 entries スクリプトフォルダーの項目が 2,048 を超えています @msg Script file open mode must be r, w, e or a スクリプトファイルを開くモードは r、w、e、a のいずれかにしてください -@msg Script file writing is not available スクリプトファイルの書き込みは利用できません -@msg Script file dialogs are not available スクリプトファイルのダイアログは利用できません @msg Script files cannot be opened in another application スクリプトファイルを別のアプリケーションで開くことはできません @msg Script file access is unavailable on the web Web ではスクリプトファイルにアクセスできません @msg Script has 256 files open スクリプトが 256 個のファイルを開いています @@ -5116,6 +5121,27 @@ swatch Bright Violet ビビッドバイオレット @msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました +@msg Script file access denied: {path} スクリプトのファイルアクセスが拒否されました: {path} +@msg Script file access to the app's own folders is not allowed スクリプトからアプリ自身のフォルダーへのアクセスは許可されていません +@msg Script file cannot encode the text スクリプトのファイルでテキストをエンコードできません +@msg Script file could not be written スクリプトのファイルを書き込めませんでした +@msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です +@msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません +@msg Script file name is already in use スクリプトのファイル名はすでに使用されています +@msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください +@msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです +@msg Script file permission could not be saved スクリプトのファイルの許可を保存できませんでした +@msg Script folder is not empty スクリプトのフォルダーが空ではありません +@msg Script files cannot make aliases スクリプトのファイルではエイリアスを作成できません +@msg Script file hidden setting cannot be changed スクリプトのファイルの非表示設定は変更できません +@msg {name}: a file 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 the script wrote more file data than one run may write (32 MiB) スクリプトが 1 回の実行で書き込める量を超えるファイルデータを書き込みました (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください +@msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください +@msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます +@msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです +@msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @msg unknown highlight `{h}` `{h}` は不明なハイライトの指定です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..f9a20f812c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5415,6 +5415,13 @@ imageTrace Outline კონტური Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება A Script Is Running სკრიპტი მუშაობს Script Alert სკრიპტის შეტყობინება + Script File Access სკრიპტის წვდომა ფაილებზე + The script asks to read a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვას. + The script asks to read and write a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვასა და ჩაწერას. + The script asks to read and write a folder you choose, with everything in it. სკრიპტი ითხოვს თქვენ მიერ არჩეული საქაღალდისა და მთელი მისი შიგთავსის წაკითხვასა და ჩაწერას. + Allow Once ერთხელ დაშვება + Always Allow This Script ამ სკრიპტის ყოველთვის დაშვება + Deny უარყოფა A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. @@ -5443,8 +5450,6 @@ imageTrace Outline კონტური @msg Script file could not be read სკრიპტის ფაილის წაკითხვა ვერ მოხერხდა @msg Script folder has more than 2,048 entries სკრიპტის საქაღალდეში 2048-ზე მეტი ჩანაწერია @msg Script file open mode must be r, w, e or a სკრიპტის ფაილის გახსნის რეჟიმი უნდა იყოს r, w, e ან a -@msg Script file writing is not available სკრიპტის ფაილების ჩაწერა მიუწვდომელია -@msg Script file dialogs are not available სკრიპტის ფაილის დიალოგები მიუწვდომელია @msg Script files cannot be opened in another application სკრიპტის ფაილების სხვა აპლიკაციაში გახსნა შეუძლებელია @msg Script file access is unavailable on the web ვებში სკრიპტის ფაილებზე წვდომა მიუწვდომელია @msg Script has 256 files open სკრიპტს 256 ფაილი აქვს გახსნილი @@ -5515,6 +5520,27 @@ imageTrace Outline კონტური @msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში +@msg Script file access denied: {path} სკრიპტის წვდომა ფაილებზე უარყოფილია: {path} +@msg Script file access to the app's own folders is not allowed სკრიპტს არ აქვს აპის საკუთარ საქაღალდეებზე წვდომის უფლება +@msg Script file cannot encode the text სკრიპტის ფაილი ვერ აკოდირებს ტექსტს +@msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა +@msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს +@msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის +@msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება +@msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე +@msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის +@msg Script file permission could not be saved სკრიპტის ფაილების ნებართვის შენახვა ვერ მოხერხდა +@msg Script folder is not empty სკრიპტის საქაღალდე ცარიელი არ არის +@msg Script files cannot make aliases სკრიპტის ფაილებს არ შეუძლიათ ფსევდონიმების შექმნა +@msg Script file hidden setting cannot be changed სკრიპტის ფაილის დამალვის პარამეტრის შეცვლა შეუძლებელია +@msg {name}: a file 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-ის მიერ გაშვებული ფაილის callback-ში; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან +@msg the script wrote more file data than one run may write (32 MiB) სკრიპტმა ჩაწერა იმაზე მეტი ფაილის მონაცემი, ვიდრე ერთ გაშვებას შეუძლია ჩაწეროს (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop +@msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით +@msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას +@msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს +@msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია) @msg {path}: not a file {path}: ფაილი არ არის Load EPS into Clipboard EPS-ის ბუფერში ჩატვირთვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..3d6d38ff44 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4943,6 +4943,13 @@ theme Appearance 외관 Show External Script Warning 외부 스크립트 경고 표시 A Script Is Running 스크립트 실행 중 Script Alert 스크립트 알림 + Script File Access 스크립트 파일 접근 + The script asks to read a file you choose. 스크립트가 선택한 파일을 읽도록 요청합니다. + The script asks to read and write a file you choose. 스크립트가 선택한 파일을 읽고 쓰도록 요청합니다. + The script asks to read and write a folder you choose, with everything in it. 스크립트가 선택한 폴더와 그 안의 모든 항목을 읽고 쓰도록 요청합니다. + Allow Once 한 번 허용 + Always Allow This Script 이 스크립트 항상 허용 + Deny 거부 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. @@ -4971,8 +4978,6 @@ theme Appearance 외관 @msg Script file could not be read 스크립트 파일을 읽을 수 없습니다 @msg Script folder has more than 2,048 entries 스크립트 폴더의 항목이 2,048개를 초과합니다 @msg Script file open mode must be r, w, e or a 스크립트 파일 열기 모드는 r, w, e 또는 a여야 합니다 -@msg Script file writing is not available 스크립트 파일 쓰기를 사용할 수 없습니다 -@msg Script file dialogs are not available 스크립트 파일 대화 상자를 사용할 수 없습니다 @msg Script files cannot be opened in another application 스크립트 파일을 다른 응용 프로그램에서 열 수 없습니다 @msg Script file access is unavailable on the web 웹에서는 스크립트 파일에 접근할 수 없습니다 @msg Script has 256 files open 스크립트가 파일 256개를 열고 있습니다 @@ -5043,6 +5048,27 @@ theme Appearance 외관 @msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 +@msg Script file access denied: {path} 스크립트 파일 접근이 거부되었습니다: {path} +@msg Script file access to the app's own folders is not allowed 스크립트는 앱 자체 폴더에 접근할 수 없습니다 +@msg Script file cannot encode the text 스크립트 파일이 텍스트를 인코딩할 수 없습니다 +@msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 +@msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 +@msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 +@msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 +@msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 +@msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 +@msg Script file permission could not be saved 스크립트 파일 권한을 저장할 수 없습니다 +@msg Script folder is not empty 스크립트 폴더가 비어 있지 않습니다 +@msg Script files cannot make aliases 스크립트 파일은 별칭을 만들 수 없습니다 +@msg Script file hidden setting cannot be changed 스크립트 파일의 숨김 설정을 변경할 수 없습니다 +@msg {name}: a file 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 the script wrote more file data than one run may write (32 MiB) 스크립트가 한 번의 실행에서 쓸 수 있는 것보다 많은 파일 데이터를 썼습니다(32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 +@msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 +@msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 +@msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 +@msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @msg unknown highlight `{h}` 알 수 없는 강조 `{h}` diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..6dea6dca40 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4227,6 +4227,13 @@ imageTrace Outline Contour Show External Script Warning Waarschuwing voor externe scripts tonen A Script Is Running Er wordt een script uitgevoerd Script Alert Scriptmelding + Script File Access Bestandstoegang van script + The script asks to read a file you choose. Het script vraagt een bestand te lezen dat u kiest. + The script asks to read and write a file you choose. Het script vraagt een bestand te lezen en te schrijven dat u kiest. + The script asks to read and write a folder you choose, with everything in it. Het script vraagt een map die u kiest te lezen en te schrijven, met alles wat erin staat. + Allow Once Eenmaal toestaan + Always Allow This Script Dit script altijd toestaan + Deny Weigeren A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..d9fca7852c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4344,6 +4344,13 @@ imageTrace Outline Kontur Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych A Script Is Running Skrypt jest uruchomiony Script Alert Komunikat skryptu + Script File Access Dostęp skryptu do plików + The script asks to read a file you choose. Skrypt prosi o odczyt wybranego przez Ciebie pliku. + The script asks to read and write a file you choose. Skrypt prosi o odczyt i zapis wybranego przez Ciebie pliku. + The script asks to read and write a folder you choose, with everything in it. Skrypt prosi o odczyt i zapis wybranego przez Ciebie folderu wraz z całą jego zawartością. + Allow Once Zezwól raz + Always Allow This Script Zawsze zezwalaj temu skryptowi + Deny Odmów A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. @@ -4372,8 +4379,6 @@ imageTrace Outline Kontur @msg Script file could not be read Nie udało się odczytać pliku skryptu @msg Script folder has more than 2,048 entries Folder skryptu ma więcej niż 2048 pozycji @msg Script file open mode must be r, w, e or a Tryb otwarcia pliku skryptu musi być r, w, e lub a -@msg Script file writing is not available Zapisywanie plików skryptu jest niedostępne -@msg Script file dialogs are not available Okna dialogowe plików skryptu są niedostępne @msg Script files cannot be opened in another application Plików skryptu nie można otworzyć w innej aplikacji @msg Script file access is unavailable on the web Dostęp do plików skryptu jest niedostępny w przeglądarce @msg Script has 256 files open Skrypt ma otwartych 256 plików @@ -4444,6 +4449,27 @@ imageTrace Outline Kontur @msg there is no script engine named {name} nie ma silnika skryptów o nazwie {name} @msg Running a script Uruchamianie skryptu @msg Copied the script report Skopiowano raport skryptu +@msg Script file access denied: {path} Odmówiono skryptowi dostępu do plików: {path} +@msg Script file access to the app's own folders is not allowed Skrypt nie ma dostępu do własnych folderów aplikacji +@msg Script file cannot encode the text Plik skryptu nie może zakodować tekstu +@msg Script file could not be written Nie można zapisać pliku skryptu +@msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie +@msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu +@msg Script file name is already in use Nazwa pliku skryptu jest już używana +@msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu +@msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku +@msg Script file permission could not be saved Nie można zapisać uprawnienia skryptu do plików +@msg Script folder is not empty Folder skryptu nie jest pusty +@msg Script files cannot make aliases Pliki skryptu nie mogą tworzyć aliasów +@msg Script file hidden setting cannot be changed Nie można zmienić ustawienia ukrycia pliku skryptu +@msg {name}: a file 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}: okna dialogowego plików nie można otworzyć w wywołaniu zwrotnym funkcji wbudowanej, gettera, konwersji ani pliku uruchamianego przez $.evalFile; wywołaj je z własnego kodu skryptu +@msg the script wrote more file data than one run may write (32 MiB) skrypt zapisał więcej danych plików, niż może zapisać jedno uruchomienie (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop +@msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów +@msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz +@msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze +@msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte @msg Corners edits the corners of a path Narożniki edytuje narożniki ścieżki @msg Couldn't copy to the system clipboard: {e} Nie udało się skopiować do schowka systemowego: {e} @msg Couldn't open {name}: {e} Nie udało się otworzyć {name}: {e} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..030c073639 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5225,6 +5225,13 @@ axis Both Ambos Show External Script Warning Mostrar aviso de scripts externos A Script Is Running Um script está em execução Script Alert Alerta do script + Script File Access Acesso do script a arquivos + The script asks to read a file you choose. O script pede para ler um arquivo que você escolher. + The script asks to read and write a file you choose. O script pede para ler e gravar um arquivo que você escolher. + The script asks to read and write a folder you choose, with everything in it. O script pede para ler e gravar uma pasta que você escolher, com todo o seu conteúdo. + Allow Once Permitir uma vez + Always Allow This Script Sempre permitir este script + Deny Negar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. @@ -5253,8 +5260,6 @@ axis Both Ambos @msg Script file could not be read Não foi possível ler o arquivo de script @msg Script folder has more than 2,048 entries A pasta de script tem mais de 2.048 entradas @msg Script file open mode must be r, w, e or a O modo de abertura do arquivo de script deve ser r, w, e ou a -@msg Script file writing is not available A gravação de arquivos de script não está disponível -@msg Script file dialogs are not available As caixas de diálogo de arquivos de script não estão disponíveis @msg Script files cannot be opened in another application Arquivos de script não podem ser abertos em outro aplicativo @msg Script file access is unavailable on the web O acesso a arquivos de script não está disponível na web @msg Script has 256 files open O script tem 256 arquivos abertos @@ -5325,6 +5330,27 @@ axis Both Ambos @msg there is no script engine named {name} não há nenhum mecanismo de script chamado {name} @msg Running a script Executando um script @msg Copied the script report Relatório do script copiado +@msg Script file access denied: {path} Acesso do script a arquivos negado: {path} +@msg Script file access to the app's own folders is not allowed O script não pode acessar as pastas do próprio aplicativo +@msg Script file cannot encode the text O arquivo do script não consegue codificar o texto +@msg Script file could not be written Não foi possível gravar o arquivo do script +@msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las +@msg Script file is not open for writing O arquivo do script não está aberto para gravação +@msg Script file name is already in use O nome do arquivo do script já está em uso +@msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta +@msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo +@msg Script file permission could not be saved Não foi possível salvar a permissão de arquivos do script +@msg Script folder is not empty A pasta do script não está vazia +@msg Script files cannot make aliases Os arquivos do script não podem criar aliases +@msg Script file hidden setting cannot be changed A configuração de oculto do arquivo do script não pode ser alterada +@msg {name}: a file 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 de arquivo não pode abrir dentro de um callback de uma função integrada, de um getter, de uma conversão ou de um arquivo que $.evalFile executa; chame-a a partir do próprio código do script +@msg the script wrote more file data than one run may write (32 MiB) o script gravou mais dados de arquivo do que uma execução pode gravar (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop +@msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue +@msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez +@msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script +@msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora @msg This shortcut file is in a form VectorCraft can't read. Este arquivo de atalhos está em um formato que o VectorCraft não consegue ler. @msg axis must be "vertical", "horizontal" or an angle in degrees, not `{v}` axis deve ser "vertical", "horizontal" ou um ângulo em graus, não `{v}` @msg give corners of the path: anchors where its sides meet at an angle informe os cantos do caminho: pontos de ancoragem onde os lados se encontram em ângulo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..c18c366da1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4248,6 +4248,13 @@ axis Both Оба Show External Script Warning Показывать предупреждение о внешних скриптах A Script Is Running Выполняется скрипт Script Alert Сообщение скрипта + Script File Access Доступ скрипта к файлам + The script asks to read a file you choose. Скрипт запрашивает чтение выбранного вами файла. + The script asks to read and write a file you choose. Скрипт запрашивает чтение и запись выбранного вами файла. + The script asks to read and write a folder you choose, with everything in it. Скрипт запрашивает чтение и запись выбранной вами папки со всем её содержимым. + Allow Once Разрешить один раз + Always Allow This Script Всегда разрешать этот скрипт + Deny Запретить A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. @@ -4276,8 +4283,6 @@ axis Both Оба @msg Script file could not be read Не удалось прочитать файл скрипта @msg Script folder has more than 2,048 entries В папке скрипта больше 2048 элементов @msg Script file open mode must be r, w, e or a Режим открытия файла скрипта должен быть r, w, e или a -@msg Script file writing is not available Запись файлов скрипта недоступна -@msg Script file dialogs are not available Диалоговые окна файлов скрипта недоступны @msg Script files cannot be opened in another application Файлы скрипта нельзя открыть в другом приложении @msg Script file access is unavailable on the web Доступ к файлам скрипта в веб-версии недоступен @msg Script has 256 files open У скрипта открыто 256 файлов @@ -4348,6 +4353,27 @@ axis Both Оба @msg there is no script engine named {name} движка скриптов с именем {name} нет @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован +@msg Script file access denied: {path} Доступ скрипта к файлам запрещён: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не разрешён доступ к собственным папкам приложения +@msg Script file cannot encode the text Файл скрипта не может закодировать текст +@msg Script file could not be written Не удалось записать файл скрипта +@msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек +@msg Script file is not open for writing Файл скрипта не открыт для записи +@msg Script file name is already in use Имя файла скрипта уже используется +@msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки +@msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла +@msg Script file permission could not be saved Не удалось сохранить разрешение скрипта на файлы +@msg Script folder is not empty Папка скрипта не пуста +@msg Script files cannot make aliases Файлы скрипта не могут создавать псевдонимы +@msg Script file hidden setting cannot be changed Нельзя изменить параметр скрытости файла скрипта +@msg {name}: a file 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 the script wrote more file data than one run may write (32 MiB) скрипт записал больше данных файлов, чем может записать один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop +@msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите +@msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз +@msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @msg Couldn't open {name}: {e} Не удалось открыть {name}: {e} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..0331bdbd36 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4121,6 +4121,13 @@ axis Both Båda Show External Script Warning Visa varning för externa skript A Script Is Running Ett skript körs Script Alert Skriptmeddelande + Script File Access Skriptets filåtkomst + The script asks to read a file you choose. Skriptet ber om att läsa en fil som du väljer. + The script asks to read and write a file you choose. Skriptet ber om att läsa och skriva en fil som du väljer. + The script asks to read and write a folder you choose, with everything in it. Skriptet ber om att läsa och skriva en mapp som du väljer, med allt innehåll. + Allow Once Tillåt en gång + Always Allow This Script Tillåt alltid det här skriptet + Deny Neka A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. @@ -4149,8 +4156,6 @@ axis Both Båda @msg Script file could not be read Skriptfilen kunde inte läsas @msg Script folder has more than 2,048 entries Skriptmappen har fler än 2 048 poster @msg Script file open mode must be r, w, e or a Skriptfilens öppningsläge måste vara r, w, e eller a -@msg Script file writing is not available Skrivning av skriptfiler är inte tillgänglig -@msg Script file dialogs are not available Fildialogrutor för skript är inte tillgängliga @msg Script files cannot be opened in another application Skriptfiler kan inte öppnas i ett annat program @msg Script file access is unavailable on the web Åtkomst till skriptfiler är inte tillgänglig på webben @msg Script has 256 files open Skriptet har 256 filer öppna @@ -4221,6 +4226,27 @@ axis Both Båda @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten +@msg Script file access denied: {path} Skriptets filåtkomst nekades: {path} +@msg Script file access to the app's own folders is not allowed Skript får inte komma åt appens egna mappar +@msg Script file cannot encode the text Skriptets fil kan inte koda texten +@msg Script file could not be written Skriptets fil kunde inte skrivas +@msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem +@msg Script file is not open for writing Skriptets fil är inte öppen för skrivning +@msg Script file name is already in use Namnet på skriptets fil används redan +@msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp +@msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil +@msg Script file permission could not be saved Skriptets filbehörighet kunde inte sparas +@msg Script folder is not empty Skriptets mapp är inte tom +@msg Script files cannot make aliases Skriptets filer kan inte skapa alias +@msg Script file hidden setting cannot be changed Inställningen för dold för skriptets fil kan inte ändras +@msg {name}: a file 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 fildialog 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 the script wrote more file data than one run may write (32 MiB) skriptet skrev mer fildata än en körning får skriva (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop +@msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka +@msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång +@msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst +@msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades @msg Corners edits the corners of a path Hörn redigerar hörnen på en bana @msg Couldn't copy to the system clipboard: {e} Kunde inte kopiera till systemets urklipp: {e} @msg Couldn't open {name}: {e} Kunde inte öppna {name}: {e} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..b1e61e080e 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1739,6 +1739,68 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// The errors a script's `File` and `Folder` objects and file dialogs give, and those of the +/// commands that answer the dialogs and keep their permissions, have a translated row in every +/// complete-message language. Each one in the first list is still a message the source gives; the +/// second list holds the note the file dialog shows when it left out picked files, and texts a +/// script reads only from a File or Folder object's `error`. +#[test] +fn script_file_messages_translate_in_every_complete_message_language() { + const SCANNED: &[&str] = &[ + "Script file access denied", + "Script file access denied: {path}", + "Script file access is unavailable on the web", + "Script file access to the app's own folders is not allowed", + "Script file cannot be decoded", + "Script file cannot encode the text", + "Script file could not be read", + "Script file could not be written", + "Script file dialogs need a person to answer them", + "Script file does not exist", + "Script file exceeds 8 MiB", + "Script file is not a regular file", + "Script file is not open", + "Script file is not open for writing", + "Script file name is already in use", + "Script file name must be a name without a folder", + "Script file path exceeds 32,767 characters", + "Script file permission can be kept only for a script run from a file", + "Script file permission could not be saved", + "Script files cannot be opened in another application", + "Script folder has more than 2,048 entries", + "Script folder mask takes too many steps to match", + "{name}: a file 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", + "the script opened more file data than one run may open (32 MiB)", + "the script wrote more file data than one run may write (32 MiB)", + "`answer` for a script's file dialog must be one of: once, always, deny, stop", + "choose a file or folder first, or deny", + "the script file permissions could not be saved: {e}", + "this script's file access can be allowed only once", + "Only the person at the keyboard can allow a script's file access", + ]; + const ERROR_ONLY: &[&str] = &[ + "A script is given at most 2,048 files: the files picked after them were left out", + "Script file open mode must be r, w, e or a", + "Script has 256 files open", + "Script folder is not empty", + "Script files cannot make aliases", + "Script file hidden setting cannot be changed", + ]; + let messages = message_literals(); + let gone: Vec<&&str> = SCANNED.iter().filter(|m| !messages.contains(**m)).collect(); + assert!(gone.is_empty(), "no longer messages in the source: {gone:?}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + for m in SCANNED.iter().chain(ERROR_ONLY) { + let row = entries.iter().find(|(ctx, src, _)| ctx == "@msg" && src == m); + assert!(row.is_some_and(|(_, src, tr)| tr != src), "{code}: no translated row for {m:?}"); + } + } + let de = Lang::from_code("de").expect("de registered"); + assert_eq!(message(de, "Script file access denied: C:/x/a.txt"), "Dateizugriff des Skripts verweigert: C:/x/a.txt"); +} + #[test] fn package_status_message_templates_parse() { let c = Catalog::parse(concat!( @@ -2532,8 +2594,8 @@ fn script_errors_are_translated() { "Script file could not be read", "Script folder has more than 2,048 entries", "Script file open mode must be r, w, e or a", - "Script file writing is not available", - "Script file dialogs are not available", + "Script file is not open for writing", + "Script file dialogs need a person to answer them", "Script files cannot be opened in another application", "Script file access is unavailable on the web", "Script has 256 files open", diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..f4df32faee 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4001,6 +4001,13 @@ axis Both Her İkisi Show External Script Warning Harici Betik Uyarısını Göster A Script Is Running Bir Betik Çalışıyor Script Alert Betik Uyarısı + Script File Access Betik Dosya Erişimi + The script asks to read a file you choose. Betik, seçtiğiniz bir dosyayı okumak için izin istiyor. + The script asks to read and write a file you choose. Betik, seçtiğiniz bir dosyayı okumak ve yazmak için izin istiyor. + The script asks to read and write a folder you choose, with everything in it. Betik, seçtiğiniz bir klasörü içindeki her şeyle birlikte okumak ve yazmak için izin istiyor. + Allow Once Bir Kez İzin Ver + Always Allow This Script Bu Betiğe Her Zaman İzin Ver + Deny Reddet A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. @@ -4029,8 +4036,6 @@ axis Both Her İkisi @msg Script file could not be read Betik dosyası okunamadı @msg Script folder has more than 2,048 entries Betik klasöründe 2.048'den fazla öğe var @msg Script file open mode must be r, w, e or a Betik dosyası açma modu r, w, e veya a olmalıdır -@msg Script file writing is not available Betik dosyası yazma kullanılamıyor -@msg Script file dialogs are not available Betik dosyası iletişim kutuları kullanılamıyor @msg Script files cannot be opened in another application Betik dosyaları başka bir uygulamada açılamaz @msg Script file access is unavailable on the web Betik dosyası erişimi web'de kullanılamıyor @msg Script has 256 files open Betiğin 256 açık dosyası var @@ -4101,6 +4106,27 @@ axis Both Her İkisi @msg there is no script engine named {name} {name} adlı bir betik motoru yok @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı +@msg Script file access denied: {path} Betiğin dosya erişimi reddedildi: {path} +@msg Script file access to the app's own folders is not allowed Betiklerin uygulamanın kendi klasörlerine erişmesine izin verilmez +@msg Script file cannot encode the text Betiğin dosyası metni kodlayamıyor +@msg Script file could not be written Betiğin dosyası yazılamadı +@msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir +@msg Script file is not open for writing Betiğin dosyası yazmak için açık değil +@msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor +@msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır +@msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir +@msg Script file permission could not be saved Betiğin dosya izni kaydedilemedi +@msg Script folder is not empty Betiğin klasörü boş değil +@msg Script files cannot make aliases Betiğin dosyaları takma ad oluşturamaz +@msg Script file hidden setting cannot be changed Betiğin dosyasının gizli ayarı değiştirilemez +@msg {name}: a file 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}: dosya iletişim kutusu yerleşik bir işlevin, bir getter'ın, bir dönüştürmenin veya $.evalFile'ın çalıştırdığı bir dosyanın geri çağrısı içinde açılamaz; onu betiğin kendi kodundan çağırın +@msg the script wrote more file data than one run may write (32 MiB) betik, bir çalıştırmanın yazabileceğinden fazla dosya verisi yazdı (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop +@msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin +@msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir +@msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir +@msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı @msg Corners edits the corners of a path Köşeler bir yolun köşelerini düzenler @msg Couldn't copy to the system clipboard: {e} Sistem panosuna kopyalanamadı: {e} @msg Couldn't open {name}: {e} {name} açılamadı: {e} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..219a79d05e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4246,6 +4246,13 @@ axis Both Обидві Show External Script Warning Показувати попередження про зовнішні скрипти A Script Is Running Виконується скрипт Script Alert Повідомлення скрипту + Script File Access Доступ скрипту до файлів + The script asks to read a file you choose. Скрипт просить дозволу прочитати вибраний вами файл. + The script asks to read and write a file you choose. Скрипт просить дозволу читати й записувати вибраний вами файл. + The script asks to read and write a folder you choose, with everything in it. Скрипт просить дозволу читати й записувати вибрану вами папку з усім її вмістом. + Allow Once Дозволити один раз + Always Allow This Script Завжди дозволяти цей скрипт + Deny Заборонити A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. @@ -4274,8 +4281,6 @@ axis Both Обидві @msg Script file could not be read Не вдалося прочитати файл скрипта @msg Script folder has more than 2,048 entries Тека скрипта має понад 2048 елементів @msg Script file open mode must be r, w, e or a Режим відкриття файлу скрипта має бути r, w, e або a -@msg Script file writing is not available Запис файлів скрипта недоступний -@msg Script file dialogs are not available Діалогові вікна файлів скрипта недоступні @msg Script files cannot be opened in another application Файли скрипта не можна відкрити в іншому застосунку @msg Script file access is unavailable on the web Доступ до файлів скрипта у вебверсії недоступний @msg Script has 256 files open Скрипт має 256 відкритих файлів @@ -4346,6 +4351,27 @@ axis Both Обидві @msg there is no script engine named {name} рушія скриптів з назвою {name} немає @msg Running a script Виконується скрипт @msg Copied the script report Звіт про сценарій скопійовано +@msg Script file access denied: {path} Доступ скрипту до файлів заборонено: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не дозволено доступ до власних папок застосунку +@msg Script file cannot encode the text Файл скрипту не може закодувати текст +@msg Script file could not be written Не вдалося записати файл скрипту +@msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина +@msg Script file is not open for writing Файл скрипту не відкрито для запису +@msg Script file name is already in use Ім’я файлу скрипту вже використовується +@msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки +@msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу +@msg Script file permission could not be saved Не вдалося зберегти дозвіл скрипту на файли +@msg Script folder is not empty Папка скрипту не порожня +@msg Script files cannot make aliases Файли скрипту не можуть створювати псевдоніми +@msg Script file hidden setting cannot be changed Не можна змінити параметр прихованості файлу скрипту +@msg {name}: a file 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 the script wrote more file data than one run may write (32 MiB) скрипт записав більше даних файлів, ніж може записати один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop +@msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте +@msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз +@msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @msg Couldn't open {name}: {e} Не вдалося відкрити {name}: {e} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..d9e307c7f4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4672,6 +4672,13 @@ theme Appearance Giao diện Show External Script Warning Hiện cảnh báo tập lệnh bên ngoài A Script Is Running Một tập lệnh đang chạy Script Alert Thông báo của tập lệnh + Script File Access Quyền truy cập tệp của tập lệnh + The script asks to read a file you choose. Tập lệnh yêu cầu đọc một tệp bạn chọn. + The script asks to read and write a file you choose. Tập lệnh yêu cầu đọc và ghi một tệp bạn chọn. + The script asks to read and write a folder you choose, with everything in it. Tập lệnh yêu cầu đọc và ghi một thư mục bạn chọn, cùng mọi thứ bên trong. + Allow Once Cho phép một lần + Always Allow This Script Luôn cho phép tập lệnh này + Deny Từ chối A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. @@ -4700,8 +4707,6 @@ theme Appearance Giao diện @msg Script file could not be read Không thể đọc tệp tập lệnh @msg Script folder has more than 2,048 entries Thư mục tập lệnh có hơn 2.048 mục @msg Script file open mode must be r, w, e or a Chế độ mở tệp tập lệnh phải là r, w, e hoặc a -@msg Script file writing is not available Không thể ghi tệp tập lệnh -@msg Script file dialogs are not available Không có hộp thoại tệp cho tập lệnh @msg Script files cannot be opened in another application Không thể mở tệp tập lệnh trong ứng dụng khác @msg Script file access is unavailable on the web Không thể truy cập tệp tập lệnh trên web @msg Script has 256 files open Tập lệnh đang mở 256 tệp @@ -4772,6 +4777,27 @@ theme Appearance Giao diện @msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name} @msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script +@msg Script file access denied: {path} Quyền truy cập tệp của tập lệnh bị từ chối: {path} +@msg Script file access to the app's own folders is not allowed Tập lệnh không được phép truy cập các thư mục riêng của ứng dụng +@msg Script file cannot encode the text Tệp của tập lệnh không thể mã hóa văn bản +@msg Script file could not be written Không thể ghi tệp của tập lệnh +@msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời +@msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi +@msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng +@msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục +@msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp +@msg Script file permission could not be saved Không thể lưu quyền truy cập tệp của tập lệnh +@msg Script folder is not empty Thư mục của tập lệnh không trống +@msg Script files cannot make aliases Tệp của tập lệnh không thể tạo bí danh +@msg Script file hidden setting cannot be changed Không thể thay đổi cài đặt ẩn của tệp tập lệnh +@msg {name}: a file 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}: không thể mở hộp thoại tệp bên trong callback 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ã riêng của tập lệnh +@msg the script wrote more file data than one run may write (32 MiB) tập lệnh đã ghi nhiều dữ liệu tệp hơn mức một lần chạy được phép ghi (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop +@msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối +@msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần +@msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp +@msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua @msg Corners edits the corners of a path Corners chỉnh sửa các góc của đường dẫn @msg could not decode image: {0} không thể giải mã ảnh: {0} @msg Couldn't copy to the system clipboard: {e} Không thể sao chép vào khay nhớ tạm hệ thống: {e} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..4f7d745e25 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4704,6 +4704,13 @@ imageTrace Outline 轮廓 Show External Script Warning 显示外部脚本警告 A Script Is Running 脚本正在运行 Script Alert 脚本提示 + Script File Access 脚本文件访问 + The script asks to read a file you choose. 脚本请求读取您选择的文件。 + The script asks to read and write a file you choose. 脚本请求读写您选择的文件。 + The script asks to read and write a folder you choose, with everything in it. 脚本请求读写您选择的文件夹及其中的所有内容。 + Allow Once 允许一次 + Always Allow This Script 始终允许此脚本 + Deny 拒绝 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 @@ -4732,8 +4739,6 @@ imageTrace Outline 轮廓 @msg Script file could not be read 无法读取脚本文件 @msg Script folder has more than 2,048 entries 脚本文件夹的条目超过 2,048 个 @msg Script file open mode must be r, w, e or a 脚本文件的打开模式必须是 r、w、e 或 a -@msg Script file writing is not available 脚本文件写入不可用 -@msg Script file dialogs are not available 脚本文件对话框不可用 @msg Script files cannot be opened in another application 脚本文件无法在其他应用程序中打开 @msg Script file access is unavailable on the web 网页版无法访问脚本文件 @msg Script has 256 files open 脚本已打开 256 个文件 @@ -4804,6 +4809,27 @@ imageTrace Outline 轮廓 @msg there is no script engine named {name} 没有名为 {name} 的脚本引擎 @msg Running a script 正在运行脚本 @msg Copied the script report 已复制脚本报告 +@msg Script file access denied: {path} 脚本的文件访问被拒绝:{path} +@msg Script file access to the app's own folders is not allowed 不允许脚本访问应用自身的文件夹 +@msg Script file cannot encode the text 脚本的文件无法编码该文本 +@msg Script file could not be written 无法写入脚本的文件 +@msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 +@msg Script file is not open for writing 脚本的文件未以写入方式打开 +@msg Script file name is already in use 脚本的文件名已被使用 +@msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 +@msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 +@msg Script file permission could not be saved 无法保存脚本的文件权限 +@msg Script folder is not empty 脚本的文件夹不为空 +@msg Script files cannot make aliases 脚本的文件无法创建别名 +@msg Script file hidden setting cannot be changed 无法更改脚本文件的隐藏设置 +@msg {name}: a file 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 the script wrote more file data than one run may write (32 MiB) 脚本写入的文件数据超过了一次运行可写入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop +@msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 +@msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 +@msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 +@msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @msg unknown highlight `{h}` 未知的高亮显示 `{h}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..a1d90936f3 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2471,6 +2471,13 @@ file-filter Templates 範本 Show External Script Warning 顯示外部指令碼警告 A Script Is Running 指令碼正在執行 Script Alert 指令碼提示 + Script File Access 指令碼檔案存取 + The script asks to read a file you choose. 指令碼要求讀取您選擇的檔案。 + The script asks to read and write a file you choose. 指令碼要求讀寫您選擇的檔案。 + The script asks to read and write a folder you choose, with everything in it. 指令碼要求讀寫您選擇的資料夾及其中的所有內容。 + Allow Once 允許一次 + Always Allow This Script 一律允許此指令碼 + Deny 拒絕 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 @@ -2499,8 +2506,6 @@ file-filter Templates 範本 @msg Script file could not be read 無法讀取指令碼檔案 @msg Script folder has more than 2,048 entries 指令碼資料夾的項目超過 2,048 個 @msg Script file open mode must be r, w, e or a 指令碼檔案的開啟模式必須是 r、w、e 或 a -@msg Script file writing is not available 無法使用指令碼檔案寫入 -@msg Script file dialogs are not available 無法使用指令碼檔案對話方塊 @msg Script files cannot be opened in another application 指令碼檔案無法在其他應用程式中開啟 @msg Script file access is unavailable on the web 網頁版無法存取指令碼檔案 @msg Script has 256 files open 指令碼已開啟 256 個檔案 @@ -2571,6 +2576,27 @@ file-filter Templates 範本 @msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 +@msg Script file access denied: {path} 指令碼的檔案存取遭拒:{path} +@msg Script file access to the app's own folders is not allowed 不允許指令碼存取應用程式本身的資料夾 +@msg Script file cannot encode the text 指令碼的檔案無法編碼該文字 +@msg Script file could not be written 無法寫入指令碼的檔案 +@msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 +@msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 +@msg Script file name is already in use 指令碼的檔案名稱已在使用中 +@msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 +@msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 +@msg Script file permission could not be saved 無法儲存指令碼的檔案權限 +@msg Script folder is not empty 指令碼的資料夾不是空的 +@msg Script files cannot make aliases 指令碼的檔案無法建立別名 +@msg Script file hidden setting cannot be changed 無法變更指令碼檔案的隱藏設定 +@msg {name}: a file 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 the script wrote more file data than one run may write (32 MiB) 指令碼寫入的檔案資料超過一次執行可寫入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop +@msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 +@msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 +@msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 +@msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @msg unknown highlight `{h}` 未知的反白顯示 `{h}` diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c6ded189..17fcb312ca 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -329,6 +329,11 @@ pub struct VectorcraftApp { /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, + /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which + /// `ui.dialog.set` writes. + pub(crate) script_picked: Vec, + /// Choose… left out files past the most a script is given. + pub(crate) script_picked_left_out: bool, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index ea1b51e049..694fc0e6d7 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -32,10 +32,14 @@ pub enum PickRequest { Open(FilePick), /// An open dialog for files to place. OpenMany, + /// An open dialog for several files of the pick's types. + OpenFiles(FilePick), /// A save dialog. Save(FilePick), /// A folder picker. Folder, + /// A folder picker that starts in the folder given. + FolderAt(String), } /// The paths a dialog shown off the UI thread picked (none: cancelled). A save dialog that reports @@ -192,10 +196,10 @@ impl Picks { /// The kind of dialog open off the UI thread (`ui.inspect`'s `fileDialog`). pub(crate) fn waiting_kind(&self) -> Option<&'static str> { self.waiting.as_ref().map(|w| match w.request { - PickRequest::Open(_) => "open", + PickRequest::Open(_) | PickRequest::OpenFiles(_) => "open", PickRequest::OpenMany => "place", PickRequest::Save(_) => "save", - PickRequest::Folder => "folder", + PickRequest::Folder | PickRequest::FolderAt(_) => "folder", }) } } @@ -350,19 +354,32 @@ pub(crate) fn folder(app: &mut VectorcraftApp) -> Option { ask(app, PickRequest::Folder)?.into_iter().next() } +/// A folder from the folder picker, which starts in `start` when the host can start it there. +pub(crate) fn folder_at(app: &mut VectorcraftApp, start: &str) -> Option { + ask(app, PickRequest::FolderAt(start.to_string()))?.into_iter().next() +} + /// Paths from the open dialog for files to place (none: cancelled). pub(crate) fn open_many(app: &mut VectorcraftApp) -> Vec { ask(app, PickRequest::OpenMany).unwrap_or_default() } +/// Paths from an open dialog for several files of `pick`'s types (none: cancelled, or shown off the +/// UI thread for now). +pub(crate) fn open_files(app: &mut VectorcraftApp, pick: &FilePick) -> Vec { + ask(app, PickRequest::OpenFiles(pick.clone())).unwrap_or_default() +} + /// Whether the host shows `request`'s kind of dialog at all. pub(crate) fn can(app: &VectorcraftApp, request: &PickRequest) -> bool { let s = &app.services; match request { PickRequest::Open(_) => s.pick_open.is_some(), PickRequest::OpenMany => s.pick_open_multi.is_some() || s.pick_open.is_some(), + PickRequest::OpenFiles(_) => s.pick_open_files.is_some() || s.pick_open.is_some(), PickRequest::Save(_) => s.pick_save.is_some(), PickRequest::Folder => s.pick_folder.is_some(), + PickRequest::FolderAt(_) => s.pick_folder_at.is_some() || s.pick_folder.is_some(), } } @@ -402,11 +419,21 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option { PickRequest::Open(pick) => one(s.pick_open.as_mut().and_then(|f| f(pick))), PickRequest::Save(pick) => one(s.pick_save.as_mut().and_then(|f| f(pick))), PickRequest::Folder => one(s.pick_folder.as_mut().and_then(|f| f())), + PickRequest::FolderAt(start) => match (s.pick_folder_at.as_mut(), s.pick_folder.as_mut()) { + (Some(at), _) => one(at(start)), + (None, Some(f)) => one(f()), + (None, None) => None, + }, PickRequest::OpenMany => match (s.pick_open_multi.as_mut(), s.pick_open.as_mut()) { (Some(many), _) => Some(many()), (None, Some(f)) => one(f(&FilePick::default())), (None, None) => None, }, + PickRequest::OpenFiles(pick) => match (s.pick_open_files.as_mut(), s.pick_open.as_mut()) { + (Some(many), _) => Some(many(pick)), + (None, Some(f)) => one(f(pick)), + (None, None) => None, + }, } } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 02c2229741..799e73b2cc 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,7 +1,7 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm` or `prompt`, waits for the person's answer. +//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. use serde_json::json; @@ -44,6 +44,15 @@ pub fn poll(app: &mut VectorcraftApp) { /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. fn ask(app: &mut VectorcraftApp) -> bool { + if let Some(picker) = app.session.script_picker() { + if app.ui.dialog.is_none() { + script_run::open_picker(app, &picker); + } + return true; + } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::PICKER_KIND) { + app.ui.dialog = None; + } if let Some(dialog) = app.session.script_dialog() { if app.ui.dialog.is_none() { script_run::open_notice(app, &dialog); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 676a9a48c8..ce48ef17c1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -35,6 +35,11 @@ pub type PickOpen = Box Option>; pub type PickSave = Box Option>; +pub type PickOpenFiles = Box Vec>; + +/// Shows a folder picker that starts in the given folder; returns the folder picked. +pub type PickFolderAt = Box Option>; + pub type ReadFn = Box Result, String>>; /// The first `max` bytes of the file at a path (all of it when it is shorter); the rest of the file @@ -120,6 +125,9 @@ pub struct Services { pub open_url: Option, /// Show an open dialog for several files (File → Place…); returns their paths (none: cancelled). pub pick_open_multi: Option Vec>>, + /// Show an open dialog for several files of the pick's types (a script's `File.openDialog` with + /// `multiSelect`); returns their paths (none: cancelled). Without it, an open dialog for one. + pub pick_open_files: Option, /// Web: start an async pick of files to place (they arrive via `place_inbox`). pub place_async: Option>, /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the @@ -160,6 +168,9 @@ pub struct Services { pub open_in_photocraft: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, + /// Show a folder picker that starts in a folder (a script's `selectDlg`); returns its path. + /// Without it, `pick_folder`, which starts where the host starts it. + pub pick_folder_at: Option, /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, Linux /// through the desktop portal, and browsers with an EyeDropper): Sample Color from Screen /// ([`screen_color`]). Without it that command answers with an error and the Color Picker's diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index e808cf2463..f0926e1979 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -53,6 +53,7 @@ pub(crate) fn off_the_ui_thread(services: &mut Services) -> (Shown, Written) { services.pick_open = Some(Box::new(in_line)); services.pick_save = Some(Box::new(in_line)); services.pick_open_multi = Some(Box::new(|| panic!("no dialog on the UI thread"))); + services.pick_open_files = Some(Box::new(|_: &FilePick| panic!("no dialog on the UI thread"))); services.pick_folder = Some(Box::new(|| panic!("no dialog on the UI thread"))); services.read = Some(Box::new(|_: &str| Ok(SVG.to_vec()))); services.write = Some(Box::new(move |path: &str, _: &[u8]| { @@ -1074,11 +1075,11 @@ fn without_tests(code: &str) -> String { } /// The calls in `code` (from [`code_only`]) of the host's in-line dialogs: [`Services`]' -/// `pick_open`, `pick_save`, `pick_folder` and `pick_open_multi` used other than to ask whether -/// the host has them (`.is_some()`, `.is_none()`). +/// `pick_open`, `pick_save`, `pick_folder`, `pick_folder_at`, `pick_open_multi` and +/// `pick_open_files` used other than to ask whether the host has them (`.is_some()`, `.is_none()`). fn in_line_dialogs(code: &str) -> Vec { let mut found = vec![]; - for name in ["pick_open", "pick_save", "pick_folder", "pick_open_multi"] { + for name in ["pick_open", "pick_save", "pick_folder", "pick_folder_at", "pick_open_multi", "pick_open_files"] { let field = format!(".{name}"); let mut rest = code; while let Some(at) = rest.find(&field) { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 08ac8e1917..ba6553e068 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -267,9 +267,13 @@ fn a_stop_names_the_files_the_run_left_written() { let dir = folder("written"); let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); - let source = format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); + let source = format!("Folder.selectDialog('Folder'); vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}"); menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); script_runs::poll(&mut app); + assert!(app.session.script_picker().is_some(), "the run waits at its folder dialog"); + let paths = vec![dir.to_string_lossy().into_owned()]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + script_runs::poll(&mut app); assert!(path.exists()); app.ui.dialog = Some(crate::state::Dialog::new(dialogs::script_run::CLOSE_KIND, json!({}))); confirm(&mut app).unwrap(); @@ -277,6 +281,327 @@ fn a_stop_names_the_files_the_run_left_written() { let _ = std::fs::remove_dir_all(&dir); } +/// A script's open dialog with `multiSelect` shows the host's dialog for several files, with the +/// file types of the script's filter, and the script gets every file picked. +#[test] +fn a_scripts_open_dialog_picks_several_files_of_its_types() { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let dir = folder("several"); + let paths: Vec = ["a.txt", "b.txt"].iter().map(|n| dir.join(n).to_string_lossy().into_owned()).collect(); + for p in &paths { + std::fs::write(p, "x").unwrap(); + } + let (seen, given) = (asked.clone(), paths.clone()); + let services = crate::Services { + pick_open: Some(Box::new(|_: &crate::FilePick| panic!("the dialog for one file"))), + pick_open_files: Some(Box::new(move |pick: &crate::FilePick| { + seen.borrow_mut().push(pick.filters.clone()); + given.clone() + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick', 'Text:*.txt;All files:*.*', true); vc.log([f.length, f[0].name, f[1].name]);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + assert_eq!(*asked.borrow(), vec![vec![("Text".to_string(), vec!["txt".to_string()]), ("All files".to_string(), vec!["*".to_string()])]]); + assert_eq!(app.script_picked, paths); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "a.txt", "b.txt"]])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A folder's `selectDlg` asks the host for a folder picker that starts in that folder, and +/// `Folder.selectDialog` for one that starts where the host starts it. +#[test] +fn a_scripts_folder_dialog_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstart"); + let requests = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = requests.clone(); + let picked = dir.to_string_lossy().into_owned(); + let services = crate::Services { + start_pick: Some(Box::new(move |request: crate::picks::PickRequest| { + seen.borrow_mut().push(request); + None + })), + pick_folder: Some(Box::new(move || Some(picked.clone()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + let start = app.session.script_report().map(|r| r["log"].clone()); + assert_eq!(start, Some(json!([[true, true]]))); + let r = requests.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [crate::picks::PickRequest::FolderAt(s), crate::picks::PickRequest::Folder] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Where the host shows file dialogs in line (Windows), a folder's `selectDlg` also opens the +/// folder picker in that folder, and `Folder.selectDialog` the one that starts where the host +/// starts it. +#[test] +fn a_scripts_folder_dialog_shown_in_line_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstartinline"); + let shown = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let (at, plain) = (shown.clone(), shown.clone()); + let (picked_at, picked) = (dir.to_string_lossy().into_owned(), dir.to_string_lossy().into_owned()); + let services = crate::Services { + pick_folder_at: Some(Box::new(move |start: &str| { + at.borrow_mut().push(Some(start.to_string())); + Some(picked_at.clone()) + })), + pick_folder: Some(Box::new(move || { + plain.borrow_mut().push(None); + Some(picked.clone()) + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + assert_eq!(app.session.script_report().map(|r| r["log"].clone()), Some(json!([[true, true]]))); + let r = shown.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [Some(s), None] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A control request, handled as the app handles one: while `answering_control` is set. +fn control(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { + let (req, _) = crate::control::ControlRequest::new(method, params); + app.ui.answering_control = true; + let outcome = crate::control::handle(app, &egui::Context::default(), &req); + app.ui.answering_control = false; + let crate::control::Outcome::Done(r) = outcome else { panic!("expected an immediate reply") }; + r +} + +const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access"; + +/// The paths a script's file dialog allows come from Choose… alone: `ui.dialog.set` cannot set +/// them, and fields set on the dialog do not let Always Allow keep a grant the run cannot keep. +#[test] +fn a_scripts_file_dialog_takes_no_paths_from_automation() { + let dir = folder("automated"); + let secret = dir.join("secret.txt"); + std::fs::write(&secret, "secret").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.fsName);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND)); + let p = secret.to_string_lossy().into_owned(); + let r = control(&mut app, "ui.dialog.set", json!({"field": "paths", "value": [p]})); + assert!(r["error"].as_str().is_some_and(|e| e.contains("no field `paths`")), "{r}"); + let always = json!({"fields": [{"field": "canAlways", "value": true}, {"field": "answer", "value": "always"}], "action": "confirm"}); + let r = control(&mut app, "ui.dialog.set", always.clone()); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("answer".into(), json!("once")); + assert_eq!(confirm(&mut app).unwrap_err(), "choose a file or folder first, or deny"); + app.script_picked = vec![p]; + let r = control(&mut app, "ui.dialog.set", always); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("canAlways".into(), json!(true)); + d.fields.insert("answer".into(), json!("always")); + assert_eq!(confirm(&mut app).unwrap_err(), "this script's file access can be allowed only once"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Allow Once and Always Allow This Script are taken only from the person at the keyboard: a control +/// request and synthetic input are refused and the dialog stays open, after a person picked a file +/// with Choose… too, while Deny from automation is taken. +#[test] +fn a_scripts_file_access_is_allowed_only_by_the_person() { + let dir = folder("byperson"); + let picked = dir.join("picked.txt"); + std::fs::write(&picked, "picked").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.name);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "once"}], "action": "confirm"})); + assert_eq!(r["error"], BY_PERSON, "{r}"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "Deny is taken from automation: {r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + app.ui.dialog.as_mut().expect("the file dialog").fields.insert("answer".into(), json!("once")); + app.synthetic_frame = true; + assert_eq!(confirm(&mut app).unwrap_err(), BY_PERSON); + app.synthetic_frame = false; + assert!(app.session.script_picker().is_some(), "the run still waits"); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["picked.txt"])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The texts the dialog layer draws, once a few frames have let it settle. +fn dialog_texts(app: &mut VectorcraftApp) -> Vec { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = vec![]; + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + v.clear(); + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + } + v +} + +/// The dialog says what the run asks for and shows the script's prompt, also after `ui.dialog.set` +/// changed the dialog's `kind` and `prompt` fields. +#[test] +fn a_scripts_file_dialog_says_what_the_run_asks_for() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick the export folder'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let r = + control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "kind", "value": "open"}, {"field": "prompt", "value": "Nothing to see"}]})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + let texts = dialog_texts(&mut app); + let folder = "The script asks to read and write a folder you choose, with everything in it."; + assert!(texts.iter().any(|t| t == folder), "{texts:?}"); + assert!(texts.iter().any(|t| t == "Pick the export folder"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Nothing to see" || t == "The script asks to read a file you choose."), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Enter in the file dialog gives Deny, its default answer, also after the person picked a folder. +#[test] +fn enter_in_a_scripts_file_dialog_denies() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![folder("enterdeny").to_string_lossy().into_owned()]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for events in [vec![], vec![], vec![enter]] { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::PICKER_KIND), "the dialog closes"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); +} + +/// Enter on the file dialog's focused Choose… button goes to that button and does not deny. +#[test] +fn enter_on_a_focused_choose_button_does_not_deny() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(Folder.selectDialog('Pick'));" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let frame = |app: &mut VectorcraftApp, events| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + for events in [vec![], vec![], vec![key(egui::Key::Tab)], vec![]] { + frame(&mut app, events); + } + assert!(ctx.memory(|m| m.focused().is_some()), "Tab gives a button the keyboard focus"); + frame(&mut app, vec![key(egui::Key::Enter)]); + frame(&mut app, vec![]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND), "the dialog stays open"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Choose… keeps at most the 2,048 files a script is given, and the dialog says the files picked +/// after them were left out. +#[test] +fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { + let given: Vec = (0..2050).map(|n| format!("/picked/{n}.txt")).collect(); + let all = given.clone(); + let services = crate::Services { pick_open_files: Some(Box::new(move |_: &crate::FilePick| all.clone())), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "File.openDialog('Pick', '', true);" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + dialogs::script_run::choose(&mut app, &mut d); + app.ui.dialog = Some(d); + assert_eq!(app.script_picked, given[..2048]); + let texts = dialog_texts(&mut app); + let note = "A script is given at most 2,048 files: the files picked after them were left out"; + assert!(texts.iter().any(|t| t == note), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + #[test] fn a_new_app_shows_the_warning_by_default() { assert!(Session::new().prefs.show_external_script_warning); diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..dd5de656cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2218,8 +2218,8 @@ script reads files with them: - `open('r')` opens a file to read, and `read([chars])`, `readln()`, `readch()`, `seek(pos[, mode])`, `tell()`, `eof` and `close()` read it. `read`, `readln` and `readch` count characters, and `seek` and `tell` count bytes. `readln` and `readch` take CR, LF, CRLF and LF CR as one line end. `folder.getFiles([mask])` lists a folder, sorted by name; - the mask matches `*` and `?` without regard to case, and a function as the mask keeps the entries it returns true - for. + the mask matches `*` and `?`, without regard to case on Windows and macOS and with case elsewhere, and a function + as the mask keeps the entries it returns true for. - A method that fails returns `false`, `null` or an empty string and sets `error`, such as `Script file access denied`, `Script file does not exist` or `Script file is not open`. A count or a position that is not a finite number, or a negative count, throws a `RangeError`. @@ -2234,7 +2234,9 @@ VectorCraft reads files by these rules of its own: `getFiles` leaves such an entry out. A missing file is refused the same way unless the nearest folder above it that exists is inside the script's folder. It is also refused when a link above it leads to a folder that does not exist. - `open` reads the whole file. A file larger than 8 MiB is refused from its size before any of it is read, with - `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A run has at most 256 + `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A file opened again + after its objects closed counts only the bytes it grew by, and a file that another object has open counts again. A + run has at most 256 files open at once; another `open` returns `false` with `Script has 256 files open` until one is closed. - The encoding is the one the file's byte order mark gives (UTF-8, UTF-16LE or UTF-16BE), otherwise the `encoding` the script set before `open`, otherwise UTF-8 when the bytes are valid UTF-8, otherwise CP1252. `BINARY` reads each @@ -2245,11 +2247,111 @@ VectorCraft reads files by these rules of its own: folder gives `null` with `Script folder mask takes too many steps to match`. - A path longer than 32,767 characters throws a `RangeError` (`Script file path exceeds 32,767 characters`) when a `File` or `Folder` is made from it. -- Writing is not available yet: `open('w')`, `open('e')`, `open('a')`, `write`, `writeln`, `copy`, `remove`, - `rename`, `create` and `createAlias` return `false` with `Script file writing is not available`, and setting - `length`, `hidden` or `readonly` sets `error` to that message and changes nothing. The file - and folder dialogs return `null`, and `execute` opens nothing and returns `false`. In the web build every lookup - fails with `Script file access is unavailable on the web`. +- `createAlias` returns `false` with `Script files cannot make aliases`, setting `hidden` sets `error` to `Script + file hidden setting cannot be changed` and changes nothing, and `execute` opens nothing and returns `false`. In the + web build every lookup fails with `Script file access is unavailable on the web`. + +The help page's writing members work as it describes +(, +): + +- `open('w')` empties the file, or makes it, `open('e')` opens a file that is there, and `open('a')` opens it at its + end. `write(...values)` writes the values as `String(value)` gives them, and `writeln(...values)` adds the line end + `lineFeed` names: CR LF for `Windows`, CR for `Macintosh` and LF for `Unix`. A byte order mark is written only + when the script writes ``. +- `copy(target)` copies the file to a path or a `File` and replaces a file that is there. `remove()` deletes a file, + or a folder only when it is empty (`Script folder is not empty`), at once and without the trash. `rename(name)` + takes a name without a folder; a name that is in use gives `Script file name is already in use`, and the object + takes the new path; another object that has the file open writes to the new path. An object whose changes + `close` could not write does not remove or rename its file, and another object that has a removed file open + drops its changes and takes no more writes. `copy` of a file over 8 MiB gives `Script file exceeds 8 MiB`, and `copy` of a file that + is open copies what the open file holds; an object that has the target open then holds the copy. `folder.create()` makes the folder and the folders above it, and gives `Script file access denied` without making any when one of them is outside the places the script may write. Setting `length` cuts the file or + pads it with zero bytes, also in an object that has the file open, and setting `readonly` changes the file (on + Unix, setting it clears every write bit, and clearing it gives back the bits the run cleared, or else the owner's + write bit). `changePath` of an object whose changes cannot be written gives `false` with `error` set and keeps its path. `copy` onto the file itself leaves it as it is, and `open('w')` with an + encoding that is not one gives `false` and leaves the file as it is. +- `File.openDialog(prompt, filter, multiSelect)`, `File.saveDialog(prompt, filter)` and `Folder.selectDialog(prompt)`, + and the objects' `openDlg`, `saveDlg` and `selectDlg`, give a `File` or a `Folder`, or `null` when the person + cancels; `multiSelect` gives an array of the files picked. A string `filter` such as `"JavaScript:*.jsx;All + files:*.*"` gives the file types the dialog shows: each `name:pattern` starts a type, a pattern without a name adds + to the type before it, and patterns are separated by `,` or `;`. `*.ext` patterns name extensions and `*` or `*.*` + every file; other patterns are left out. A `filter` that is a function is called with a `File` for each file + picked, and the files it gives a false value for are left out of the result; when none is left, the dialog + gives `null`. The dialog itself then shows every file. + +VectorCraft writes files by these rules of its own: + +- A script writes only in `Folder.temp`, `Folder.userData` and what a person allowed it in a file dialog. Its own + folder is only read. `Folder.temp` is a folder for the run, made when the script first names it and deleted when + the run ends; `new File()` names a new file there. `Folder.userData` is the script's own folder in the Script Data + folder next to the settings, kept between runs; a script given as `source`, or a session without a settings + folder, gets one inside `Folder.temp`. When that folder is a link, `Folder.userData` is `null` and the place the + link leads to is not granted. When automation write roots are set and do not take the folder, `Folder.temp` or + `Folder.userData` is `null` and the folder is not made; the same holds when they do not take a missing folder above it. When automation write roots are set, the place written must also be inside + them. Opening a file with `e` or `a` reads it, so the automation read roots apply to it as well. The folder that + holds the settings (the Scripts and Plug-ins folders among them) is kept out of every grant, also before it has + been made, apart from the script's own `Folder.userData`, and a folder that holds it cannot be renamed. Anything + else gives `false` with + `Script file access denied`. +- What a script writes is written when it closes the file or when the run ends, also when the run fails. At the + run's end the files left open are written in the order they were opened. A file + that `close` could not write is written again when the run ends, and a `write` that would pass the run's limit + is not written. A run that + would otherwise succeed fails when a changed file it left open cannot be written, with + `Error: the script left open files that could not be written` and the files' paths. One file + holds at most 8 MiB, and a run that writes more than 32 MiB in all ends with an error. `write` encodes in the + file's encoding: `ASCII` and `ISO-8859-1` give `false` with `Script file cannot encode the text` for a character + they cannot hold, and `BINARY` writes each character's low byte. `write` and `writeln` turn their values into text + only for an open file, and stop once the text is longer than 16,777,216 UTF-16 code units, giving `false` with + `Script file exceeds 8 MiB`. Each object that has a file open holds its own bytes, so the 32 MiB counts what + setting `length` adds to the file and to each such object, and what `copy` writes to its target and to each such + object of the target. The report's `written` names each file written, at most 4,096 of them; a run that wrote more + also has `writtenMore: true`. +- In the app a file dialog shows the script's prompt and what the script asks for: a file to read (open), a file to + read and write (save), or a folder to read and write with everything in it. The person chooses with Choose…, whose + dialog picks several files at once, and adds them to those chosen before, when the script asked for several with + `multiSelect` (Choose… keeps at most 2,048, and the dialog says when it left out the files picked after them), and + then picks Allow Once, Always Allow This Script or Deny; Deny, Enter, Escape and Cancel give `null`, and Stop ends + the run. Choose… for a folder's `selectDlg` opens the host's folder dialog in that folder. + The prompt and what the dialog says the script asks for come from the script's request, so `ui.dialog.set` on the + dialog's `kind` or `prompt` does not change them. Only the person at the keyboard allows access: an `answer` of + `once` or `always` from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input gives `Only the person at the + keyboard can allow a script's file access`, and the dialog stays open; `deny` and `stop` are taken from automation. + Always Allow This Script keeps the grant in `Script Grants.json` next to the settings for that script file with + that text with the files it includes, by its SHA-256, so a changed or moved script, or a changed included file, + asks again. It is offered only for a script run from a file. The grant also keeps the SHA-256 of each source the + run evaluated up to its end (a file `$.evalFile` ran, a string given to `eval` or `Function`, at most 256). A later + run loses the grant before it evaluates a source the grant does not list, and from the start when its + `#targetengine` engine holds code the grant does not list, such as another script's. A kept grant stays on the + real path that was allowed: when that path now leads elsewhere, through a link put in its place or in a folder + above it, the grant is not used. +- A command a script runs with `vc.run` reads and writes files only where the script's `File` and `Folder` objects + may, and in the files the open documents were opened from or saved to. Anything else fails with + `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic + styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in + its `Folder.temp` and `Folder.userData` and to the open documents' own files. + A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's + own folders is not allowed`. +- A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to + `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a + built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. + +`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` +the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's +grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later +takes its place), and `file` the grants +file's path, or `null` without a settings folder. `script.grants.revoke {script?, path?, all?}` removes the grants of +a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. While a script +runs it is refused with the busy error, as the run keeps the grants it started with. A script cannot run either +command. + +```json +{"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} +``` + +```sh +vectorcraft-cli run --cmd script.grants --params '{}' +``` Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and `$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message` (or `name: file:line:column: message` when the error is in another diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..ba3af3858f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,7 +783,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; writing, the file dialogs and `execute` are not available yet. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. From 2a54ad21cdb9275f20194a6a3e5ad32ef2ca4e00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 06:29:38 -0800 Subject: [PATCH 003/138] Image Trace: the Flat Logo size test expects the status line with its note count A trace with one note now shows "Traced with 1 note: ..." and keeps the note for the message's hover. The test that traces a 1602 x 1602 image as a Flat Logo checks that line and the hover's note list. --- crates/ui-egui/src/panels/image_trace/tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 1586943c07..e30a701d72 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -107,7 +107,10 @@ fn a_large_image_traced_as_a_flat_logo_shows_the_size_it_was_traced_at() { app.run("file.place", json!({"name": "logo.png", "dataBase64": data, "link": false})).unwrap(); trace_with(&mut app, "Flat Logo"); assert!(target(&app).2.is_some(), "the image is traced: {}", app.ui.status); - assert_eq!(app.ui.status, "Flat Logo traced the image at 801 × 801 pixels, averaged down from 1602 × 1602."); + let note = "Flat Logo traced the image at 801 × 801 pixels, averaged down from 1602 × 1602."; + let status = format!("Traced with 1 note: {note}"); + assert_eq!(app.ui.status, status); + assert_eq!(app.ui.status_notes, Some((status, vec![note.to_string()]))); } #[test] From db26ce4a945368723aec538608c6c595626609ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:11:22 -0800 Subject: [PATCH 004/138] Tests: the script report test allows its script the folder it writes in A script now writes only in its own folders and in what a person allowed it, so the ui.inspect script report test picks the test folder in the script's folder dialog before the script exports into it. --- crates/ui-egui/src/tests/automation.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index d7f438d285..3683ec1ae7 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -1004,22 +1004,26 @@ fn ui_inspect_keeps_text_that_only_looks_like_a_library_id() { let _ = std::fs::remove_dir_all(base); } -/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root, and -/// the included file a failed run stopped in (also in its error line), by its file name; the person -/// sees the paths. +/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root (in +/// the folder the person allowed it), and the included file a failed run stopped in (also in its +/// error line), by its file name; the person sees the paths. #[test] fn ui_inspect_script_report_leaves_out_files_outside_the_read_root() { let (mut app, tx, base) = confined("inspect-script-report"); let (kept, hidden) = (s(base.join("in/kept.svg")), s(base.join("outside/hidden.svg"))); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let source = format!( - "vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", + "Folder.selectDialog('Folder'); vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", kept = json!(kept), hidden = json!(hidden) ); let finish = |app: &mut VectorcraftApp, params: Value| { app.session.execute("script.run", ¶ms).unwrap(); for _ in 0..10_000 { + if app.session.script_picker().is_some() { + let paths = vec![s(base.clone())]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + } if app.session.script_pump().is_some() { break; } From eb1f29f94bcc66f4362b9dd448f43b3012005afe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:56:02 -0800 Subject: [PATCH 005/138] Scripts: a script in the settings folder reads only its own file there A script run from a file directly in the settings folder could read every file in that folder, Script Grants.json included, because its own folder was left open inside the fence. Only folders below the settings folder stay open now, and a script in the settings folder itself reads only its own file there. --- crates/engine/src/script/files.rs | 10 ++++++++-- crates/engine/src/tests/script_io.rs | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 37f3b93213..258d5a2863 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -79,7 +79,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; use super::{Host, bump}; -use crate::file_access::{ScriptRead, ScriptScope}; +use crate::file_access::{ScriptRead, ScriptScope, path_inside}; /// The most bytes of one file a script opens. pub const MAX_FILE_BYTES: usize = 8 << 20; @@ -331,7 +331,13 @@ impl Disk { let _ = d.saw(hash); } if let Some(f) = fenced { - let own = d.scope.roots().to_vec(); + // A script's folder inside the settings folder stays open; the settings folder itself + // does not, only the script's own file there. + let roots = d.scope.roots(); + let mut own: Vec = roots.iter().filter(|r| !path_inside(&f, r)).cloned().collect(); + if roots.iter().any(|r| path_inside(r, &f) && path_inside(&f, r)) { + own.extend(d.script.as_ref().map(|(p, _)| p.clone())); + } d.scope.fence(f.clone(), &own); d.writes.fence(f, &[]); } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 0d09bd2796..e3e7ade3a2 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1108,6 +1108,25 @@ fn script_files_in_a_folder_above_the_settings_folder_do_not_reach_it() { let _ = std::fs::remove_dir_all(base); } +/// A script run from the settings folder itself reads its own file there, but no other file in the +/// settings folder. +#[test] +fn script_files_in_the_settings_folder_do_not_reach_it() { + let base = folder("insettings"); + let mut s = Session::new(); + s.attach_script_data(base.join("main/Script Data")); + write(&base.join("main/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + let r = run_in( + &mut s, + &base, + "var a = new File('main.jsx'), g = new File('Script Grants.json');\n\ + var out = [a.open('r'), a.read().length > 0]; a.close(); out.push(g.open('r'), g.error, g.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([[true, true, false, DENIED, false]])); + let _ = std::fs::remove_dir_all(base); +} + /// The settings folder is kept out of every grant also before it has been made. #[test] fn script_file_grants_never_reach_a_settings_folder_not_made_yet() { From ea21d344c9f133f590a90b1a04ea4cee88fafe72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:36:36 -0800 Subject: [PATCH 006/138] i18n: Dutch rows for script file access messages --- crates/ui-egui/src/i18n/nl.tsv | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index df8847ea77..f1e6c1fc37 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -83,6 +83,27 @@ @msg Script file path exceeds 32,767 characters Het pad van het scriptbestand is langer dan 32.767 tekens @msg Script folder mask takes too many steps to match Het masker van de scriptmap vraagt te veel stappen om te vergelijken @msg the script opened more file data than one run may open (32 MiB) het script heeft meer bestandsgegevens geopend dan één uitvoering mag openen (32 MiB) +@msg Script file access denied: {path} Toegang tot het scriptbestand geweigerd: {path} +@msg Script file access to the app's own folders is not allowed Scriptbestanden mogen geen toegang krijgen tot de eigen mappen van de app +@msg Script file cannot encode the text Het scriptbestand kan de tekst niet coderen +@msg Script file could not be written Het scriptbestand kon niet worden geschreven +@msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord +@msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven +@msg Script file name is already in use De naam van het scriptbestand is al in gebruik +@msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn +@msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd +@msg Script file permission could not be saved De toestemming voor het scriptbestand kon niet worden opgeslagen +@msg Script folder is not empty De scriptmap is niet leeg +@msg Script files cannot make aliases Scriptbestanden kunnen geen aliassen maken +@msg Script file hidden setting cannot be changed De instelling Verborgen van het scriptbestand kan niet worden gewijzigd +@msg {name}: a file 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 bestandsdialoogvenster kan niet worden geopend binnen een callback van een ingebouwde functie, een getter, een conversie of een bestand dat door $.evalFile wordt uitgevoerd; roep het aan vanuit de eigen code van het script +@msg the script wrote more file data than one run may write (32 MiB) het script heeft meer bestandsgegevens geschreven dan één uitvoering mag schrijven (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop +@msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger +@msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan +@msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan +@msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten @msg File.seek: takes a position and a mode File.seek: verwacht een positie en een modus @msg vc.run: give a command id, as a string vc.run: geef een opdracht-id, als string @msg vc.run: takes a command id and an object of parameters vc.run: verwacht een opdracht-id en een object met parameters From 4f8e1d5ed2d59ce6c0c4f5d2f50a4fe8075546dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:48:48 -0800 Subject: [PATCH 007/138] i18n: Hindi script file messages use the glossary term for save --- crates/ui-egui/src/i18n/hi.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b01e66ed4f..07ff5595c2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6614,7 +6614,7 @@ antiAlias Sharp शार्प @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है -@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सहेजी नहीं जा सकी +@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सेव नहीं की जा सकी @msg Script folder is not empty स्क्रिप्ट फ़ोल्डर खाली नहीं है @msg Script files cannot make aliases स्क्रिप्ट फ़ाइलें उपनाम नहीं बना सकतीं @msg Script file hidden setting cannot be changed स्क्रिप्ट फ़ाइल की छिपी सेटिंग बदली नहीं जा सकती @@ -6622,7 +6622,7 @@ antiAlias Sharp शार्प @msg the script wrote more file data than one run may write (32 MiB) स्क्रिप्ट ने एक रन में लिखे जा सकने वाले फ़ाइल डेटा से अधिक लिखा (32 MiB) @msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop @msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें -@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सहेजी नहीं जा सकीं: {e} +@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सेव नहीं की जा सकीं: {e} @msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है @msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है @msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं From 6742d277e960cd257de6ef93e13476ab7966ebdd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 09:35:28 -0800 Subject: [PATCH 008/138] Tools: Ctrl+` chooses the selection tool chosen last Select Last Selection Tool (tool.selectLastSelection, {}) chooses the one of Selection, Direct Selection and Group Selection chosen last, or the Selection tool before any of them is chosen. Magic Wand, Lasso and other tools do not change which one it chooses, and running it with that tool active keeps it. It returns {tool} and adds no undo step. The help page lists the shortcut: https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html - Default Ctrl+` (Cmd+~) on Windows and Linux. macOS keeps Command+` for switching between an app's windows, so the command has no default there; Edit > Keyboard Shortcuts can assign one. The keymap, the shortcut editor and engine.commands use the platform's default. - The headless backend and vectorcraft-cli run accept it as a host command. - In the app, tool.select and tool.selectLastSelection return the error when the tool switch fails. The app's tool.select reported success before and showed the error only in the status bar. - A row for the label in every catalog; docs/mcp.md and the progress line in docs/target-app-parity.md. --- crates/engine/src/tooling.rs | 6 +++++ crates/mcp/src/headless.rs | 15 ++++++++++++ crates/mcp/src/tests.rs | 24 +++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 6 +++++ crates/ui-egui/src/app/commands.rs | 23 +++++++++++++----- crates/ui-egui/src/canvas/tests.rs | 31 +++++++++++++++++++++++++ crates/ui-egui/src/control.rs | 1 + crates/ui-egui/src/control/tests.rs | 16 +++++++++++++ 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/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/keymap.rs | 22 +++++++++++++++++- crates/ui-egui/src/menus/run.rs | 10 ++++---- crates/ui-egui/src/menus/ui_commands.rs | 6 +++++ crates/ui-egui/src/shortcut_editor.rs | 29 ++++++++++++++++++----- crates/ui-egui/src/shortcuts/tests.rs | 24 +++++++++++++++++++ docs/mcp.md | 12 +++++++++- docs/target-app-parity.md | 1 + 42 files changed, 235 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 0452251a09..fe6b4523e7 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -120,6 +120,12 @@ impl Session { self.tool.id() } + /// The selection tool chosen last (Selection, Direct Selection or Group Selection), which + /// `tool.selectLastSelection` chooses: the Selection tool until one is chosen. + pub fn last_selection_tool(&self) -> &'static str { + self.last_selection_tool.unwrap_or("selection") + } + /// How many times switching or closing documents, or replacing the active one (File › Revert), /// has started the tool afresh, also inside a `command.batch` or `action.batch`. A frontend /// compares it before and after a command. diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 69c7b5ba0e..6b34a82edc 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -45,6 +45,11 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ "{folder?, zip?, artboards? | range? | fullDocument? | assets?, includeBleed?, includeArtboardFill?, subfolders?, preset?, formats?, settings?, prefix?} = document.exportForScreens (no folder → the files, or one zip, as dataBase64)", ), ("tool.select", "Select Tool", "{tool} e.g. selection, directSelection, pen, rectangle, ellipse, polygon, star, lineSegment"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool) → {tool}", + ), ( "tool.setOption", "Tool Option", @@ -164,6 +169,7 @@ impl Headless { "file.export" => self.export(params), "file.exportForScreens" => self.session.execute("document.exportForScreens", params).map_err(|e| e.to_string()), "tool.select" => self.select_tool(params), + "tool.selectLastSelection" => self.select_last_selection_tool(), "tool.setOption" => self.session.set_tool_option_cmd(params), _ => self.session.execute(id, params).map_err(|e| e.to_string()), } @@ -207,6 +213,15 @@ impl Headless { Ok(json!({"tool": self.session.tool_id()})) } + /// `tool.selectLastSelection`: the selection tool chosen last, kept when it is already active. + fn select_last_selection_tool(&mut self) -> Result { + let id = self.session.last_selection_tool(); + if self.session.tool_id() != id { + self.session.select_tool(id, self.view).map_err(|e| e.to_string())?; + } + Ok(json!({"tool": self.session.tool_id()})) + } + fn apply_ui_requests(&mut self, reqs: Vec, out: &mut Vec) -> Result<(), String> { for r in reqs { match r { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6529cf175d..987df83c3f 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1797,6 +1797,30 @@ fn e_during_a_marquee_gesture_selects_only_the_objects_inside() { assert_eq!(serde_json::from_str::(&text_of(&r)).unwrap()["handledBy"], "tool.select", "{r}"); } +/// `run_command tool.selectLastSelection` headless: the Selection tool before any selection tool +/// is chosen, then the selection tool chosen last; Magic Wand doesn't count. `list_commands` +/// lists it as a command the headless backend runs. +#[test] +fn select_last_selection_tool_runs_headless() { + let mut s = server(); + let mut id = 0; + let mut run = |s: &mut Server, command: &str, params: Value| { + id += 1; + let r = call(s, id, "run_command", json!({"command": command, "params": params})); + assert_eq!(r["isError"], false, "{command}: {r}"); + serde_json::from_str::(&text_of(&r)).unwrap() + }; + run(&mut s, "tool.select", json!({"tool": "pen"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "selection"})); + run(&mut s, "tool.select", json!({"tool": "groupSelection"})); + run(&mut s, "tool.select", json!({"tool": "magicWand"})); + assert_eq!(run(&mut s, "tool.selectLastSelection", json!({})), json!({"tool": "groupSelection"})); + let r = call(&mut s, 99, "list_commands", json!({"filter": "selectLastSelection"})); + let v: Value = serde_json::from_str(&text_of(&r)).unwrap(); + let listed = v["commands"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned().unwrap_or_default(); + assert_eq!((listed["host"].clone(), listed["label"].clone()), (json!(true), json!("Select Last Selection Tool")), "{v}"); +} + /// `press_key {key: "c"}` and `{key: "f"}` while an arc is being dragged go to the Arc tool, and /// the release draws one arc. With nothing dragged, C is a shortcut again. #[test] diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 3e80e0a2dd..59c1fece68 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -771,6 +771,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools)"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "Cmd+~", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows", + ), ( "tool.setOption", "Tool Option", diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 1d2493385e..479c4df359 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -411,31 +411,41 @@ impl VectorcraftApp { /// Select a tool (also used by the toolbar and shortcuts). pub fn select_tool(&mut self, id: &str) { + // A failure shows in the status bar. + let _ = self.try_select_tool(id); + } + + /// [`Self::select_tool`], returning the error it shows in the status bar when the switch fails. + pub(crate) fn try_select_tool(&mut self, id: &str) -> Result<(), String> { // The tip of a pen whose eraser end selected the Eraser doesn't undo this choice, and // neither does letting go of a held tool shortcut. self.pen_end.forget_tool(); self.held_tool.clear(); - self.activate_tool(id, true); + let switched = self.activate_tool(id, true); let now = self.session.tool_id(); if crate::touch::is_drawing_tool(now) { self.ui.touch_drawing_tool = Some(now.to_string()); } + switched } /// Go back to tool `id` after a tool that stood in for it (the pen's eraser end, [`stylus`]): /// a perspective grid hidden meanwhile stays hidden. pub(crate) fn return_to_tool(&mut self, id: &str) { - self.activate_tool(id, false); + // A failure shows in the status bar. + let _ = self.activate_tool(id, false); } /// Make tool `id` active: chosen afresh (`fresh`, [`vectorcraft_engine::Session::select_tool`]), - /// or back from a tool that stood in for it ([`vectorcraft_engine::Session::switch_tool`]). - fn activate_tool(&mut self, id: &str, fresh: bool) { + /// or back from a tool that stood in for it ([`vectorcraft_engine::Session::switch_tool`]). A + /// failure is shown in the status bar and returned. + fn activate_tool(&mut self, id: &str, fresh: bool) -> Result<(), String> { let v = self.view_info(); let before = self.session.tool_id(); let switched = if fresh { self.session.select_tool(id, v) } else { self.session.switch_tool(id, v) }; - if let Err(e) = switched { - self.ui.status = e.to_string(); + let switched = switched.map_err(|e| e.to_string()); + if let Err(e) = &switched { + self.ui.status.clone_from(e); } if before != self.session.tool_id() { // A control gesture cannot resume after another tool has owned the pointer. @@ -455,6 +465,7 @@ impl VectorcraftApp { } toolbar::remember(self, id); self.ui.flyout = None; + switched } /// Show a transient status message. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 6bf8a6fa97..089e597ee5 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1051,6 +1051,37 @@ fn switch_selection_and_drawing_modes_command() { } } +/// Select Last Selection Tool: the Selection tool before any selection tool is chosen, then the +/// one of Selection, Direct Selection and Group Selection chosen last; Magic Wand and Lasso don't +/// count. Running it again keeps that tool, and it changes no art, selection or undo history. +#[test] +fn select_last_selection_tool_command() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let last = |app: &mut VectorcraftApp| app.run("tool.selectLastSelection", json!({})).unwrap(); + let state = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + (st.doc.clone(), st.selection.clone(), st.history.undo.len()) + }; + app.select_tool("pen"); + let before = state(&app); + assert_eq!((last(&mut app), app.session.tool_id()), (json!({"tool": "selection"}), "selection"), "none chosen yet: Selection"); + for id in ["directSelection", "groupSelection", "selection"] { + app.select_tool(id); + app.select_tool("pen"); + assert_eq!(last(&mut app), json!({"tool": id}), "{id}"); + } + app.select_tool("directSelection"); + for other in ["magicWand", "lasso", "rectangle", "hand"] { + app.select_tool(other); + } + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "Magic Wand and Lasso are not remembered"); + assert_eq!(last(&mut app), json!({"tool": "directSelection"}), "again: the same tool, no cycling"); + assert!(state(&app) == before, "no art, selection or undo step changes"); +} + /// The Artboard tool's label holds the artboard's name (never translated); the tools' own /// labels are interface text. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 89ab7e37b4..ca1d8baea1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -239,6 +239,7 @@ fn wrap(r: Result) -> Outcome { pub fn all_commands(app: &VectorcraftApp) -> Value { let mut v: Vec = app.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); for (id, label, sc, params) in crate::menus::UI_COMMANDS { + let sc = crate::shortcut_editor::ui_command_default(id, sc, crate::keymap::platform()); v.push(json!({"id": id, "label": label, "shortcut": sc, "params": params, "enabled": crate::menus::enabled(app, id), "ui": true})); } Value::Array(v) diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index ac8fbfa3eb..08d6f9539c 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -1273,3 +1273,19 @@ fn dialog_set_refuses_a_field_the_dialog_does_not_have() { app.ui.dialog = None; assert_eq!(input_request(&mut app, "ui.dialog.set", json!({"field": "name", "value": "A"}))["error"], "no dialog open"); } + +/// `engine.commands` lists each UI command's default shortcut on this platform: Select Last +/// Selection Tool shows Ctrl+` (`Cmd+~`) on Windows and Linux and none on macOS. +#[test] +fn the_command_list_shows_this_platforms_default_shortcut() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let r = input_request(&mut app, "engine.commands", json!({})); + let row = r["result"].as_array().unwrap().iter().find(|c| c["id"] == "tool.selectLastSelection").cloned(); + let row = row.unwrap_or_else(|| panic!("listed: {r}")); + assert_eq!(row["shortcut"], if crate::keymap::platform().is_mac() { "" } else { "Cmd+~" }, "{row}"); + for p in [craft_keymap::Platform::Windows, craft_keymap::Platform::Linux] { + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", p), "Cmd+~", "{p:?}"); + } + assert_eq!(crate::shortcut_editor::ui_command_default("tool.selectLastSelection", "Cmd+~", craft_keymap::Platform::Mac), ""); + assert_eq!(crate::shortcut_editor::ui_command_default("view.zoomIn", "Cmd+=", craft_keymap::Platform::Mac), "Cmd+="); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 708ffe9db6..552589dbf6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1019,6 +1019,7 @@ font-technology Variable Променливи Enable text access for screen readers Разрешаване на достъп до текст за екранни четци Enable Touch Gestures Разрешаване на докосващи жестове Switch Selection and Drawing Modes Превключване между режим на селекция и рисуване + Select Last Selection Tool Избор на последния инструмент за селекция Enable Touch Workspace Разрешаване на работно пространство за докосване Encoding Кодиране Encoding: Кодиране: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 8f5ea73487..6b9a238354 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3749,6 +3749,7 @@ theme Appearance Izgled Enable Rubber Band for Omogući gumenu traku za Enable Touch Gestures Omogući pokrete dodirom Switch Selection and Drawing Modes Prebaci između načina odabira i crtanja + Select Last Selection Tool Odaberi posljednji alat za odabir Enable Touch Workspace Omogući radni prostor za dodir English: UK Engleski: UK Every (minutes) Svakih (minuta) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5516c9662f..cb3b052504 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1486,6 +1486,7 @@ antiAlias Sharp Nítid Enable text access for screen readers Activa l’accés al text per als lectors de pantalla Enable Touch Gestures Activa els gestos tàctils Switch Selection and Drawing Modes Canvia entre els modes de selecció i de dibuix + Select Last Selection Tool Tria l'última eina de selecció Enable Touch Workspace Activa l’espai de treball tàctil Encoding Codificació Encoding and writing the file… S’està codificant i escrivint el fitxer… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d03d192a3a..94be545cf5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3803,6 +3803,7 @@ theme Appearance Motiv Enable Rubber Band for Povolit gumovou čáru pro Enable Touch Gestures Povolit dotyková gesta Switch Selection and Drawing Modes Přepnout mezi režimem výběru a kreslení + Select Last Selection Tool Vybrat poslední nástroj výběru Enable Touch Workspace Povolit dotykový pracovní prostor English: UK Angličtina: Spojené království Every (minutes) Každých (minut) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 00c85aaeb6..409f9f2324 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3536,6 +3536,7 @@ theme Appearance Udseende Enable Rubber Band for Aktivér gummibånd for Enable Touch Gestures Aktivér berøringsbevægelser Switch Selection and Drawing Modes Skift mellem markerings- og tegnetilstand + Select Last Selection Tool Vælg det seneste markeringsværktøj Enable Touch Workspace Aktivér touch-arbejdsområde English: UK Engelsk: UK Every (minutes) Hvert (minut) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 47337855aa..eb36468471 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1021,6 +1021,7 @@ font-technology Variable Variabel Enable text access for screen readers Textzugriff für Bildschirmlesegeräte zulassen Enable Touch Gestures Touch-Gesten aktivieren Switch Selection and Drawing Modes Zwischen Auswahl- und Zeichenmodus wechseln + Select Last Selection Tool Zuletzt verwendetes Auswahl-Werkzeug wählen Enable Touch Workspace Touch-Arbeitsbereich aktivieren Encoding Kodierung Encoding: Kodierung: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c319729a71..9ca053e657 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -989,6 +989,7 @@ font-technology Variable Μεταβλητές Enable text access for screen readers Ενεργοποίηση πρόσβασης κειμένου για αναγνώστες οθόνης Enable Touch Gestures Ενεργοποίηση χειρονομιών αφής Switch Selection and Drawing Modes Εναλλαγή λειτουργιών επιλογής και σχεδίασης + Select Last Selection Tool Επιλογή του τελευταίου εργαλείου επιλογής Enable Touch Workspace Ενεργοποίηση χώρου εργασίας αφής Encoding Κωδικοποίηση Encoding: Κωδικοποίηση: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b203292a4..98edc0b25f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1042,6 +1042,7 @@ font-technology Variable Variables Enable text access for screen readers Permitir el acceso al texto para lectores de pantalla Enable Touch Gestures Activar gestos táctiles Switch Selection and Drawing Modes Cambiar entre modos de selección y dibujo + Select Last Selection Tool Elegir la última herramienta de selección Enable Touch Workspace Activar espacio de trabajo táctil Encoding Codificación Encoding: Codificación: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index b2c6f48d54..cd231f0606 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3741,6 +3741,7 @@ theme Appearance Ulkoasu Enable Rubber Band for Ota kumilankavalinta käyttöön kohteelle Enable Touch Gestures Ota kosketuseleet käyttöön Switch Selection and Drawing Modes Vaihda valinta- ja piirtotilan välillä + Select Last Selection Tool Valitse viimeksi käytetty valintatyökalu Enable Touch Workspace Ota kosketustyötila käyttöön English: UK Englanti: UK Every (minutes) Välein (minuuttia) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e84f344060..d03fd4bfa6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1037,6 +1037,7 @@ font-technology Variable Variables Enable text access for screen readers Autoriser l’accès au texte pour les lecteurs d’écran Enable Touch Gestures Activer les gestes tactiles Switch Selection and Drawing Modes Basculer entre les modes sélection et dessin + Select Last Selection Tool Choisir le dernier outil de sélection Enable Touch Workspace Activer l’espace de travail tactile Encoding Codage Encoding: Codage : diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 017bc03750..858535b20d 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1637,6 +1637,7 @@ antiAlias Sharp शार्प Enable text access for screen readers स्क्रीन रीडर के लिए टेक्स्ट एक्सेस सक्षम करें Enable Touch Gestures टच जेस्चर ऑन करें Switch Selection and Drawing Modes चयन और ड्रॉइंग मोड के बीच बदलें + Select Last Selection Tool पिछला सिलेक्शन टूल चुनें Enable Touch Workspace टच वर्कस्पेस सक्षम करें Enclosing Lasso लासो संलग्न करना Enclosing Lasso Tool लासो टूल संलग्न करना diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index effb31e5d8..a39b65a47e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1322,6 +1322,7 @@ font-technology Variable Változó Enable text access for screen readers Szöveghozzáférés engedélyezése képernyőolvasóknak Enable Touch Gestures Érintési kézmozdulatok Switch Selection and Drawing Modes Váltás a kijelölési és a rajzolási mód között + Select Last Selection Tool Az utoljára használt kijelölőeszköz kiválasztása Enable Touch Workspace Érintőképernyős munkaterület Encoding Kódolás Encoding: Kódolás: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 912c6954eb..3c2d75c67a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3536,6 +3536,7 @@ theme Appearance Tampilan Enable Rubber Band for Aktifkan rubber band untuk Enable Touch Gestures Aktifkan gestur sentuh Switch Selection and Drawing Modes Beralih antara mode seleksi dan menggambar + Select Last Selection Tool Pilih alat seleksi terakhir Enable Touch Workspace Aktifkan ruang kerja sentuh English: UK Inggris: UK Every (minutes) Setiap (menit) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2d6c7e2186..8d5bdddd7f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1051,6 +1051,7 @@ font-technology Variable Variabili Enable text access for screen readers Consenti l'accesso al testo per le utilità di lettura dello schermo Enable Touch Gestures Attiva gesti touch Switch Selection and Drawing Modes Passa tra modalità selezione e disegno + Select Last Selection Tool Scegli l'ultimo strumento di selezione Enable Touch Workspace Attiva area di lavoro touch Encoding Codifica Encoding: Codifica: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 17444d894e..7052dad10e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1642,6 +1642,7 @@ antiAlias Sharp シャープ Enable Rubber Band for ラバーバンドを有効にする対象 Enable Touch Gestures タッチジェスチャーを有効にする Switch Selection and Drawing Modes 選択モードと描画モードを切り替え + Select Last Selection Tool 最後に使用した選択ツールに切り替え Enable Touch Workspace タッチワークスペースを有効にする Enable copying of text, images and other content テキスト、イメージ、その他のコンテンツのコピーを許可 Enable in-menu font previews メニュー内でフォントプレビューを有効にする diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index be8a847cb2..fa1404c866 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3380,6 +3380,7 @@ theme Appearance იერსახე Enable Rubber Band for რეზინის ზოლის ჩართვა: Enable Touch Gestures შეხების ჟესტების ჩართვა Switch Selection and Drawing Modes მონიშვნისა და ხატვის რეჟიმების გადართვა + Select Last Selection Tool ბოლოს გამოყენებული მონიშვნის ხელსაწყოს არჩევა Enable Touch Workspace სენსორული სამუშაო სივრცის ჩართვა English: UK ინგლისური: ბრიტანეთი Every (minutes) ყოველ (წუთში) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 991daba6d0..d9640a1856 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1632,6 +1632,7 @@ antiAlias Sharp 날카롭게 Enable Rubber Band for 러버 밴드 사용 대상 Enable Touch Gestures 터치 제스처 사용 Switch Selection and Drawing Modes 선택 모드와 그리기 모드 전환 + Select Last Selection Tool 마지막으로 사용한 선택 도구로 전환 Enable Touch Workspace 터치 작업 영역 사용 Enable copying of text, images and other content 텍스트, 이미지 및 기타 콘텐츠 복사 허용 Enable in-menu font previews 메뉴에서 글꼴 미리 보기 사용 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b8ca33858f..6cd1fc2bd3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4051,6 +4051,7 @@ theme Appearance Vormgeving Enable Rubber Band for Rubberband inschakelen voor Enable Touch Gestures Touchgebaren inschakelen Switch Selection and Drawing Modes Wisselen tussen selectie- en tekenmodus + Select Last Selection Tool Laatst gebruikte selectiegereedschap kiezen Enable Touch Workspace Touch-werkruimte inschakelen English: UK Engels: VK Every (minutes) Elke (minuten) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index eb5afe87cc..665ad1c353 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3680,6 +3680,7 @@ theme Appearance Wygląd Enable Rubber Band for Włącz gumkę podglądu dla Enable Touch Gestures Włącz gesty dotykowe Switch Selection and Drawing Modes Przełącz tryby zaznaczania i rysowania + Select Last Selection Tool Wybierz ostatnie narzędzie zaznaczania Enable Touch Workspace Włącz dotykowy obszar roboczy English: UK Angielski: Wielka Brytania Every (minutes) Co (minuty) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 80615d6370..251d045df9 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -932,6 +932,7 @@ antiAlias Sharp Nítido Enable Rubber Band for Habilitar Elástico para Enable Touch Gestures Habilitar Gestos de Toque Switch Selection and Drawing Modes Alternar Modos de Seleção e Desenho + Select Last Selection Tool Selecionar Última Ferramenta de Seleção Enable Touch Workspace Habilitar Espaço de Trabalho de Toque Enable copying of text, images and other content Habilitar cópia de texto, imagens e outro conteúdo Enable in-menu font previews Habilitar visualizações de fonte no menu diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c830e69b37..97281ecfb0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1040,6 +1040,7 @@ font-technology Variable Вариативные Enable text access for screen readers Разрешить доступ к тексту для программ чтения с экрана Enable Touch Gestures Включить сенсорные жесты Switch Selection and Drawing Modes Переключить режимы выделения и рисования + Select Last Selection Tool Выбрать последний инструмент выделения Enable Touch Workspace Включить сенсорную рабочую среду Encoding Кодировка Encoding: Кодировка: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d4304b97bd..ade417d700 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1021,6 +1021,7 @@ font-technology Variable Variabla Enable text access for screen readers Ge skärmläsare åtkomst till text Enable Touch Gestures Aktivera pekgester Switch Selection and Drawing Modes Växla mellan markerings- och ritläge + Select Last Selection Tool Välj det senaste markeringsverktyget Enable Touch Workspace Aktivera arbetslayout för pekskärm Encoding Kodning Encoding: Kodning: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f5fc694ec2..afcab87b6e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1013,6 +1013,7 @@ font-technology Variable Değişken Enable text access for screen readers Ekran okuyucular için metin erişimini etkinleştirin Enable Touch Gestures Dokunma Hareketlerini Etkinleştir Switch Selection and Drawing Modes Seçim ve Çizim Modları Arasında Geçiş Yap + Select Last Selection Tool Son Kullanılan Seçim Aracını Seç Enable Touch Workspace Dokunmatik Çalışma Alanını Etkinleştir Encoding Kodlama Encoding: Kodlama: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5a36512db0..0bed28992d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1045,6 +1045,7 @@ font-technology Variable Варіативні Enable text access for screen readers Дозволити доступ до тексту для програм читання з екрану Enable Touch Gestures Увімкнути сенсорні жести Switch Selection and Drawing Modes Перемкнути режими виділення та малювання + Select Last Selection Tool Вибрати останній інструмент виділення Enable Touch Workspace Включити сенсорне робоче середовище Encoding Кодування Encoding: Кодування: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 839f5c7405..1a9c3a431d 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1212,6 +1212,7 @@ font-technology Variable Biến thiên Enable text access for screen readers Bật truy cập văn bản cho trình đọc màn hình Enable Touch Gestures Bật cử chỉ cảm ứng Switch Selection and Drawing Modes Chuyển giữa chế độ chọn và vẽ + Select Last Selection Tool Chọn công cụ chọn dùng gần nhất Enable Touch Workspace Bật không gian làm việc cảm ứng Encoding Mã hóa Encoding: Mã hóa: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b0d6001e32..f5622cf162 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -983,6 +983,7 @@ antiAlias Sharp 锐利 Enable text access for screen readers 启用屏幕阅读器的文字访问 Enable Touch Gestures 启用触控手势 Switch Selection and Drawing Modes 切换选择与绘图模式 + Select Last Selection Tool 切换到上次使用的选择工具 Enable Touch Workspace 启用触控工作区 Encoding 编码 Encoding: 编码: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c24ae37609..1e5abe580f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1013,6 +1013,7 @@ font-technology Variable 可變 Enable text access for screen readers 啟用螢幕閱讀器的文字存取 Enable Touch Gestures 啟用觸控手勢 Switch Selection and Drawing Modes 切換選取與繪圖模式 + Select Last Selection Tool 切換到上次使用的選取工具 Enable Touch Workspace 啟用觸控工作區 Encoding 編碼 Encoding: 編碼: diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index d32ae53d5d..79e53edfdd 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -216,7 +216,7 @@ fn catalogue(snapshot: &Snapshot, p: Platform) -> Vec { if TOGGLES.contains(&e.key.as_str()) { b = b.toggle(); } - if let Some(d) = shortcut_editor::default_of(&e.key).and_then(vc_binding) { + if let Some(d) = shortcut_editor::default_on(&e.key, p).and_then(vc_binding) { b = b.with_default(d); } for alias in default_aliases(&e.key, p) { @@ -639,6 +639,26 @@ mod tests { } } + /// Select Last Selection Tool is Ctrl+` on Windows and Linux. macOS takes Cmd+` to switch + /// between an app's windows, so there the command has no default and takes a chord the user + /// assigns. + #[test] + fn last_selection_tool_default_follows_the_platform() { + let snapshot = shortcut_editor::snapshot(); + let command = command_of("tool.selectLastSelection"); + let chord = vc_chord("Cmd+~").unwrap(); + for p in [Platform::Windows, Platform::Linux] { + let km = keymap_for(p, &snapshot); + assert_eq!(lookup(&km, &chord), Some(command.clone()), "{p:?}"); + assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", p), Some("Cmd+~"), "{p:?}"); + } + let mut mac = keymap_for(Platform::Mac, &snapshot); + assert_eq!(mac.bindings(&command), vec![], "no default on macOS"); + assert_eq!(shortcut_editor::default_on("tool.selectLastSelection", Platform::Mac), None); + shortcut_editor::assign_in(&mut mac, "tool.selectLastSelection", Some("Alt+~"), true).unwrap(); + assert_eq!(lookup(&mac, &vc_chord("Alt+~").unwrap()), Some(command)); + } + #[test] fn panel_entries_bridge_to_window_panel() { let c = command_of("panel:layers"); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index efa4e95ac4..32af53ba16 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -677,13 +677,15 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::chrome::step_document(app, true), "window.previousDocument" => crate::chrome::step_document(app, false), "tool.select" => match s("tool") { - Some(t) if vectorcraft_tools::tool_info(&t).is_some() => { - app.select_tool(&t); - Ok(json!({"tool": app.session.tool_id()})) - } + Some(t) if vectorcraft_tools::tool_info(&t).is_some() => app.try_select_tool(&t).map(|()| json!({"tool": app.session.tool_id()})), Some(t) => Err(format!("unknown tool `{t}`")), None => Err("missing `tool`".into()), }, + "tool.selectLastSelection" => { + let id = app.session.last_selection_tool(); + let switched = if app.session.tool_id() == id { Ok(()) } else { app.try_select_tool(id) }; + switched.map(|()| json!({"tool": app.session.tool_id()})) + } crate::touch::TOGGLE_MODE => Ok(crate::touch::toggle_mode(app)), crate::addons::pathtools::corner::COMMAND => crate::addons::pathtools::corner::open(app), crate::addons::pathtools::shared_edge::COMMAND => crate::addons::pathtools::shared_edge::open(app), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 31340a3a48..65441f3c2a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -772,6 +772,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", ), ("tool.select", "Select Tool", "", "{tool: id} (see tools)"), + ( + "tool.selectLastSelection", + "Select Last Selection Tool", + "Cmd+~", + "{} choose the selection tool chosen last (Selection, Direct Selection or Group Selection; none yet: the Selection tool), keeping the active tool when it is that tool; choosing Magic Wand, Lasso or any other tool does not change which one it chooses → {tool}. Default shortcut Ctrl+` on Windows and Linux, none on macOS, where Cmd+` switches windows", + ), ( "tool.setOption", "Tool Option", diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 4e02180017..027893f0ab 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -152,12 +152,23 @@ pub fn sync(ui: &UiState) { crate::custom_toolbars::sync(ui); } -/// Registry default shortcut of a command (engine or UI command). +/// Registry default shortcut of a command (engine or UI command) on [`crate::keymap::platform`]. pub fn default_command_shortcut(id: &str) -> Option<&'static str> { + default_command_shortcut_on(id, crate::keymap::platform()) +} + +/// Registry default shortcut of a command on platform `p`. +fn default_command_shortcut_on(id: &str, p: craft_keymap::Platform) -> Option<&'static str> { if let Some(c) = vectorcraft_engine::find_command(id) { return c.shortcut; } - menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.2).filter(|s| !s.is_empty()) + menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| ui_command_default(c.0, c.2, p)).filter(|s| !s.is_empty()) +} + +/// The default shortcut `sc` of UI command `id` on platform `p` (empty for none). Select Last +/// Selection Tool has none on macOS, which takes Cmd+` to switch between an app's windows. +pub(crate) fn ui_command_default(id: &str, sc: &'static str, p: craft_keymap::Platform) -> &'static str { + if id == "tool.selectLastSelection" && p.is_mac() { "" } else { sc } } /// Window menu items that show a panel (`window.panel {panel}`) with a default shortcut: (panel @@ -184,15 +195,21 @@ pub const PANEL_SHORTCUTS: &[(&str, &str)] = &[ ("openType", "Cmd+Alt+Shift+T"), ]; -/// Default shortcut of an entry key (`tool:`, `panel:` or a command id). +/// Default shortcut of an entry key (`tool:`, `panel:` or a command id) on +/// [`crate::keymap::platform`]. pub fn default_of(key: &str) -> Option<&'static str> { + default_on(key, crate::keymap::platform()) +} + +/// Default shortcut of an entry key on platform `p`. +pub(crate) fn default_on(key: &str, p: craft_keymap::Platform) -> Option<&'static str> { if let Some(t) = key.strip_prefix("tool:") { return vectorcraft_tools::tool_info(t).and_then(|t| t.shortcut); } - if let Some(p) = key.strip_prefix("panel:") { - return PANEL_SHORTCUTS.iter().find(|(id, _)| *id == p).map(|(_, sc)| *sc); + if let Some(panel) = key.strip_prefix("panel:") { + return PANEL_SHORTCUTS.iter().find(|(id, _)| *id == panel).map(|(_, sc)| *sc); } - default_command_shortcut(key) + default_command_shortcut_on(key, p) } /// Effective shortcut of an entry key, honouring the user's overrides. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 60b8c5eacd..b07039e1db 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -3096,3 +3096,27 @@ fn artboard_navigation_commands_can_be_given_keys() { frame(&mut app, press(Key::PageUp)); assert_eq!(at(&app), 1, "Page Up goes to the previous artboard"); } + +/// Ctrl+` (Windows and Linux) chooses the selection tool chosen last; macOS gives the command no +/// default key. Edit › Keyboard Shortcuts lists it, and a chord the user assigns runs it. +#[test] +fn ctrl_backtick_chooses_the_last_selection_tool() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let mac = crate::keymap::platform().is_mac(); + let list = app.run("shortcuts.list", json!({ "query": "tool.selectLastSelection" })).unwrap(); + let listed = list.as_array().unwrap().iter().find(|e| e["id"] == "tool.selectLastSelection").cloned(); + let listed = listed.unwrap_or_else(|| panic!("listed: {list}")); + assert_eq!(listed["label"], "Select Last Selection Tool"); + assert_eq!(listed["default"], if mac { json!(null) } else { json!("Cmd+~") }); + app.select_tool("directSelection"); + app.select_tool("pen"); + frame(&mut app, press(Key::Backtick, cmd())); + assert_eq!(app.session.tool_id(), if mac { "pen" } else { "directSelection" }); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "tool.selectLastSelection", "Alt+~"); + app.select_tool("groupSelection"); + app.select_tool("rectangle"); + frame(&mut app, press(Key::Backtick, Modifiers::ALT)); + assert_eq!(app.session.tool_id(), "groupSelection", "the user's chord"); + crate::shortcut_editor::sync(&crate::state::UiState::default()); +} diff --git a/docs/mcp.md b/docs/mcp.md index 59bb3c78ad..e02cb5451d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1392,7 +1392,8 @@ vectorcraft-cli run --cmd file.new --params '{"width":800,"height":600}' \ `run` prints one JSON line per step (`open`, `cmd`, `export`) and exits non-zero on the first failure, naming the step (counting from 0, as `"$N"` references do) and its command. `--params` applies to the `--cmd` just before it. `run` -also accepts the host commands `file.open`, `file.save`, `file.export`, `file.exportForScreens` and `tool.select`. +also accepts the host commands `file.open`, `file.save`, `file.export`, `file.exportForScreens`, `tool.select` and +`tool.selectLastSelection`. `run --in`, `convert` and `info` read every format `document.open` reads (`vectorcraft-cli --help` lists them). ### Steps from a file or standard input @@ -4967,6 +4968,15 @@ macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool` Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing the path it had begun while that stays selected. Its reply's `tool` is the tool given back. +`tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on +Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the +shortcut among those for selections). Only Selection, Direct Selection and Group Selection count: choosing Magic Wand, +Lasso or any other tool leaves the remembered one as it was. Before any of the three is chosen it chooses the Selection +tool; with the remembered tool already active it keeps it, so running it again does not cycle. It returns `{tool}` and +adds no undo step. On macOS it has no default shortcut, because the system uses Command+` to switch between an app's +windows; Edit › Keyboard Shortcuts can assign one. The Selection tool as the first choice and the macOS default are +VectorCraft's own rules. The headless backend and `vectorcraft-cli run` run it too. + ```json {"name":"pointer_gesture","arguments":{"tool":"pen","events":[{"kind":"down","x":100,"y":300},{"kind":"up","x":100,"y":300},{"kind":"down","x":200,"y":300},{"kind":"drag","x":250,"y":300},{"kind":"up","x":250,"y":300}]}} {"name":"pointer_gesture","arguments":{"mods":{"cmd":true},"events":[{"kind":"down","x":250,"y":300},{"kind":"drag","x":250,"y":260},{"kind":"up","x":250,"y":260}]}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7044797d5e..721e6aa41e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -973,6 +973,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+Alt+N (`file.newWithoutDialog`) makes a document without opening the New Document dialog, 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 assigns to creating a document directly. The page does not say which settings the document gets. VectorCraft gives it the settings the dialog opens on (the first Recent entry, or the Print category's Letter while Recent is empty) and the next untitled name. - 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. + - Ctrl+` (`tool.selectLastSelection`, Select Last Selection Tool) on Windows and Linux chooses the selection tool chosen last of Selection, Direct Selection and Group Selection, on the key [the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists for switching to the last-used selection tool; Magic Wand and Lasso do not count. Before one is chosen it chooses the Selection tool, and it keeps the remembered tool when that tool is already active. On macOS it has no default shortcut, because the system uses Command+` to switch between an app's windows; Edit › Keyboard Shortcuts can assign one. The first choice and the macOS default are VectorCraft's own rules. - 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`. - 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. From dbfffc8ecb155e7f95ae9bcee3d88d6555c66796 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:09:27 -0800 Subject: [PATCH 009/138] Scripts: commands read through the gate in runs the person starts, and the grants file is not written over when it cannot be read - A command a script runs reads only where the script may, also in a run the person started; only reads of the app's own folders inside the command are exempt. - Always and script.grants.revoke leave a grants file they cannot read as it is, and fail. - script.grants names a path outside the automation read roots by its file name alone. - copy reads the source once, within the 8 MiB limit, writes those bytes, and gives the copy the source's permissions. - write joins its values as UTF-16 before making them text, so a surrogate pair split between two values is one character. --- crates/engine/src/cmd/scripts.rs | 12 ++++- crates/engine/src/file_access.rs | 45 ++++++++++++----- crates/engine/src/script/files.rs | 68 +++++++++++++++++++------- crates/engine/src/tests/script_io.rs | 62 +++++++++++++++++++++++ crates/engine/src/tests/script_run.rs | 6 ++- crates/js/src/file_classes.rs | 12 +++-- crates/ui-egui/src/tests/script_run.rs | 14 +++++- docs/mcp.md | 10 ++-- 8 files changed, 186 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 623ab8a87f..a620d398c8 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -341,7 +341,17 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { fn grants(s: &mut Session, _: &Value) -> Result { let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; let file = dir.with_file_name(script::files::GRANTS_FILE); - Ok(json!({"grants": script::files::stored_grants(dir), "file": file.to_string_lossy()})) + // A script or a granted path outside the automation read roots is named by its file name alone. + let mut grants = script::files::stored_grants(dir); + for g in &mut grants { + for key in ["script", "path"] { + if let Some(name) = g[key].as_str().and_then(hidden_name) { + g[key] = json!(name); + } + } + } + let file = file.to_string_lossy(); + Ok(json!({"grants": grants, "file": super::fileio::shown_path(&file)})) } fn grants_revoke(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 9aaeb58dab..8979914d43 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -176,7 +176,7 @@ fn with_scope(scope: Option, f: impl FnOnce() -> T) -> T { /// Run `f` with `roots` in force on this thread (`None`: as things stand). pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) -> T { match roots { - Some(r) => with_scope(Some(Scope::Confined(r.clone())), f), + Some(r) => with_gate_reads_exempt(false, || with_scope(Some(Scope::Confined(r.clone())), f)), None => f(), } } @@ -184,24 +184,44 @@ pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) - /// Run `f` with no roots in force on this thread: what the person at the keyboard does, and the /// app's own folders. pub fn unconfined(f: impl FnOnce() -> T) -> T { - with_scope(Some(Scope::Unconfined), f) + with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) +} + +thread_local! { + /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an + /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Puts the exemption it replaced back when dropped (also when `f` panics). +struct RestoreExempt(bool); + +impl Drop for RestoreExempt { + fn drop(&mut self) { + GATE_READS_EXEMPT.with(|e| e.set(self.0)); + } +} + +fn with_gate_reads_exempt(exempt: bool, f: impl FnOnce() -> T) -> T { + let _restore = RestoreExempt(GATE_READS_EXEMPT.with(|e| e.replace(exempt))); + f() } /// This thread's scope, with the gate of the script command it runs, to carry to work it hands to /// another thread ([`ScopeHandle::run`]). #[derive(Clone, Debug)] -pub struct ScopeHandle(Option, Option>); +pub struct ScopeHandle(Option, Option>, bool); impl ScopeHandle { /// The scope of the calling thread. pub fn capture() -> Self { - Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone())) + Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { - let Self(scope, gate) = self; - with_gate(gate, || with_scope(scope, f)) + let Self(scope, gate, exempt) = self; + with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f))) } } @@ -252,17 +272,18 @@ fn with_gate(gate: Option>, f: impl FnOnce() -> T) -> T { } /// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or -/// writes must pass the gate as well as the automation roots. Reads of the app's own folders, -/// inside [`unconfined`], are not checked; writes there are, so a script's command does not save -/// into the app's libraries. +/// writes must pass the gate as well as the automation roots, also when the run itself is +/// [`unconfined`] (one the person started). Reads of the app's own folders, inside an +/// [`unconfined`] the command enters, are not checked; writes there are, so a script's command +/// does not save into the app's libraries. pub(crate) fn with_script_gate(gate: ScriptGate, f: impl FnOnce() -> T) -> T { - with_gate(Some(Arc::new(gate)), f) + with_gate(Some(Arc::new(gate)), || with_gate_reads_exempt(false, f)) } /// May `path` be read (or written) by the script command this thread runs? Always outside one, -/// and for a read inside [`unconfined`]. +/// and for a read inside an [`unconfined`] the command entered. fn check_gate(path: &str, access: Access) -> Result<(), String> { - if matches!(access, Access::Read) && SCOPE.with(|s| matches!(*s.borrow(), Some(Scope::Unconfined))) { + if matches!(access, Access::Read) && GATE_READS_EXEMPT.with(std::cell::Cell::get) { return Ok(()); } GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 258d5a2863..ddc574ee71 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -431,7 +431,7 @@ impl Disk { } let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); - let mut grants = read_store(&store); + let Ok(mut grants) = try_read_store(&store) else { return }; for g in &mut grants { let ours = g["script"] == *script && g["sha256"] == *hash @@ -565,7 +565,8 @@ impl Disk { /// takes its place. fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; - let mut grants = read_store(&store); + // A grants file that is there but cannot be read is left as it is. + let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); for p in paths { @@ -880,15 +881,34 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { Ok(bytes) } -/// The grants the grants file at `store` holds; none when it is missing or cannot be read. +/// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant +/// that is not well formed is left out. fn read_store(store: &Path) -> Vec { - let Ok(bytes) = read_head(store, MAX_STORE_BYTES) else { return Vec::new() }; + load_store(store, false).unwrap_or_default() +} + +/// The grants the grants file at `store` holds, to change and write back; none when it is missing, +/// and `Err` when it is there but cannot be read, is too large, is not a grants file of this +/// version, or holds a grant that is not well formed or more grants than may be kept, so that a +/// change is not written over it. +fn try_read_store(store: &Path) -> std::io::Result> { + load_store(store, true) +} + +/// The grants file at `store` read as [`read_store`] reads it, or with `strict` as +/// [`try_read_store`] does. +fn load_store(store: &Path, strict: bool) -> std::io::Result> { + let bytes = match read_head(store, MAX_STORE_BYTES) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(e), + }; if bytes.len() > MAX_STORE_BYTES { - return Vec::new(); + return Err(std::io::Error::other("the grants file is too large")); } - let Ok(v) = serde_json::from_slice::(&bytes) else { return Vec::new() }; + let v = serde_json::from_slice::(&bytes).map_err(std::io::Error::other)?; if v["version"] != 1 { - return Vec::new(); + return Err(std::io::Error::other("the grants file has another version")); } let valid = |g: &serde_json::Value| { g["script"].is_string() @@ -898,7 +918,14 @@ fn read_store(store: &Path) -> Vec { && g["write"].is_boolean() && g["folder"].is_boolean() }; - v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default() + if strict { + let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?; + if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) { + return Err(std::io::Error::other("the grants file holds a grant that cannot be read")); + } + return Ok(grants.clone()); + } + Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default()) } /// Writes `grants` as the grants file at `store`: to a file beside it, which then takes its place. @@ -930,7 +957,7 @@ pub(crate) fn stored_grants(data_dir: &Path) -> Vec { /// → how many were removed. pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); - let grants = read_store(&store); + let grants = try_read_store(&store)?; let before = grants.len(); let kept: Vec = grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); @@ -1636,28 +1663,33 @@ fn copy(host: &Host, a: &[Data]) -> Result { if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { return Ok(error(m)); } - let n = std::fs::metadata(&source).map_or(0, |m| m.len()); - if n > MAX_FILE_BYTES as u64 { - return Ok(error(TOO_LARGE)); - } + // The bytes are read once, no more than the limit, and those bytes are what is charged and + // written: a source that grows after it is read does not copy more. + let copied = match read_head(&source, MAX_FILE_BYTES) { + Ok(bytes) if bytes.len() > MAX_FILE_BYTES => return Ok(error(TOO_LARGE)), + Ok(bytes) => bytes, + Err(_) => return Ok(error(READ_FAILED)), + }; // The target's open objects each take a copy of the bytes, which count as written too, as does // the copy itself when it is written. let holders = disk.open.values().filter(|o| o.target.as_deref() == Some(target.as_path())).count(); - disk.charge_write(usize::try_from(n).unwrap_or(usize::MAX).saturating_mul(holders.saturating_add(usize::from(!itself))))?; - let r = if itself { Ok(n) } else { std::fs::copy(&source, &target) }; + disk.charge_write(copied.len().saturating_mul(holders.saturating_add(usize::from(!itself))))?; + // The copy takes the source's permissions, as `std::fs::copy` gives them. + let permissions = std::fs::metadata(&source).map(|m| m.permissions()); + let r = + if itself { Ok(()) } else { std::fs::write(&target, &copied).and_then(|()| permissions.and_then(|p| std::fs::set_permissions(&target, p))) }; if !itself && (r.is_ok() || target.exists()) { disk.wrote(&target); } // Open objects of the target hold the copy, so closing them does not write their older bytes. - if r.is_ok() && disk.open.values().any(|o| o.target.as_deref() == Some(target.as_path())) { - let copied = read_head(&target, MAX_FILE_BYTES).unwrap_or_default(); + if r.is_ok() { for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { file.bytes.clone_from(&copied); file.pos = file.pos.min(copied.len()); file.dirty = false; } } - Ok(done(r.map(drop).map_err(|_| WRITE_FAILED))) + Ok(done(r.map_err(|_| WRITE_FAILED))) } /// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e3e7ade3a2..b9bb6a2162 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -730,6 +730,34 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// `copy` gives the copy the source's permissions: the copy of a read-only file is read-only. +#[test] +fn script_file_copy_keeps_the_source_read_only() { + let base = folder("copyreadonly"); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('x'); s.close(); s.readonly = true;\n\ + var out = [s.copy(d + '/t.txt'), new File(d + '/t.txt').readonly, new File(d + '/t.txt').length];\n\ + s.readonly = false; new File(d + '/t.txt').readonly = false; vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, 1]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `write` with several values joins them before making them text, so a surrogate pair split +/// between two values is written as one character. +#[test] +fn script_file_write_joins_a_surrogate_pair_split_between_values() { + let base = folder("surrogates"); + let r = run( + &base, + "var f = new File(Folder.temp.fsName + '/s.txt'); f.encoding = 'UTF-8'; f.open('w'); f.write('\\uD83D', '\\uDE00'); f.close();\n\ + f.open('r'); var t = f.read(); f.close(); vc.log([t === '\\uD83D\\uDE00', t.length]);", + ); + assert_eq!(r["log"], json!([[true, 2]])); + let _ = std::fs::remove_dir_all(base); +} + /// A grant that would make the grants file larger than it may be read is not kept, and the grants /// file keeps the grants it had. #[test] @@ -754,6 +782,34 @@ fn script_file_grants_file_stays_within_its_size_limit() { let _ = std::fs::remove_dir_all(base); } +/// A grants file that is there but cannot be read (another version, not JSON, a grant that is not +/// well formed, or no list of grants) is not written over: a grant picked with Always is not kept, and a revoke fails, so the grants it holds stay. +#[test] +fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() { + let cases = [ + ("newer", br#"{"version": 2, "grants": [{"script": "x"}]}"#.as_slice()), + ("broken", b"{ not json".as_slice()), + ("malformed", br#"{"version": 1, "grants": [{"script": "x"}]}"#.as_slice()), + ("nolist", br#"{"version": 1, "grants": {}}"#.as_slice()), + ]; + for (name, held) in cases { + let base = folder(&format!("store-{name}")); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let store = base.join("settings/Script Grants.json"); + write(&store, held); + let mut s = with_data(&base); + start_framed(&mut s, &base, "var f = File.saveDialog('p'); vc.log(f === null ? null : f.fsName);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let _ = pump_to_picker(&mut s).unwrap(); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + assert!(s.execute("script.grants.revoke", &json!({"all": true})).is_err(), "{name}"); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: a revoke leaves it too"); + let _ = std::fs::remove_dir_all(base); + } +} + /// `copy` of a file over 8 MiB is refused, as opening one is. #[test] fn script_file_copy_is_held_to_the_file_limit() { @@ -1387,6 +1443,12 @@ fn script_file_dialog_grants_are_kept_for_the_same_script_text() { let grants = s.execute("script.grants", &json!({})).unwrap(); assert_eq!(grants["grants"].as_array().unwrap().len(), 1, "{grants}"); assert_eq!(grants["grants"][0]["write"], true); + // Under automation read roots, a path outside them is named by its file name alone. + let roots = AutomationRoots::new(&[&base.join("main")], &[]).unwrap(); + let hidden = confine(roots.as_ref(), || s.execute("script.grants", &json!({}))).unwrap(); + assert_eq!(hidden["grants"][0]["path"], "out.txt", "{hidden}"); + assert_eq!(hidden["grants"][0]["script"], grants["grants"][0]["script"], "the script inside the roots is named whole: {hidden}"); + assert_eq!(hidden["file"], "Script Grants.json", "{hidden}"); start_framed(&mut s, &base, &text); let r = pump_to_picker(&mut s).unwrap().unwrap(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0a4037a0d8..ab8345e6cb 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -316,7 +316,8 @@ fn an_export_that_fails_names_no_file() { } /// The commands a script runs read and write only where its `File` and `Folder` objects may (its -/// temporary folder and what a person allowed it, here), and the files of the open documents. +/// temporary folder and what a person allowed it, here), and the files of the open documents, +/// also in a run the person started. #[test] fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let dir = fresh_folder("gate"); @@ -354,6 +355,9 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let r = run(&mut s, &source).unwrap(); assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}"); assert!(!outside.join("other.svg").exists()); + let source = format!("{}{}", call("document.open", &own), call("document.open", &outside.join("copy.svg"))); + let r = crate::file_access::unconfined(|| run(&mut s, &source)).unwrap(); + assert_eq!(r["log"], json!(["ok", "denied"]), "a run the person starts reads through the gate as well: {r}"); std::fs::remove_file(&own).unwrap(); let r = run(&mut s, &call("document.save", &own)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f6d87de964..0d8d997a91 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -542,19 +542,21 @@ fn write_values(i: &mut Interp, this: &Value, args: &[Value], what: &str, line: Value::Number(n) if n.is_finite() && n >= 0.0 => (n as usize).saturating_mul(2), _ => usize::MAX, }; - let mut text = String::new(); - let mut units = 0usize; + // The values are joined as UTF-16 code units and made text once, so a surrogate pair split + // between two values is one character. + let mut joined: Vec = Vec::new(); for a in args { i.use_fuel()?; let s = i.to_str(a)?; - units = units.saturating_add(s.len()); - if units > max { + if joined.len().saturating_add(s.len()) > max { let m = message(i, "tooLarge")?; set_slot(i, o, ERROR, m)?; return Ok(Value::Bool(false)); } - text.push_str(&s.to_rust_string()); + joined.extend_from_slice(&s.flat()); } + let mut text = String::from_utf16_lossy(&joined); + drop(joined); if line { text.push_str(line_end(i, o)?); } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index ba6553e068..202ac35c6f 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -553,10 +553,18 @@ fn enter_in_a_scripts_file_dialog_denies() { assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); } -/// Enter on the file dialog's focused Choose… button goes to that button and does not deny. +/// Enter on the file dialog's focused Choose… button goes to that button, which opens the folder +/// picker once, and does not deny. #[test] fn enter_on_a_focused_choose_button_does_not_deny() { - let mut app = app(); + let asked = std::rc::Rc::new(std::cell::Cell::new(0usize)); + let counted = asked.clone(); + let pick_folder: Box Option> = Box::new(move || { + counted.set(counted.get() + 1); + None + }); + let mut app = VectorcraftApp::new(Session::new(), crate::Services { pick_folder: Some(pick_folder), ..Default::default() }); + app.run("file.new", json!({})).unwrap(); app.session.prefs.show_external_script_warning = false; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(Folder.selectDialog('Pick'));" })).unwrap().unwrap(); script_runs::poll(&mut app); @@ -571,8 +579,10 @@ fn enter_on_a_focused_choose_button_does_not_deny() { frame(&mut app, events); } assert!(ctx.memory(|m| m.focused().is_some()), "Tab gives a button the keyboard focus"); + assert_eq!(asked.get(), 0); frame(&mut app, vec![key(egui::Key::Enter)]); frame(&mut app, vec![]); + assert_eq!(asked.get(), 1, "Enter chose the focused Choose… button"); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND), "the dialog stays open"); assert!(app.session.script_picker().is_some(), "the run still waits"); dialogs::cancel(&mut app); diff --git a/docs/mcp.md b/docs/mcp.md index 481961c67f..8fefe75b07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2263,7 +2263,7 @@ The help page's writing members work as it describes - `open('w')` empties the file, or makes it, `open('e')` opens a file that is there, and `open('a')` opens it at its end. `write(...values)` writes the values as `String(value)` gives them, and `writeln(...values)` adds the line end `lineFeed` names: CR LF for `Windows`, CR for `Macintosh` and LF for `Unix`. A byte order mark is written only - when the script writes ``. + when the script writes `\uFEFF`. - `copy(target)` copies the file to a path or a `File` and replaces a file that is there. `remove()` deletes a file, or a folder only when it is empty (`Script folder is not empty`), at once and without the trash. `rename(name)` takes a name without a folder; a name that is in use gives `Script file name is already in use`, and the object @@ -2345,10 +2345,12 @@ VectorCraft writes files by these rules of its own: the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later takes its place), and `file` the grants -file's path, or `null` without a settings folder. `script.grants.revoke {script?, path?, all?}` removes the grants of +file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them +is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. While a script -runs it is refused with the busy error, as the run keeps the grants it started with. A script cannot run either -command. +runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but +cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script +cannot run either command. ```json {"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} From b153a3d7a673fab8f0baf2f294917a2004e1a1fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:31:59 -0800 Subject: [PATCH 010/138] Scripts: a file whose close could not write it stays open, so a later close tries again --- crates/engine/src/tests/script_io.rs | 15 +++++++++++++++ crates/js/src/file_classes.rs | 7 +++++-- docs/mcp.md | 3 ++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index b9bb6a2162..4fae8d33b8 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -730,6 +730,21 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// A file whose `close` could not write it stays open, so a later `close` writes it. +#[test] +fn script_file_close_that_fails_can_be_tried_again() { + let base = folder("closeagain"); + let r = run( + &base, + "var d = Folder.temp.fsName, f = new File(d + '/f.txt'); f.open('w'); f.write('kept');\n\ + new File(f.fsName).readonly = true; var out = [f.close(), f.error];\n\ + new File(f.fsName).readonly = false; out.push(f.close());\n\ + var g = new File(f.fsName); g.open('r'); out.push(g.read()); g.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file could not be written", true, "kept"]])); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` gives the copy the source's permissions: the copy of a read-only file is read-only. #[test] fn script_file_copy_keeps_the_source_read_only() { diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 0d8d997a91..7ebcc7bfae 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -220,14 +220,17 @@ fn is_open(i: &Interp, o: ObjId) -> JsResult> { } /// Closes the object's open file, if it has one, which writes what the script wrote to it. → false -/// after setting `error` when that could not be written. +/// after setting `error` when that could not be written; the file then stays open, so a later +/// `close` tries again. fn close_open(i: &mut Interp, o: ObjId) -> JsResult { let mut written = true; if let Some(h) = is_open(i, o)? { let r = host(i, "close", &[h])?; written = outcome(i, o, &r)?; } - set_slot(i, o, HANDLE, Value::Number(-1.0))?; + if written { + set_slot(i, o, HANDLE, Value::Number(-1.0))?; + } Ok(written) } diff --git a/docs/mcp.md b/docs/mcp.md index 8fefe75b07..1b642340cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2300,7 +2300,8 @@ VectorCraft writes files by these rules of its own: `Script file access denied`. - What a script writes is written when it closes the file or when the run ends, also when the run fails. At the run's end the files left open are written in the order they were opened. A file - that `close` could not write is written again when the run ends, and a `write` that would pass the run's limit + that `close` could not write stays open, so a later `close` tries again, and is written again when the run ends; a + `write` that would pass the run's limit is not written. A run that would otherwise succeed fails when a changed file it left open cannot be written, with `Error: the script left open files that could not be written` and the files' paths. One file From 3ef3ed568a0d97ee6e3c3d0f31fe3c43659baa26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:55:29 -0800 Subject: [PATCH 011/138] Scripts: script.grants.revoke does not look up a path outside the automation read roots --- crates/engine/src/cmd/scripts.rs | 13 +++++++++---- crates/engine/src/tests/script_io.rs | 19 +++++++++++++++++-- docs/mcp.md | 3 ++- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index a620d398c8..3af4f351f1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed; refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -358,9 +358,14 @@ fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; let path_of = |key: &str| match p.get(key) { None => Ok(None), - Some(Value::String(t)) if !t.is_empty() => { - Ok(Some(std::fs::canonicalize(t).map_or_else(|_| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()))) - } + // A path the request may not read (outside the automation read roots, a network path among + // them) is compared as written, without looking it up. + Some(Value::String(t)) if !t.is_empty() => Ok(Some( + crate::file_access::check_read(t) + .ok() + .and_then(|()| std::fs::canonicalize(t).ok()) + .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), + )), Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 4fae8d33b8..39276d737f 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1492,8 +1492,23 @@ fn script_file_dialog_grants_are_kept_for_the_same_script_text() { assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); assert!(pump_to_picker(&mut s).is_some(), "the run ends"); - let removed = s.execute("script.grants.revoke", &json!({"path": out.to_string_lossy()})).unwrap(); - assert_eq!(removed["removed"], 1); + // Under automation read roots, a path outside them is not looked up: a link there to the + // granted file does not name it. + #[cfg(unix)] + { + let link = base.join("link.txt"); + std::os::unix::fs::symlink(&out, &link).unwrap(); + let roots = AutomationRoots::new(&[&base.join("main")], &[]).unwrap(); + let r = confine(roots.as_ref(), || s.execute("script.grants.revoke", &json!({"path": link.to_string_lossy()}))).unwrap(); + assert_eq!(r["removed"], 0, "{r}"); + let r = s.execute("script.grants.revoke", &json!({"path": link.to_string_lossy()})).unwrap(); + assert_eq!(r["removed"], 1, "without roots the link is followed: {r}"); + } + #[cfg(not(unix))] + { + let removed = s.execute("script.grants.revoke", &json!({"path": out.to_string_lossy()})).unwrap(); + assert_eq!(removed["removed"], 1); + } assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); assert!(s.execute("script.grants.revoke", &json!({})).is_err()); assert!(!base.join("settings/Script Grants.json.part").exists()); diff --git a/docs/mcp.md b/docs/mcp.md index 1b642340cb..2e8843ce07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2348,7 +2348,8 @@ grant, which covers everything in the folder (a file's grant covers its own path takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of -a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. While a script +a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is +matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script cannot run either command. From 0300f7095079cdfaa8dd4e49363bc0783e7ffc41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 14:45:05 -0800 Subject: [PATCH 012/138] Scripts: file and folder dialogs are native functions that pause the script File.openDialog, File.saveDialog, Folder.selectDialog and the openDlg, saveDlg and selectDlg methods are now built-ins written in Rust instead of JavaScript source compiled when File and Folder are installed. The interpreter gains a native function form that asks the host for a value: it gives the host call to make and a function that takes the answer. When the host waits, the run pauses at the call, and the answer goes to that function before the next instruction, so a filter function or an exception it throws runs at the dialog's call. Arguments, filters, multiSelect, the start folder and the null and error answers work as before. --- crates/js/src/builtins.rs | 11 +- crates/js/src/file_classes.rs | 297 ++++++++++++++++++++++++---------- crates/js/src/heap.rs | 4 +- crates/js/src/interp.rs | 83 ++++++++++ crates/js/src/realm.rs | 6 +- 5 files changed, 313 insertions(+), 88 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 92db4e6502..98327a2b61 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -38,6 +38,15 @@ pub(crate) fn native(interp: &mut Interp, name: &'static str, f: NativeFn, lengt Ok(o) } +/// A built-in function object that may wait for the host ([`crate::interp::Pause`]), defined as +/// `name` on `on` the way [`method`] defines one. +pub(crate) fn pausable_method(interp: &mut Interp, on: ObjId, name: &'static str, f: crate::interp::PausableFn, length: u32) -> JsResult<()> { + let proto = interp.intrinsics.function_proto; + let m = alloc(interp, Class::Function(Func::Pausable { f, name }), Some(proto)); + interp.define(m, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) +} + pub(crate) fn method(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn, length: u32) -> JsResult<()> { let m = native(interp, name, f, length, NativeKind::Plain, false)?; interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) @@ -514,7 +523,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); return Ok(Value::String(Str::from_units(units.to_vec()))); } - Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"), + Some(Func::Native { name, .. } | Func::Pausable { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Bound { .. }) => "function () { [native code] }".to_string(), None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")), diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 7ebcc7bfae..f1bba51291 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -14,8 +14,8 @@ //! //! `write` and `writeln` join their values as `String(value)` gives them, and `writeln` adds the //! line end `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF otherwise. The file -//! dialogs are functions of script code that call the host's `pick`, so that a run can wait there -//! for the person's answer; they give a `File`, a `Folder`, an array of `File`s or `null`. +//! dialogs are built-ins that ask the host's `pick` and may pause the run until the person answers +//! ([`crate::interp::Pause`]); they give a `File`, a `Folder`, an array of `File`s or `null`. //! //! A method whose host call fails sets `error` and returns `false`, `null` or an empty string. A //! count or position that is not a finite number, a negative count and a seek mode other than 0, 1 @@ -24,11 +24,10 @@ //! true value for; every entry takes fuel. use crate::HostItem; -use crate::builtins::{arg, constructor, data, method, native, put_at}; -use crate::bytecode::CodeKind; +use crate::builtins::{arg, constructor, data, method, native, pausable_method, put_at}; use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; -use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; -use crate::value::Value; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::value::{Value, index_key}; /// The objects of `File` and `Folder`, kept by the realm, and `Folder.current`. #[derive(Clone, Debug)] @@ -579,69 +578,79 @@ fn writeln(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { - let kind = arg(args, 0); - let start = match arg(args, 1) { - Value::Null => Value::str(""), - s => this_path(i, &s, "dialog")?.1, +/// Asks the host's `pick` for the dialog `kind` (`open`, `save` or `folder`), with the arguments +/// `[kind, prompt, multi, start, types]`. `me` is the `File` or `Folder` whose `openDlg`, `saveDlg` +/// or `selectDlg` was called, or `None` for the class's own dialog: the dialog starts at its path, +/// and an `{error}` answer sets its `error`. The prompt is `String(prompt)`, or `""` for +/// `undefined` and `null`. A `filter` that is a string gives the file types; one that is a function +/// is called with each file picked ([`picked`]). The run may pause at `pick` until the person +/// answers. +fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Value, multi: bool, filter: &Value) -> JsResult { + let start = match me { + None => Value::str(""), + Some(me) => this_path(i, me, "dialog")?.1, }; - let prompt = match arg(args, 2) { + let prompt = match prompt { Value::Undefined | Value::Null => Value::str(""), - p => Value::String(i.to_str(&p)?), + p => Value::String(i.to_str(p)?), }; - let multi = Value::Bool(arg(args, 3).truthy()); - let filter = match arg(args, 4) { - f @ Value::String(_) => f, + let types = match filter { + f @ Value::String(_) => f.clone(), _ => Value::str(""), }; - i.rooted(&[kind.clone(), start.clone(), prompt.clone(), filter.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES)?; - let proto = i.intrinsics.array_proto; - let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto))); + let pick = host_value(i, "pick")?; + Ok(Pause { + host: pick, + args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types], + keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()], + resume: picked, + }) +} + +/// What a file dialog gives for `pick`'s `answer`, with `[folder, me, filter]` kept from +/// [`ask_pick`]: the objects [`wrap`] makes, of which a `filter` that is a function keeps the +/// files it gives a true value for, or `null` when it keeps none. +fn picked(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { + let files = wrap(i, arg(keep, 0).truthy(), &arg(keep, 1), answer)?; + let filter = arg(keep, 2); + if !i.is_callable(&filter) { + return Ok(files); + } + let Some(o) = files.as_object() else { return Ok(files) }; + let length = match &i.object(o)?.class { + Class::Array { length, .. } => Some(*length), + _ => None, + }; + let Some(length) = length else { + let kept = i.rooted(std::slice::from_ref(&files), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&files)))?; + return Ok(if kept.truthy() { files } else { Value::Null }); + }; + i.rooted(std::slice::from_ref(&files), |i| { + i.reserve_heap(OBJECT_BYTES)?; + let array_proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(array_proto))); i.rooted(&[Value::Object(out)], |i| { - for (at, v) in [kind.clone(), prompt.clone(), multi.clone(), start.clone(), filter.clone()].into_iter().enumerate() { - put_at(i, out, at as f64, v)?; + let mut n = 0.0; + for at in 0..length { + i.use_fuel()?; + let file = i.get_value(&files, &index_key(at))?; + let kept = i.rooted(std::slice::from_ref(&file), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&file)))?; + if kept.truthy() { + put_at(i, out, n, file)?; + n += 1.0; + } } - Ok(Value::Object(out)) + Ok(if n > 0.0 { Value::Object(out) } else { Value::Null }) }) }) } -/// `wrap(kind, self, answer)`: the `File` (a `Folder` for a folder dialog) for each path `pick` -/// gave, an array of them for a list, `null` for `null`, and `null` after setting `self`'s `error` -/// for `{error}`. -fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { +/// The `File` (a `Folder` for a `folder` dialog) for each path `pick` gave in `answer`, an array of +/// them for a list, `null` for `null`, and `null` after setting the `error` of `me`, when it is a +/// `File` or `Folder`, for `{error}`. +fn wrap(i: &mut Interp, folder: bool, me: &Value, answer: Value) -> JsResult { let c = classes(i)?; - let proto = if matches!(arg(args, 0), Value::String(s) if s.to_rust_string() == "folder") { c.folder_proto } else { c.file_proto }; - let answer = arg(args, 2); + let proto = if folder { c.folder_proto } else { c.file_proto }; match &answer { Value::String(_) => return instance(i, proto, answer.clone()), Value::Object(_) => {} @@ -649,7 +658,7 @@ fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { } let error = i.rooted(std::slice::from_ref(&answer), |i| field(i, &answer, "error"))?; if matches!(error, Value::String(_)) { - if let Some(o) = arg(args, 1).as_object() + if let Some(o) = me.as_object() && matches!(slot(i, o, PATH)?, Value::String(_)) { set_slot(i, o, ERROR, error)?; @@ -676,33 +685,44 @@ fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { }) } +/// `File.openDialog(prompt, filter, multiSelect)`. +fn open_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "open", None, &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1)) +} + +/// `File.saveDialog(prompt, filter)`. +fn save_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "save", None, &arg(args, 0), false, &arg(args, 1)) +} + +/// `File.prototype.openDlg(prompt, filter, multiSelect)`. +fn open_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "open", Some(&this), &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1)) +} + +/// `File.prototype.saveDlg(prompt, filter)`. +fn save_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "save", Some(&this), &arg(args, 0), false, &arg(args, 1)) +} + +/// `Folder.selectDialog(prompt)`. +fn select_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "folder", None, &arg(args, 0), false, &Value::Null) +} + +/// `Folder.prototype.selectDlg(prompt)`. +fn select_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "folder", Some(&this), &arg(args, 0), false, &Value::Null) +} + /// Defines the file dialogs on `File`, `Folder` and their prototypes. fn dialogs(i: &mut Interp, file: ObjId, file_proto: ObjId, folder: ObjId, folder_proto: ObjId) -> JsResult<()> { - let units = i.encode_source(DIALOGS).map_err(|e| i.compile_error_to_abrupt(e))?; - let code = i.compile_source(&units, false, CodeKind::Eval).map_err(|e| i.compile_error_to_abrupt(e))?; - let make = i.run_global(code, true)?; - let c = classes(i)?; - let pick = i.rooted(std::slice::from_ref(&make), |i| i.get_value(&Value::Object(c.host), &key("pick")))?; - let ask = native(i, "ask", ask, 5, NativeKind::Plain, false)?; - let made = i.rooted(&[make.clone(), pick.clone(), Value::Object(ask)], |i| { - let wrap = native(i, "wrap", wrap, 3, NativeKind::Plain, false)?; - i.call(&make, &Value::Undefined, &[Value::Object(ask), pick.clone(), Value::Object(wrap)]) - })?; - let on = [ - (file, "openDialog"), - (file, "saveDialog"), - (file_proto, "openDlg"), - (file_proto, "saveDlg"), - (folder, "selectDialog"), - (folder_proto, "selectDlg"), - ]; - i.rooted(std::slice::from_ref(&made), |i| { - for (at, (target, name)) in on.into_iter().enumerate() { - let f = i.get_value(&made, &crate::value::number_to_str(at as f64).flat())?; - data(i, target, name, f, HIDDEN)?; - } - Ok(()) - }) + pausable_method(i, file, "openDialog", open_dialog, 3)?; + pausable_method(i, file, "saveDialog", save_dialog, 2)?; + pausable_method(i, file_proto, "openDlg", open_dlg, 3)?; + pausable_method(i, file_proto, "saveDlg", save_dlg, 2)?; + pausable_method(i, folder, "selectDialog", select_dialog, 1)?; + pausable_method(i, folder_proto, "selectDlg", select_dlg, 1) } fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { @@ -1084,13 +1104,51 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul #[cfg(test)] mod tests { + use std::cell::RefCell; use std::rc::Rc; - use crate::{Data, HostItem, JsValue, Realm}; + use crate::{Data, HostError, HostItem, JsValue, Progress, Realm}; /// A host whose paths are `/` and a name, where `/d` is a folder holding `a` and `b` and every /// other path is missing. fn realm() -> Realm { + realm_with(|_| Vec::new()) + } + + /// [`realm`] with a `pick` that waits where it can and throws where it cannot. → the arguments + /// of each call, joined with `|`. + fn dialog_realm() -> (Realm, Rc>>) { + let asked: Rc>> = Rc::default(); + let calls = asked.clone(); + let r = realm_with(move |r| { + let can_wait = r.wait_flag(); + let pick = move |a: Vec| -> Result { + let text = |d: &Data| match d { + Data::String(s) => s.clone(), + Data::Bool(b) => b.to_string(), + other => format!("{other:?}"), + }; + calls.borrow_mut().push(a.iter().map(text).collect::>().join("|")); + if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) } + }; + vec![("pick".into(), HostItem::Function(Rc::new(pick)))] + }); + (r, asked) + } + + /// Advances the run until it waits or ends. → its value when it ended. + fn until_wait(r: &mut Realm) -> Option { + for _ in 0..10_000 { + match r.advance(1_000).unwrap() { + Progress::Done(v) => return Some(v), + Progress::Paused if r.waits() => return None, + Progress::Paused => {} + } + } + panic!("the run neither waited nor ended") + } + + fn realm_with(more: impl FnOnce(&Realm) -> Vec<(String, HostItem)>) -> Realm { let f = |g: fn(&[Data]) -> Data| HostItem::Function(Rc::new(move |a: Vec| Ok(g(&a)))); let text = |a: &[Data], i: usize| match a.get(i) { Some(Data::String(s)) => s.clone(), @@ -1120,7 +1178,7 @@ mod tests { Ok(obj(vec![("entries", Data::Array(vec![e("a"), e("b")]))])) }; let mut r = Realm::new(); - let items: Vec<(String, HostItem)> = vec![ + let mut items: Vec<(String, HostItem)> = vec![ ("text".into(), HostItem::Object(messages.to_vec())), ("system".into(), HostItem::Value(Data::String("Unix".into()))), ("lineFeed".into(), HostItem::Value(Data::String("Unix".into()))), @@ -1131,10 +1189,79 @@ mod tests { ("tempName".into(), f(|_| Data::String("/tmp1".into()))), ("locations".into(), f(|_| Data::Object(vec![]))), ]; + items.extend(more(&r)); r.define_file_classes(items).unwrap(); r } + #[test] + fn a_dialog_pauses_the_run_and_its_answer_becomes_files() { + let (mut r, asked) = dialog_realm(); + let v = r.run("[File.openDialog.length, File.prototype.saveDlg.length, String(Folder.selectDialog).indexOf('[native code]') > 0].join()"); + assert_eq!(v.unwrap(), JsValue::String("3,2,true".into()), "the dialogs are built-ins"); + r.start("var f = File.openDialog('Pick', 'Text:*.txt', 1); [f.length, f[0].name, f[1].fsName, f[1] instanceof File].join()").unwrap(); + assert_eq!(until_wait(&mut r), None); + assert_eq!(*asked.borrow(), ["open|Pick|true||Text:*.txt"]); + r.answer(Data::Array(vec![Data::String("/a".into()), Data::String("/b".into())])).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("2,a,/b,true".into()))); + r.start("var g = new Folder('d').selectDlg(5); [g.name, g instanceof Folder].join()").unwrap(); + assert_eq!(until_wait(&mut r), None); + assert_eq!(asked.borrow()[1], "folder|5|false|/d|", "the folder's own dialog starts at its path"); + r.answer(Data::String("/e".into())).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("e,true".into()))); + } + + #[test] + fn a_canceled_dialog_gives_null_and_an_error_answer_sets_error() { + let (mut r, asked) = dialog_realm(); + r.start( + "var d = new File('x'); var a = File.saveDialog(); var b = d.saveDlg('Save', function () { return true; }); [a, b, d.error].join('|')", + ) + .unwrap(); + assert_eq!(until_wait(&mut r), None); + r.answer(Data::Null).unwrap(); + assert_eq!(until_wait(&mut r), None, "a canceled dialog lets the run go on to the next one"); + assert_eq!(asked.borrow()[1], "save|Save|false|/x|", "a filter that is not a string gives no file types"); + r.answer(Data::Object(vec![("error".into(), Data::String("denied".into()))])).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("||denied".into()))); + r.start("File.openDialog(); 'went on'").unwrap(); + assert_eq!(until_wait(&mut r), None); + r.end(); + assert!(!r.waits() && !r.is_running(), "a run ended at a dialog drops it"); + assert_eq!(r.run("'next'").unwrap(), JsValue::String("next".into())); + let e = r.run("File.openDialog()").unwrap_err(); + assert!(e.message.contains("cannot wait here"), "a run that cannot pause does not wait: {e:?}"); + let e = r.run("File.prototype.openDlg.call({})").unwrap_err(); + assert!(e.message.contains("is not a File or a Folder"), "{e:?}"); + } + + #[test] + fn a_dialog_in_a_function_or_a_loop_resumes_where_it_was_called() { + let (mut r, asked) = dialog_realm(); + let script = "var seen = []; + function pickOne(n) { + try { var f = File.openDialog('n' + n, function (f) { return f.name !== 'skip'; }); return f === null ? 'none' : f.name; } + finally { seen.push('f' + n); } + } + for (var k = 0; k < 3; k++) seen.push(pickOne(k)); + var many = File.openDialog('m', function (f) { return f.name !== 'b'; }, true); + var thrown; + try { File.openDialog('t', function () { throw new Error('no'); }); } catch (e) { thrown = e.message; } + seen.concat([many.length, many[1].name, thrown]).join()"; + r.start(script).unwrap(); + for answer in ["/a", "/skip", "/c"] { + assert_eq!(until_wait(&mut r), None); + r.answer(Data::String(answer.into())).unwrap(); + } + assert_eq!(until_wait(&mut r), None); + r.answer(Data::Array(["/a", "/b", "/c"].map(|p| Data::String(p.into())).to_vec())).unwrap(); + assert_eq!(until_wait(&mut r), None); + r.collect_garbage(); + r.answer(Data::String("/a".into())).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("f0,a,f1,none,f2,c,2,c,no".into()))); + assert_eq!(asked.borrow().len(), 5, "each dialog asked once"); + } + #[test] fn objects_keep_their_classes_through_collections() { let mut r = realm(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index dea53c557f..3b96953e8d 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -177,11 +177,13 @@ pub(crate) enum NativeKind { /// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given. /// `Data` is a host function given [`crate::Data`], its arguments read as `read` says. `Eval` is a /// host function that gives source to run as global code ([`crate::HostItem::Evaluator`]); `end` -/// is called when that code ends. +/// is called when that code ends. `Pausable` is a built-in that may ask the host for a value the +/// run to wait for ([`crate::interp::Pause`]). #[derive(Clone)] pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, + Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b6bf85bfcc..bb1de36694 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -165,6 +165,31 @@ type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; +/// A built-in function that may wait for the host ([`crate::heap::Func::Pausable`]): it is given +/// `this` and the arguments, and gives the host call it makes. +pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; + +/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the +/// answer, and gives the result of its call. +pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; + +/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to +/// `resume` with `keep`, at once when the host answers at once. When the host waits +/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on +/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +pub(crate) struct Pause { + pub(crate) host: Value, + pub(crate) args: Vec, + pub(crate) keep: Vec, + pub(crate) resume: ResumeFn, +} + +/// A [`Pause`] whose host call waits for its answer. +pub(crate) struct Resumption { + resume: ResumeFn, + keep: Vec, +} + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -225,6 +250,9 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before + /// the next instruction runs. + pub(crate) resuming: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -472,6 +500,7 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, @@ -682,6 +711,7 @@ impl Interp { let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); + roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -746,6 +776,14 @@ impl Interp { fn step(&mut self) -> JsResult> { self.tick()?; + // A built-in that waited for the host takes the answer on top of the stack before the + // instruction after its call runs; what it throws is thrown at that call. + if let Some(r) = self.resuming.take() { + let answer = self.pop()?; + let v = self.resume(r, answer)?; + self.push(v)?; + return Ok(None); + } let frame = self.frame_mut()?; let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") }; frame.pc += 1; @@ -2159,6 +2197,16 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } + Func::Pausable { f: native, .. } => { + let mark = self.temp_roots.len(); + self.temp_roots.push(this.clone()); + self.temp_roots.extend(args.iter().cloned()); + let held = self.held_bytes; + let r = native(self, this, &args).and_then(|p| self.ask(p)); + self.held_bytes = held; + self.temp_roots.truncate(mark); + return Ok(Prepared::Done(r?)); + } Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. @@ -2384,6 +2432,41 @@ impl Interp { Ok(a) } + /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host + /// function is called as the script's own code calls it, so it may wait; then the resume + /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands + /// in for that answer is the call's result for now. + fn ask(&mut self, p: Pause) -> JsResult { + let Pause { host, args, keep, resume } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + self.resume(r, answer) + } + + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.push(answer.clone()); + self.temp_roots.extend(r.keep.iter().cloned()); + let v = (r.resume)(self, &r.keep, answer); + self.temp_roots.truncate(mark); + v + } + /// Calls `f` from Rust and returns its result, running the loop again for a function written /// in JavaScript. pub(crate) fn call(&mut self, f: &Value, this: &Value, args: &[Value]) -> JsResult { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 72a85fb66f..0a1006a23c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -251,6 +251,7 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -286,6 +287,7 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.resuming = None; interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), @@ -375,7 +377,9 @@ impl Realm { } /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next - /// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that + /// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the + /// call, the built-in takes `d` first and gives its own result, and what it throws is thrown + /// at its call. A result past the heap limit ends the run with that /// limit, and with no call waiting this gives an internal error. pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; From fb12ddb7598d3570d6c95b9c1fc7fd98e477fe4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 15:06:11 -0800 Subject: [PATCH 013/138] Scripts: a renamed file's old path is named in the report's written rename named only the new path in written, so a run that renamed a file an earlier run wrote did not name the path it emptied. It now names both, as remove names the path it deletes. --- crates/engine/src/script/files.rs | 2 ++ crates/engine/src/tests/script_io.rs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ddc574ee71..ba2f5ec4dc 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1763,6 +1763,8 @@ fn rename(host: &Host, a: &[Data]) -> Result { file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } } + // The old path no longer holds the file, so the report names it as well as the new one. + disk.wrote(&from); disk.wrote(&to); Ok(Data::Object(vec![("fs".into(), Data::String(new))])) } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 39276d737f..75abff6956 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -513,6 +513,29 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// `rename` of a file an earlier run wrote names both its old and its new path in `written`. +#[test] +fn a_renamed_file_names_its_old_and_new_paths_in_written() { + let base = folder("renamed"); + let mut s = with_data(&base); + let first = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/old.txt'); u.open('w'); u.write('x'); vc.log(u.close());"); + assert_eq!(first.unwrap()["log"], json!([true])); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/old.txt'); var before = u.fsName;\n\ + vc.log(u.rename('new.txt')); vc.log(before); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!(true)); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for at in [1, 2] { + let path = r["log"][at].as_str().unwrap(); + assert!(written.contains(&path), "{path} in {written:?}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a /// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and /// `readonly`. From 9811cafc25bc27f07de793413ea0872556bb506d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 15:39:59 -0800 Subject: [PATCH 014/138] Scripts: copy reads its source under the rules for reading copy read the source's real path as it was when looked up, so a file replaced by a link before the read could copy a file from outside the script's places, and a link given as the source that was pointed elsewhere copied the old target. copy now reads the path as given through the same checks open uses and refuses the copy with Script file access denied when the path no longer leads to the file it was looked up as. --- crates/engine/src/script/files.rs | 29 ++++++++++--- crates/engine/src/tests/script_io.rs | 63 ++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ba2f5ec4dc..6340912cb8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1663,12 +1663,19 @@ fn copy(host: &Host, a: &[Data]) -> Result { if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { return Ok(error(m)); } - // The bytes are read once, no more than the limit, and those bytes are what is charged and - // written: a source that grows after it is read does not copy more. - let copied = match read_head(&source, MAX_FILE_BYTES) { - Ok(bytes) if bytes.len() > MAX_FILE_BYTES => return Ok(error(TOO_LARGE)), - Ok(bytes) => bytes, - Err(_) => return Ok(error(READ_FAILED)), + #[cfg(test)] + if let Some(hook) = BEFORE_COPY_READ.with(|h| h.borrow_mut().take()) { + hook(Path::new(&from), &source); + } + // The bytes are read once, no more than the limit, under the rules for reading, and those bytes + // are what is charged and written: a source that grows after it is read does not copy more, + // and a path that leads somewhere else than when it was looked up is refused. + let copied = match disk.scope.read(Path::new(&from), MAX_FILE_BYTES) { + Ok((at, bytes)) if at == source => bytes, + Ok(_) | Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)), + Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)), + Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)), + Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)), }; // The target's open objects each take a copy of the bytes, which count as written too, as does // the copy itself when it is written. @@ -2195,6 +2202,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr realm.define_file_classes(items) } +/// Tests: what the next `copy` does with its source's path, as given and as its real path, after +/// looking it up and before reading it. +#[cfg(test)] +pub(crate) type CopyHook = Box; + +#[cfg(test)] +thread_local! { + pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 75abff6956..fdd75c8c57 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -513,6 +513,69 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// `copy` reads its source under the rules for reading: a source that a link to a file outside the +/// script's places replaced after it was looked up is refused, and nothing is copied. +#[cfg(unix)] +#[test] +fn a_copy_whose_source_becomes_a_link_outside_copies_nothing() { + let base = folder("copy-link"); + let mut s = with_data(&base); + let secret = base.join("secret.txt"); + write(&secret, b"secret"); + crate::script::files::BEFORE_COPY_READ.with(|h| { + *h.borrow_mut() = Some(Box::new(move |_: &Path, source: &Path| { + std::fs::remove_file(source).unwrap(); + std::os::unix::fs::symlink(&secret, source).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, a = new File(d + '/a.txt'); a.open('w'); a.write('mine'); a.close();\n\ + vc.log([a.copy(d + '/b.txt'), a.error, new File(d + '/b.txt').exists]);", + ) + .unwrap(); + crate::script::files::BEFORE_COPY_READ.with(|h| h.borrow_mut().take()); + assert_eq!(r["log"], json!([[false, "Script file access denied", false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a link whose target changes after it was looked up is refused, also when both files +/// are in the script's places. +#[cfg(unix)] +#[test] +fn a_copy_of_a_link_that_leads_elsewhere_after_it_was_looked_up_copies_nothing() { + let base = folder("copy-relink"); + let mut s = with_data(&base); + let first = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName;\n\ + ['a', 'c'].forEach(function (n) { var f = new File(d + '/' + n + '.txt'); f.open('w'); f.write(n); f.close(); });\n\ + vc.log(d);", + ) + .unwrap(); + let data = PathBuf::from(first["log"][0].as_str().unwrap()); + std::os::unix::fs::symlink(data.join("a.txt"), data.join("link.txt")).unwrap(); + let other = data.join("c.txt"); + crate::script::files::BEFORE_COPY_READ.with(|h| { + *h.borrow_mut() = Some(Box::new(move |given: &Path, _: &Path| { + std::fs::remove_file(given).unwrap(); + std::os::unix::fs::symlink(&other, given).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, l = new File(d + '/link.txt');\n\ + vc.log([l.copy(d + '/b.txt'), l.error, new File(d + '/b.txt').exists]);", + ) + .unwrap(); + crate::script::files::BEFORE_COPY_READ.with(|h| h.borrow_mut().take()); + assert_eq!(r["log"], json!([[false, "Script file access denied", false]])); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From e9baf43e1a893bf2c658edb1f487e1eba8e77494 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 16:04:00 -0800 Subject: [PATCH 015/138] Tests: a script in the settings Scripts folder reads the files beside it The settings folder is closed to scripts except for a script's own folder inside it. The test runs a script from settings/Scripts, reads a file beside it and is refused a file elsewhere in the settings folder. --- crates/engine/src/tests/script_io.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index fdd75c8c57..2f2d7fe6f5 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1850,6 +1850,21 @@ fn script_file_grants_never_reach_the_settings_folder() { let _ = std::fs::remove_dir_all(base); } +/// A script in the Scripts folder inside the settings folder reads the files beside it, while the +/// rest of the settings folder stays closed to it. +#[test] +fn a_script_in_the_settings_scripts_folder_reads_its_own_folder() { + let base = folder("installed"); + let mut s = with_data(&base); + write(&base.join("settings/Scripts/x.txt"), b"beside"); + write(&base.join("settings/other.txt"), b"settings"); + let main = base.join("settings/Scripts/main.jsx"); + write(&main, b"var f = new File('x.txt'), g = new File(f.parent.parent.fsName + '/other.txt'); vc.log([f.open('r'), f.read(), g.open('r')]);"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!([[true, "beside", false]])); + let _ = std::fs::remove_dir_all(base); +} + /// A file dialog inside a built-in's callback throws in the app, where it cannot wait. #[test] fn script_file_dialog_in_a_callback_throws() { From 93d49ed5519bf85339c3a0a9f4425f08a4457589 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 18:15:52 -0800 Subject: [PATCH 016/138] Actions: an error in a played step names its step number within the whole action A step that fails during playback now reports its place in the action, 1 for the first step, counting excluded steps and stops, as "action step N (`id`) failed: reason". Before, the error carried the engine's batch-local number, which restarted after each View menu step, after each stop, and at every step of Step by Step and Pause For, and skipped excluded steps. A failing step of a recorded batch is named by the batch's step and its own command id. An error about the whole batch keeps its text. The engine's command.batch errors are unchanged. The message has a row in every complete-message catalog. docs/mcp.md and docs/target-app-parity.md describe the numbering. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/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/tests.rs | 17 +++ 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/actions.rs | 198 +++++++++++++++++++++++---- docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 27 files changed, 220 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 373eb0b79d..b762458dee 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5420,6 +5420,7 @@ digits Malayalam Malaiàlam @msg bad trailer tràiler incorrecte @msg balance must be between 0 and 100 balance ha d’estar entre 0 i 100 @msg batch step {_1} (`{id}`) failed: {e} el pas de lot {_1} (`{id}`) ha fallat: {e} +@msg action step {_1} (`{id}`) failed: {reason} el pas {_1} de l’acció (`{id}`) ha fallat: {reason} @msg Batch: {count} processed Lot: {count} processats @msg Batch: {count} processed, {failed} failed Lot: {count} processats, {failed} fallits @msg before must name a panel before ha de nomenar un panell diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7178be3143..48698a971f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4890,6 +4890,7 @@ imageTrace Outline Obrys @msg bad trailer chybný trailer @msg balance must be between 0 and 100 balance musí být mezi 0 a 100 @msg batch step {_1} (`{id}`) failed: {e} krok dávky {_1} (`{id}`) selhal: {e} +@msg action step {_1} (`{id}`) failed: {reason} krok akce {_1} (`{id}`) selhal: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness musí být dark|mediumDark|mediumLight|light @msg can't encode the document: {0} dokument nelze zakódovat: {0} @msg can't parse shortcut `{c}` klávesovou zkratku `{c}` nelze analyzovat diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 951f6f9c37..16dbf2930f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4504,6 +4504,7 @@ theme Appearance Erscheinungsbild @msg bad trailer fehlerhafter Trailer @msg balance must be between 0 and 100 balance muss zwischen 0 und 100 liegen @msg batch step {_1} (`{id}`) failed: {e} Stapelschritt {_1} (`{id}`) ist fehlgeschlagen: {e} +@msg action step {_1} (`{id}`) failed: {reason} Aktionsschritt {_1} (`{id}`) ist fehlgeschlagen: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness muss dark|mediumDark|mediumLight|light sein @msg can't encode the document: {0} das Dokument kann nicht kodiert werden: {0} @msg can't parse shortcut `{c}` Tastaturbefehl `{c}` kann nicht ausgewertet werden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 62e3adc491..1c210ebb38 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4537,6 +4537,7 @@ digits Malayalam Μαλαγιάλαμ @msg bad trailer μη έγκυρο τελικό τμήμα @msg balance must be between 0 and 100 το balance πρέπει να είναι μεταξύ 0 και 100 @msg batch step {_1} (`{id}`) failed: {e} απέτυχε το βήμα {_1} της μαζικής επεξεργασίας (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} απέτυχε το βήμα {_1} της ενέργειας (`{id}`): {reason} @msg brightness must be dark|mediumDark|mediumLight|light το brightness πρέπει να είναι dark|mediumDark|mediumLight|light @msg can't encode the document: {0} δεν είναι δυνατή η κωδικοποίηση εγγράφου: {0} @msg can't parse shortcut `{c}` δεν είναι δυνατή η ανάλυση της συντόμευσης `{c}` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d1c6aa53af..ed27d9b712 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4581,6 +4581,7 @@ axis Both Ambos @msg bad trailer trailer no válido @msg balance must be between 0 and 100 balance debe estar entre 0 y 100 @msg batch step {_1} (`{id}`) failed: {e} falló el paso {_1} del lote (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} falló el paso {_1} de la acción (`{id}`): {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness debe ser dark|mediumDark|mediumLight|light @msg can't encode the document: {0} no se puede codificar el documento: {0} @msg can't parse shortcut `{c}` no se puede interpretar el atajo `{c}` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 45e47fd355..1b06b0e746 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4796,6 +4796,7 @@ imageTrace Outline Ääriviiva @msg bad trailer virheellinen trailer @msg balance must be between 0 and 100 balance-arvon on oltava väliltä 0–100 @msg batch step {_1} (`{id}`) failed: {e} erävaihe {_1} (`{id}`) epäonnistui: {e} +@msg action step {_1} (`{id}`) failed: {reason} toiminnon vaihe {_1} (`{id}`) epäonnistui: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness-arvon on oltava dark|mediumDark|mediumLight|light @msg can't encode the document: {0} asiakirjaa ei voi koodata: {0} @msg can't parse shortcut `{c}` pikanäppäintä `{c}` ei voi jäsentää diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 057dce6872..2f75ad551a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4570,6 +4570,7 @@ axis Both Les deux @msg bad trailer trailer non valide @msg balance must be between 0 and 100 balance doit être compris entre 0 et 100 @msg batch step {_1} (`{id}`) failed: {e} l’étape {_1} du lot (`{id}`) a échoué : {e} +@msg action step {_1} (`{id}`) failed: {reason} l’étape {_1} du script (`{id}`) a échoué : {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness doit valoir dark|mediumDark|mediumLight|light @msg can't encode the document: {0} impossible d’encoder le document : {0} @msg can't parse shortcut `{c}` impossible d’interpréter le raccourci `{c}` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9d056e085a..eb6f033a90 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6473,6 +6473,7 @@ antiAlias Sharp शार्प @msg bad trailer size बुरा ट्रेलर आकार @msg balance must be between 0 and 100 balance 0 से 100 के बीच होना चाहिए @msg batch step {_1} (`{id}`) failed: {e} बैच चरण {_1} (`{id}`) विफल: {e} +@msg action step {_1} (`{id}`) failed: {reason} कार्रवाई चरण {_1} (`{id}`) विफल: {reason} @msg Batch: {count} processed बैच: {count} संसाधित @msg Batch: {count} processed, {failed} failed बैच: {count} संसाधित, {failed} विफल @msg batches cannot nest बैच घोंसला नहीं कर सकते diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c2f1a52cd9..64d53370e8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5041,6 +5041,7 @@ imageTrace Outline Körvonal @msg bad trailer hibás záró rész (trailer) @msg balance must be between 0 and 100 a balance értéke 0 és 100 között lehet @msg batch step {_1} (`{id}`) failed: {e} a kötegelt lépés sikertelen: {_1} (`{id}`): {e} +@msg action step {_1} (`{id}`) failed: {reason} a művelet lépése sikertelen: {_1} (`{id}`): {reason} @msg before must name a panel a before egy panelt kell megnevezzen @msg below and above must name a panel floating in another group a below és az above egy másik csoportban lebegő panelt kell megnevezzen @msg Blend colors: select at least three objects with filled colours Színek összemosása: jelölj ki legalább három kitöltött objektumot diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0ac2816b07..f10c28ac8a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4633,6 +4633,7 @@ axis Both Entrambi @msg bad trailer trailer non valido @msg balance must be between 0 and 100 balance deve essere compreso tra 0 e 100 @msg batch step {_1} (`{id}`) failed: {e} il passaggio {_1} del batch (`{id}`) non è riuscito: {e} +@msg action step {_1} (`{id}`) failed: {reason} il passaggio {_1} dell’azione (`{id}`) non è riuscito: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness deve essere dark|mediumDark|mediumLight|light @msg can't encode the document: {0} impossibile codificare il documento: {0} @msg can't parse shortcut `{c}` impossibile interpretare la scelta rapida `{c}` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 71de1ce91c..c17b3b0c8c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4471,6 +4471,7 @@ swatch Bright Violet ビビッドバイオレット @msg Expand: no gradient fills 拡張: グラデーションの塗りがありません @msg Expand: nothing to expand 拡張: 拡張するものがありません @msg batch step {_1} (`{id}`) failed: {e} バッチのステップ {_1} (`{id}`) が失敗しました: {e} +@msg action step {_1} (`{id}`) failed: {reason} アクションのステップ {_1} (`{id}`) が失敗しました: {reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP ファイルが対応するのは RGB とグレースケールのみです: colorModel には rgb または gray を指定してください @msg Targa files are RGB: colorModel rgb Targa ファイルが対応するのは RGB のみです: colorModel には rgb を指定してください @msg antiAlias `{id}`: none, art or type antiAlias に `{id}` は指定できません: none、art、type のいずれかを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2cff51d94b..e377031bad 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4267,6 +4267,7 @@ font-technology Variable ცვლადი @msg bad trailer არასწორი ტრეილერი @msg balance must be between 0 and 100 balance უნდა იყოს 0-სა და 100-ს შორის @msg batch step {_1} (`{id}`) failed: {e} პაკეტის ნაბიჯი {_1} (`{id}`) ვერ შესრულდა: {e} +@msg action step {_1} (`{id}`) failed: {reason} მოქმედების ნაბიჯი {_1} (`{id}`) ვერ შესრულდა: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness უნდა იყოს dark|mediumDark|mediumLight|light @msg can't encode the document: {0} დოკუმენტის კოდირება ვერ ხერხდება: {0} @msg can't parse shortcut `{c}` მალსახმობის `{c}` ანალიზი ვერ ხერხდება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4715a413f4..897e91021f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4398,6 +4398,7 @@ theme Appearance 외관 @msg Expand: no gradient fills 확장: 그레이디언트 칠이 없습니다 @msg Expand: nothing to expand 확장: 확장할 항목이 없습니다 @msg batch step {_1} (`{id}`) failed: {e} 일괄 처리 단계 {_1}(`{id}`) 실패: {e} +@msg action step {_1} (`{id}`) failed: {reason} 액션 단계 {_1}(`{id}`) 실패: {reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 파일은 RGB 또는 그레이스케일입니다: colorModel rgb 또는 gray @msg Targa files are RGB: colorModel rgb Targa 파일은 RGB입니다: colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`: none, art 또는 type이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 94957fb782..46a3a9dfd9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4967,6 +4967,7 @@ imageTrace Outline Contour @msg bad trailer onjuiste trailer @msg balance must be between 0 and 100 balance moet tussen 0 en 100 liggen @msg batch step {_1} (`{id}`) failed: {e} batchstap {_1} (`{id}`) is mislukt: {e} +@msg action step {_1} (`{id}`) failed: {reason} actiestap {_1} (`{id}`) is mislukt: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness moet dark|mediumDark|mediumLight|light zijn @msg can't encode the document: {0} kan het document niet coderen: {0} @msg can't parse shortcut `{c}` kan sneltoets `{c}` niet parseren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5184985726..adcd25f281 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4714,6 +4714,7 @@ imageTrace Outline Kontur @msg bad trailer nieprawidłowa sekcja trailer @msg balance must be between 0 and 100 balance musi mieścić się w zakresie od 0 do 100 @msg batch step {_1} (`{id}`) failed: {e} krok wsadowy {_1} (`{id}`) nie powiódł się: {e} +@msg action step {_1} (`{id}`) failed: {reason} krok operacji {_1} (`{id}`) nie powiódł się: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness musi mieć wartość dark|mediumDark|mediumLight|light @msg can't encode the document: {0} nie można zakodować dokumentu: {0} @msg can't parse shortcut `{c}` nie można przeanalizować skrótu `{c}` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f6e54552d4..3a4fd2b812 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4035,6 +4035,7 @@ axis Both Ambos @msg bad trailer trailer inválido @msg balance must be between 0 and 100 balance deve estar entre 0 e 100 @msg batch step {_1} (`{id}`) failed: {e} a etapa {_1} do lote (`{id}`) falhou: {e} +@msg action step {_1} (`{id}`) failed: {reason} a etapa {_1} da ação (`{id}`) falhou: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness deve ser dark|mediumDark|mediumLight|light @msg can't encode the document: {0} não foi possível codificar o documento: {0} @msg can't parse shortcut `{c}` não foi possível interpretar o atalho `{c}` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8dc8336089..7d4271e645 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4618,6 +4618,7 @@ axis Both Оба @msg bad trailer недопустимый трейлер @msg balance must be between 0 and 100 balance должен быть от 0 до 100 @msg batch step {_1} (`{id}`) failed: {e} шаг пакета {_1} (`{id}`) не выполнен: {e} +@msg action step {_1} (`{id}`) failed: {reason} шаг действия {_1} (`{id}`) не выполнен: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness должен быть dark|mediumDark|mediumLight|light @msg can't encode the document: {0} не удалось закодировать документ: {0} @msg can't parse shortcut `{c}` не удалось разобрать сочетание `{c}` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cfb9d9734b..366ec12fec 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4481,6 +4481,7 @@ axis Both Båda @msg bad trailer ogiltig trailer @msg balance must be between 0 and 100 balance måste vara mellan 0 och 100 @msg batch step {_1} (`{id}`) failed: {e} batchsteg {_1} (`{id}`) misslyckades: {e} +@msg action step {_1} (`{id}`) failed: {reason} åtgärdssteg {_1} (`{id}`) misslyckades: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness måste vara dark|mediumDark|mediumLight|light @msg can't encode the document: {0} kan inte koda dokumentet: {0} @msg can't parse shortcut `{c}` kan inte tolka kortkommandot `{c}` diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 705fc68db2..0c6b771f25 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2931,6 +2931,23 @@ fn selected_path_reason_is_translated() { } } +/// The error of a played action step is translated in every language of [`COMPLETE_MESSAGES`], with +/// its reason; the step's number and command id stay as they are. +#[test] +fn action_step_errors_are_translated() { + let template = "action step {_1} (`{id}`) failed: {reason}"; + assert!(message_literals().contains(template)); + let reason = "select a path"; + let error = format!("action step 4 (`path.reverse`) failed: {reason}"); + assert_eq!(message(Lang::EN, &error), error); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &error); + assert!(!shown.starts_with("action step") && shown.contains('4') && shown.contains("`path.reverse`"), "{code}: {shown}"); + assert!(shown.contains(&message(lang, reason)) && !shown.contains(reason), "{code}: {shown}"); + } +} + /// The errors a script's `File` and `Folder` objects, `vc.run` and `$.evalFile` raise are /// translated in every language of [`COMPLETE_MESSAGES`], and so is the status bar's line for a run /// that ends with one: the script's name, its place, the command ids and what the script itself diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2b3e843ba3..8ecb0be5fb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4316,6 +4316,7 @@ axis Both Her İkisi @msg bad trailer kötü römork @msg balance must be between 0 and 100 balance 0 ile 100 arasında olmalıdır @msg batch step {_1} (`{id}`) failed: {e} toplu adım {_1} (`{id}`) başarısız oldu: {e} +@msg action step {_1} (`{id}`) failed: {reason} eylem adımı {_1} (`{id}`) başarısız oldu: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness dark|mediumDark|mediumLight|light olmalıdır @msg can't encode the document: {0} belge kodlanamıyor: {0} @msg can't parse shortcut `{c}` `{c}` kısayolu ayrıştırılamıyor diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d4a2493914..38b0fb90d4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4617,6 +4617,7 @@ axis Both Обидві @msg bad trailer неприпустимий трейлер @msg balance must be between 0 and 100 balance має бути від 0 до 100 @msg batch step {_1} (`{id}`) failed: {e} крок пакету {_1} (`{id}`) не виконано: {e} +@msg action step {_1} (`{id}`) failed: {reason} крок дії {_1} (`{id}`) не виконано: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness має бути dark|mediumDark|mediumLight|light @msg can't encode the document: {0} не вдалося закодувати документ: {0} @msg can't parse shortcut `{c}` не вдалося розібрати поєднання `{c}` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d8469bce53..f56f05514a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4695,6 +4695,7 @@ theme Appearance Giao diện @msg bad trailer trailer không hợp lệ @msg balance must be between 0 and 100 balance phải nằm trong khoảng 0 đến 100 @msg batch step {_1} (`{id}`) failed: {e} bước hàng loạt {_1} (`{id}`) thất bại: {e} +@msg action step {_1} (`{id}`) failed: {reason} bước {_1} của hành động (`{id}`) thất bại: {reason} @msg before must name a panel before phải đặt tên bảng @msg below and above must name a panel floating in another group below và above phải đặt tên bảng đang thả nổi trong nhóm khác @msg Blend colors: select at least three objects with filled colours Hòa trộn màu: chọn ít nhất ba đối tượng có màu tô diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8ab185e5f9..4881841f48 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4174,6 +4174,7 @@ imageTrace Outline 轮廓 @msg Expand: no gradient fills 扩展:没有渐变填色 @msg Expand: nothing to expand 扩展:没有可扩展的内容 @msg batch step {_1} (`{id}`) failed: {e} 批处理步骤 {_1} (`{id}`) 失败:{e} +@msg action step {_1} (`{id}`) failed: {reason} 动作步骤 {_1} (`{id}`) 失败:{reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 文件为 RGB 或灰度:colorModel rgb 或 gray @msg Targa files are RGB: colorModel rgb Targa 文件为 RGB:colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`:none、art 或 type diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a0d987fe69..44123bb83a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1887,6 +1887,7 @@ file-filter Templates 範本 @msg Expand: no gradient fills 展開:沒有漸層填色 @msg Expand: nothing to expand 展開:沒有可展開的內容 @msg batch step {_1} (`{id}`) failed: {e} 批次步驟 {_1} (`{id}`) 失敗:{e} +@msg action step {_1} (`{id}`) failed: {reason} 動作步驟 {_1} (`{id}`) 失敗:{reason} @msg BMP files are RGB or grayscale: colorModel rgb or gray BMP 檔案為 RGB 或灰階:colorModel rgb 或 gray @msg Targa files are RGB: colorModel rgb Targa 檔案為 RGB:colorModel rgb @msg antiAlias `{id}`: none, art or type antiAlias `{id}`:none、art 或 type diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 630d81e95f..995c1ca1dc 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -74,18 +74,32 @@ impl Action { /// played, or a panel operation that runs as one batch, while recording) gives its own steps, /// since batches do not nest. pub(crate) fn included_commands(&self) -> Vec { + self.playback_steps().into_iter().map(|s| s.command).collect() + } + + /// [`Action::included_commands`], each with the index in [`Action::steps`] of the step it comes + /// from: the steps of a recorded `command.batch` share its index. + fn playback_steps(&self) -> Vec { self.steps .iter() .enumerate() .filter(|(i, _)| !self.excluded_steps.contains(i)) - .flat_map(|(_, (command, params))| match params.get("commands").and_then(Value::as_array) { - Some(steps) if command == "command.batch" => steps.clone(), - _ => vec![json!({"command": command, "params": params})], + .flat_map(|(row, (command, params))| match params.get("commands").and_then(Value::as_array) { + Some(steps) if command == "command.batch" => steps.iter().map(|c| PlayStep { row, command: c.clone() }).collect(), + _ => vec![PlayStep { row, command: json!({"command": command, "params": params}) }], }) .collect() } } +/// A step that playback runs: a command as `command.batch` takes it, and the index in +/// [`Action::steps`] of the step it comes from, which an error names. +#[derive(Clone, Debug)] +struct PlayStep { + row: usize, + command: Value, +} + /// An action id no other action in this run has. fn next_action_id() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -231,9 +245,12 @@ pub fn default_sets() -> Vec { /// A View menu step ([`is_ui_step`]) runs on its own at every speed, in its place among the steps, and /// adds no undo step ([`run_steps`]). At Accelerated the steps before it and the steps after it are /// then one undo step each. +/// +/// At every speed, the error of a step that fails names the step by its place in the action, 1 for +/// the first, counting excluded steps and stops ([`step_error`]). pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result { let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(idx)).cloned() else { return Err("no such action".into()) }; - let commands = a.included_commands(); + let commands = a.playback_steps(); if commands.is_empty() { return Err("the action has no included steps".into()); } @@ -241,13 +258,13 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result = commands.into(); + let mut steps: std::collections::VecDeque = commands.into(); let Some(first) = steps.pop_front() else { return Err("the action has no included steps".into()) }; let result = play_step(app, &a.name, first)?; let pending = steps.len(); @@ -265,7 +282,7 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result Result { +fn play_step(app: &mut VectorcraftApp, label: &str, step: PlayStep) -> Result { Ok(run_steps(app, label, vec![step])?.into_iter().next().unwrap_or(Value::Null)) } @@ -278,20 +295,33 @@ pub(crate) fn is_ui_step(step: &Value) -> bool { /// Runs `steps` in order, as saved steps ([`VectorcraftApp::replay`]) → their results. The steps /// between two View menu steps ([`is_ui_step`]) run as one `command.batch` named `label`, which is one /// undo step; a View menu step runs on its own ([`play_ui_step`]). A step that fails ends the run with -/// its error: the batch it is in changes nothing, and the steps before that batch stay done. -fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec) -> Result, String> { - fn batch(app: &mut VectorcraftApp, label: &str, run: Vec, results: &mut Vec) -> Result<(), String> { +/// its error: the batch it is in changes nothing, and the steps before that batch stay done. The error +/// of a step names the step's place in the action ([`step_error`]). +fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec) -> Result, String> { + fn batch(app: &mut VectorcraftApp, label: &str, run: Vec, results: &mut Vec) -> Result<(), String> { if run.is_empty() { return Ok(()); } - let r = app.replay("command.batch", json!({"label": label, "commands": run}))?; + let (rows, run): (Vec, Vec) = run.into_iter().map(|s| (s.row, s.command)).unzip(); + let r = match app.replay("command.batch", json!({"label": label, "commands": run})) { + Ok(r) => r, + Err(e) => { + // The batch numbers its steps from 0 within this run of them, not within the action. + if let Some((n, id, reason)) = batch_step_failure(&e) + && let Some(&row) = rows.get(n) + { + return step_error(row, id, reason); + } + return Err(e); + } + }; results.extend(r.get("results").and_then(Value::as_array).cloned().unwrap_or_default()); Ok(()) } let mut results = Vec::with_capacity(steps.len()); let mut run = vec![]; for step in steps { - if is_ui_step(&step) { + if is_ui_step(&step.command) { batch(app, label, std::mem::take(&mut run), &mut results)?; results.push(play_ui_step(app, &step)?); } else { @@ -302,13 +332,34 @@ fn run_steps(app: &mut VectorcraftApp, label: &str, steps: Vec) -> Result Ok(results) } +/// The step number, command id and reason in the error `command.batch` gives when one of its steps +/// fails (``batch step 2 (`object.move`) failed: …``); none for any other error, such as one about +/// the whole batch. +fn batch_step_failure(e: &str) -> Option<(usize, &str, &str)> { + let rest = e.strip_prefix("batch step ")?; + let digits = rest.find(|c: char| !c.is_ascii_digit())?; + let n = rest[..digits].parse().ok()?; + let (id, reason) = rest[digits..].strip_prefix(" (`")?.split_once("`) failed: ")?; + Some((n, id, reason)) +} + +/// The error of a played step with command `id` that failed with `reason`, naming the step by its +/// place in the action: 1 for the action's first step, counting excluded steps and stops. A step of +/// a recorded `command.batch` is named by the batch's place and its own command. +fn step_error(row: usize, id: &str, reason: &str) -> Result { + Err(format!("action step {} (`{id}`) failed: {reason}", row + 1)) +} + /// Runs a View menu step as its menu item runs it, which adds no undo step → its result. While an /// action records, the step goes into the recording too, as a stop does, unless it does not fit in /// the action ([`recording_room`]): then the status bar shows the reason. -fn play_ui_step(app: &mut VectorcraftApp, step: &Value) -> Result { - let command = step.get("command").and_then(Value::as_str).unwrap_or_default().to_string(); - let params = step.get("params").filter(|p| !p.is_null()).cloned().unwrap_or_else(|| json!({})); - let r = app.replay(&command, params.clone())?; +fn play_ui_step(app: &mut VectorcraftApp, step: &PlayStep) -> Result { + let command = step.command.get("command").and_then(Value::as_str).unwrap_or_default().to_string(); + let params = step.command.get("params").filter(|p| !p.is_null()).cloned().unwrap_or_else(|| json!({})); + let r = match app.replay(&command, params.clone()) { + Ok(r) => r, + Err(e) => return step_error(step.row, &command, &e), + }; if app.ui.recording.is_some() { match recording_room(app, &command, ¶ms) { Ok(()) => app.session.journal.push((command, params)), @@ -320,8 +371,8 @@ fn play_ui_step(app: &mut VectorcraftApp, step: &Value) -> Result /// [`play`] for an action with a stop: runs what comes before the first stop, or at Step by Step and /// Pause For the first step, and leaves the rest to [`tick_playback`] and [`continue_playback`]. -fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec, options: PlaybackOptions) -> Result { - let mut steps: std::collections::VecDeque = commands.into(); +fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec, options: PlaybackOptions) -> Result { + let mut steps: std::collections::VecDeque = commands.into(); let run = next_run(&mut steps, options.speed); let ran = !run.is_empty(); let results = if ran { run_steps(app, &label, run)? } else { vec![] }; @@ -332,9 +383,9 @@ fn play_with_stops(app: &mut VectorcraftApp, label: String, commands: Vec /// Takes the steps that run next as one undo step off the front of `steps`: at Accelerated all of /// them up to the next stop, at the other speeds one. None when a stop comes next. -fn next_run(steps: &mut std::collections::VecDeque, speed: PlaybackSpeed) -> Vec { +fn next_run(steps: &mut std::collections::VecDeque, speed: PlaybackSpeed) -> Vec { let mut run = vec![]; - while steps.front().is_some_and(|s| !is_stop(s)) { + while steps.front().is_some_and(|s| !is_stop(&s.command)) { run.extend(steps.pop_front()); if speed != PlaybackSpeed::Accelerated { break; @@ -353,7 +404,7 @@ fn after_run(app: &mut VectorcraftApp, ran: bool) { playing.played_in = played_in; playing.next_at = None; playing.hold = ran && playing.options.speed == PlaybackSpeed::Step; - if (!ran || playing.options.speed == PlaybackSpeed::Accelerated) && playing.steps.front().is_some_and(is_stop) { + if (!ran || playing.options.speed == PlaybackSpeed::Accelerated) && playing.steps.front().is_some_and(|s| is_stop(&s.command)) { hold_at_stop(app); } if let Some(ctx) = &app.ui_ctx { @@ -418,7 +469,7 @@ struct AtStop { fn hold_at_stop(app: &mut VectorcraftApp) { let Some(playing) = app.ui.action_playing.as_mut() else { return }; let Some(step) = playing.steps.pop_front() else { return }; - let params = step.get("params").cloned().unwrap_or(Value::Null); + let params = step.command.get("params").cloned().unwrap_or(Value::Null); let message = params.get("message").and_then(Value::as_str).unwrap_or_default().to_string(); let allow_continue = params.get("allowContinue").and_then(Value::as_bool).unwrap_or(false); playing.stop = Some(AtStop { message, allow_continue, shown: false }); @@ -523,7 +574,7 @@ pub fn deserialize_playback<'de, D: serde::Deserializer<'de>>(d: D) -> Result, + steps: std::collections::VecDeque, /// The options the action started playing with. options: PlaybackOptions, /// With Pause For, when the next step runs (seconds on the app's clock); none until the frame @@ -581,7 +632,7 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { return Some(due - now); } } - if playing.steps.front().is_some_and(is_stop) { + if playing.steps.front().is_some_and(|s| is_stop(&s.command)) { hold_at_stop(app); return None; } @@ -4922,6 +4973,105 @@ mod tests { assert_eq!(x(&app), 1.0, "the move before Outline stays, and the move of 2 in the failing batch is taken back"); } + /// The error of a played step that fails, with the step's place in the action (1 for the first) + /// and its command id. + fn assert_names_step(e: &str, step: usize, id: &str) { + let prefix = format!("action step {step} (`{id}`) failed: "); + assert!(e.starts_with(&prefix) && e.len() > prefix.len(), "{e}"); + assert!(!e.contains("batch step"), "{e}"); + } + + /// A step that fails after a View menu step at Accelerated is named by its place in the action, + /// not by its place in the batch of the steps after the View step. + #[test] + fn an_error_after_a_view_item_names_the_step_in_the_action() { + let (mut app, _) = app_with_a_view_step(); + app.ui.action_sets[0].actions[0].steps.insert(3, ("object.align".into(), json!({}))); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 4, "object.align"); + } + + /// A View menu step that fails is named by its place in the action, excluded steps counted. + #[test] + fn a_failing_view_item_names_the_step_in_the_action() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let steps = vec![("object.move".to_string(), json!({"dx": 1, "dy": 0})), ("view.outline".to_string(), json!({}))]; + let mut action = Action::new("Outline", steps); + action.excluded_steps.insert(0); + app.ui.action_sets = vec![ActionSet::new("Test", vec![action])]; + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 2, "view.outline"); + } + + /// An excluded step before the failing one counts at Accelerated, as the panel lists it. + #[test] + fn an_error_counts_excluded_steps() { + let (mut app, x) = app_with_three_moves(); + let action = &mut app.ui.action_sets[0].actions[0]; + action.steps.push(("object.align".into(), json!({}))); + action.excluded_steps.insert(0); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 4, "object.align"); + assert_eq!(x(&app), 0.0, "the failing batch changes nothing"); + } + + /// A step of a recorded `command.batch` that fails is named by the batch's place in the action + /// and its own command. + #[test] + fn an_error_in_a_recorded_batch_names_the_batch_step() { + let (mut app, _) = app_with_three_moves(); + let batch = json!({"commands": [{"command": "object.move", "params": {"dx": 2, "dy": 0}}, {"command": "object.align", "params": {}}]}); + app.ui.action_sets[0].actions[0].steps.insert(1, ("command.batch".into(), batch)); + assert_names_step(&play(&mut app, 0, 0).unwrap_err(), 2, "object.align"); + } + + /// An error about the whole batch, which names no step, is kept as it is. + #[test] + fn an_error_of_the_whole_batch_names_no_step() { + let (mut app, _) = app_with_three_moves(); + let nested = json!({"commands": [{"command": "command.batch", "params": {"commands": []}}]}); + app.ui.action_sets[0].actions[0].steps.push(("command.batch".into(), nested)); + let e = play(&mut app, 0, 0).unwrap_err(); + assert!(!e.starts_with("action step"), "{e}"); + assert!(e.contains("batches cannot nest"), "{e}"); + } + + /// At Step by Step and Pause For, a later step that fails is named by its place in the action, + /// in the status bar, and the playback ends. + #[test] + fn a_paced_error_names_the_step_in_the_action() { + for speed in ["step", "pause"] { + let (mut app, x) = app_with_three_moves(); + app.ui.action_sets[0].actions[0].steps.insert(2, ("object.align".into(), json!({}))); + app.run(PLAYBACK_OPTIONS, json!({"speed": speed})).unwrap(); + play(&mut app, 0, 0).unwrap(); + let mut now = 0.0; + for _ in 0..40 { + if app.ui.action_playing.is_none() { + break; + } + now += 2.0; + frame(&mut app, now); + } + assert!(app.ui.action_playing.is_none(), "{speed}: the playback ended"); + assert_names_step(&app.ui.status, 3, "object.align"); + assert_eq!(x(&app), 3.0, "{speed}: the moves before the failing step stay, the move after it does not run"); + } + } + + /// A step that fails after Continue at a stop is named by its place in the action, the stops + /// before it counted, the excluded one too. + #[test] + fn an_error_after_a_stop_names_the_step_in_the_action() { + let (mut app, _) = app_with_three_moves(); + let stop = (STOP_STEP.to_string(), json!({"message": "", "allowContinue": true})); + let action = &mut app.ui.action_sets[0].actions[0]; + action.steps.insert(1, stop.clone()); + action.steps.insert(3, stop); + action.steps.push(("object.align".into(), json!({}))); + action.excluded_steps.insert(3); + assert_eq!(play(&mut app, 0, 0).unwrap()["atStop"], json!(true)); + assert_names_step(&app.run(CONTINUE_PLAYBACK, json!({})).unwrap_err(), 6, "object.align"); + assert!(app.ui.action_playing.is_none(), "the playback ended"); + } + /// At Step by Step and Pause For a View menu step is one step of the playback and adds no undo /// step. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index f7d99cbd04..d320187c0d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3323,8 +3323,11 @@ already walks Image Trace. Short agent entry points: menu step (`ui.action.insertMenuItem`) plays at every speed in its place among the steps, as its menu item runs, and adds no undo step. At Accelerated the steps before it and the steps after it are one undoable batch each, and the result is `{results}` with every step's result in order. A step that fails ends the playback with its error: the - batch it is in changes nothing, and the steps before that batch stay done. While another action records, the View - menu step is recorded too. Batch… refuses an action with an included View menu step. + batch it is in changes nothing, and the steps before that batch stay done. At every speed, and after + `ui.action.continue`, the error names the step by its place in the action, 1 for the first step, counting excluded + steps and stops (``action step 4 (`object.align`) failed: …``). A failing step of a recorded `command.batch` is + named by the batch's place and its own command. An error about the whole batch names no step. While another action + records, the View menu step is recorded too. Batch… refuses an action with an included View menu step. - Actions: `ui.action.insertStop {set?, action?, step?, message?, allowContinue?}` inserts a stop. With `set` and `action`, the stop goes into that action, after step `step`, else after its last step, and the command returns `{set, action, step}`. Without them it goes into the recording in progress, after the steps recorded so far, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 19b9c8d319..79ed09c229 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -772,6 +772,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Insert Stop… opens Record Stop, with a Message box and Allow Continue, and adds a stop to the recording in progress, after the selected command, or at the end of the selected action ([Insert stops in actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-stops-in-actions.html); `ui.action.insertStop`). A playing action waits at the stop and shows the message so the user can do a manual task, and Play Current Selection plays the rest ([Illustrator CS5 help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=459); `ui.action.continue`). With Allow Continue, the message box also has Continue. VectorCraft's own rules, which the pages do not cover: an empty message still waits, Stop Playing/Recording ends the playback and keeps the steps already played, the rest plays on the document active then, a stop waits at every playback speed, at Accelerated the steps between two stops are one undo step, Batch… refuses an action with an included stop, and Delete Selection on a selected step deletes that step, a stop or a command, without asking (`ui.action.deleteStep`). - Actions panel: the panel menu's Insert Menu Item… adds a menu command to the recording in progress, after the selected step, or at the end of the selected action, without running it, and playback runs it as the menu does ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertMenuItem`). The dialog's Find box picks the one item that matches the words typed, and a click on a listed item picks it. VectorCraft's own rules, which the page does not cover: items that open a dialog, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern, and the File, Window and Help menu items are not listed, and an action holds at most 10,000 steps and its set file at most 8 MiB, for stops too. - Actions panel: Insert Menu Item… also lists the Object › Align items and the View menu commands that act on the window rather than the document (Outline, Pixel Preview, Trim View, Presentation Mode, Screen Mode, zoom, fit, Rotate View, and the show, hide and snap items), which the help page names among the commands that cannot be recorded ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); [Align and distribute objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/align-and-distribute-objects.html); `ui.action.insertMenuItem`, `ui.action.play`). VectorCraft's own rules, which the pages do not cover: an Align step keeps the Align To choice of its insertion, and one that aligns to the key object stops the playback when there is no key; a View menu step plays in its place at every speed and adds no undo step, so at Accelerated the steps on each side of it are one undo step each; Batch… refuses an action with one; and a set file with one is version 6. Tests `panels::actions::tests::{an_inserted_view_item_plays_in_its_place_at_accelerated, an_inserted_view_item_plays_step_by_step_and_with_pauses, an_inserted_view_item_plays_up_to_a_stop, a_view_step_played_while_recording_is_recorded, a_saved_view_step_survives_as_version_6, an_inserted_align_item_keeps_the_align_to_of_its_insertion, an_align_step_to_the_key_object_fails_without_a_key}`. + - Actions panel: the error of a played step that fails names the step by its place in the expanded action, 1 for the first step, counting excluded steps and stops, at every playback speed and after a stop (`ui.action.play`, `ui.action.continue`). A failing step of a recorded batch is named by the batch's place and its own command. The numbering is VectorCraft's own rule. Tests `panels::actions::tests::{an_error_after_a_view_item_names_the_step_in_the_action, a_failing_view_item_names_the_step_in_the_action, an_error_counts_excluded_steps, an_error_in_a_recorded_batch_names_the_batch_step, an_error_of_the_whole_batch_names_no_step, a_paced_error_names_the_step_in_the_action, an_error_after_a_stop_names_the_step_in_the_action}`. - Actions panel: with a path selected, the panel menu's Insert Select Path adds a step that selects that path to the recording in progress, after the selected step, or at the end of the selected action, without changing the selection ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectPath`, `select.storedPath`). VectorCraft's own rules, which the page does not cover: the selection must be one whole path or compound path that can be selected, the step stores the path's id and a fingerprint of its anchors, and playback selects the path only while it is still there unchanged and can be selected, else the step is an error and the selection stays; the row reads Select Path, and a set file with the step is version 5. - Actions panel: the panel menu's Select Object… opens Set Selection, where the note typed names the objects to select, and adds a step to the recording in progress, after the selected step, or at the end of the selected action; playback selects the objects whose Attributes note matches it, and the steps after it act on them ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectObject`, `select.byNote`). VectorCraft's own rules, which the page does not cover: the note matches anywhere and in any letter case unless Case Sensitive or Whole Word is checked, hidden and locked objects are left out, the objects found replace the selection, a step that finds none stops the playback with an error, and the note is at most 1,024 bytes. Action sets with the step save as version 4. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. From e53b1346aea2f1ea7581e1fa527b959137a8deea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 18:45:18 -0800 Subject: [PATCH 017/138] i18n: Swedish names Apply SVG Filter, Check Spelling, SVG Filter and the 3D graphics note MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Swedish catalog had rows for "Apply SVG Filter…", "Check Spelling…" and "SVG Filters", and an @msg row for the 3D graphics sentence, but no plain rows for the names without an ellipsis, the singular effect name or the sentence with its period. The command names, the SVG Filter undo step and the 3D and Materials panel's note showed in English. Add the four plain rows next to their related rows, using the catalog's existing terms, and a test that checks them and the undo step name. --- crates/ui-egui/src/i18n/sv.tsv | 4 ++++ crates/ui-egui/src/i18n/tests.rs | 16 ++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 21 insertions(+) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cfb9d9734b..f66b87b050 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -212,6 +212,7 @@ font-technology Variable Variabla Apply Last Gradient Använd senaste gradienten Apply Paragraph Style Använd styckestil Apply SVG Filter… Använd SVG-filter… + Apply SVG Filter Använd SVG-filter Apply to All Använd på alla @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) Använd på alla ({n} till saknas)|Använd på alla ({n} till saknas) Arc Båge @@ -462,6 +463,7 @@ font-technology Variable Variabla Not a script for the reference app Inte ett skript för referensappen Some lists were cut short at their limit. Vissa listor kortades av vid gränsvärdet. Check Spelling… Kontrollera stavning… + Check Spelling Kontrollera stavning Choose a folder Välj en mapp Choose… Välj… Circle Cirkel @@ -3491,6 +3493,7 @@ digits Malayalam Malayalam Superscript (on the roadmap) Upphöjd (planeras) Superscript: Upphöjd: SVG Filters SVG-filter + SVG Filter SVG-filter SVG Interactivity SVG-interaktivitet Event: Händelse: JavaScript: JavaScript: @@ -5483,6 +5486,7 @@ lighting Light Ljus @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} i `{GRAPHICS}` måste vara ett tal från {lo} till {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` måste vara en matris @msg Graphics map onto the Plane, Extrude and Revolve object types Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel + Graphics map onto the Plane, Extrude and Revolve object types. Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel. @msg Revolve maps graphics onto its side: map them onto the front Rotera runt axel placerar grafik på sin mantelyta: placera den på framsidan @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiken är för komplex för den här ytan: förenkla symbolernas teckning eller minska Segment @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tar högst {MAX_GRAPHICS} grafiker diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 705fc68db2..3700b555cd 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -309,6 +309,22 @@ fn catalan_reads_as_catalan() { assert_eq!(message(ca, nested), "l’ordre `object.group` no està disponible ara mateix: no hi ha res seleccionat"); } +/// The Swedish catalog names the SVG Filter and Check Spelling commands without their ellipsis, +/// the SVG Filter undo step, and the 3D and Materials panel's note with its period. +#[test] +fn swedish_svg_filter_spelling_and_3d_labels_are_complete() { + let sv = Lang::from_code("sv").expect("sv registered"); + for (en, want) in [ + ("Apply SVG Filter", "Använd SVG-filter"), + ("Check Spelling", "Kontrollera stavning"), + ("SVG Filter", "SVG-filter"), + ("Graphics map onto the Plane, Extrude and Revolve object types.", "Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel."), + ] { + assert_eq!(sv.catalog().plain(en), Some(want), "{en}"); + } + assert_eq!(crate::panels::history::step_name(sv, "SVG Filter").as_deref(), Some("SVG-filter")); +} + #[test] fn font_height_reference_labels_are_in_complete_catalogs() { for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 19b9c8d319..a2d523c024 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -915,6 +915,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`). - 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`). + - The Swedish catalog has rows for the Apply SVG Filter and Check Spelling command names, the SVG Filter effect's name, which also names its undo step, and the 3D and Materials panel's note that graphics map onto the Plane, Extrude and Revolve object types, so these show in Swedish instead of English (`swedish_svg_filter_spelling_and_3d_labels_are_complete`). - 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. - Commands that read their `ids` (or `slices`) list themselves refuse a list with an entry that is not a non-negative integer, and a value that is not a list, and change nothing; they no longer drop the entry and act on the rest (Copy Appearance From, the Edit Colors commands and Overprint Black, Find and Replace, `layer.highlight`, `layer.move`, `library.add`, the Links panel commands, `object.transform`, Make Pattern, the Repeat commands, the slice commands, Join, Average and Join, `plugin.run`, `symbol.edit`, Make Opacity Mask; `tests::ids_without_selection::an_ids_entry_that_is_not_an_id_is_refused_and_changes_nothing`). The error for an entry of an object id list names the key, the entry and its value ("`ids` entry 1 is true, not a non-negative integer object id"), with a row in every catalog that has the other object id errors. From b73c9834c816cc90908e73ca77fc4c5270c3369e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:08:44 -0800 Subject: [PATCH 018/138] Scripts: grants file changes take turns and use a file of their own Two processes that changed Script Grants.json at once both wrote Script Grants.json.part, so one could overwrite the other's file or fail on it. Each write now goes to a new file named for its process and write, passing over a name an earlier write left behind, and only that file is removed when the write fails. Changes hold a lock on Script Grants.lock beside the grants file and are not made when it cannot be taken; reads take it when they can. --- crates/engine/src/script/files.rs | 57 +++++++++++++++++++++++++--- crates/engine/src/tests/script_io.rs | 37 ++++++++++++++++++ 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 6340912cb8..ba1bc60827 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -431,6 +431,7 @@ impl Disk { } let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); + let Ok(_lock) = lock_store(&store) else { return }; let Ok(mut grants) = try_read_store(&store) else { return }; for g in &mut grants { let ours = g["script"] == *script @@ -566,6 +567,7 @@ impl Disk { fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; // A grants file that is there but cannot be read is left as it is. + let _lock = lock_store(&store).map_err(|_| NOT_SAVED)?; let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); @@ -882,8 +884,10 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { } /// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant -/// that is not well formed is left out. +/// that is not well formed is left out. It is read under [`lock_store`]'s lock when that can be +/// taken, so it is read between two changes. fn read_store(store: &Path) -> Vec { + let _lock = lock_store(store).ok(); load_store(store, false).unwrap_or_default() } @@ -928,8 +932,13 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result) -> std::io::Result<()> { let text = serde_json::to_vec_pretty(&serde_json::json!({"version": 1, "grants": grants})).map_err(std::io::Error::other)?; if text.len() > MAX_STORE_BYTES { @@ -938,14 +947,49 @@ fn write_store(store: &Path, grants: Vec) -> std::io::Result< if let Some(dir) = store.parent() { std::fs::create_dir_all(dir)?; } - let part = store.with_extension("json.part"); - std::fs::write(&part, text)?; + // A name an earlier write left behind is passed over, up to 64 times, and only the file made here + // is removed. + let mut tries = 0; + let (part, mut file) = loop { + let n = NEXT_PART.fetch_add(1, Ordering::Relaxed); + let part = store.with_extension(format!("json.{}-{n}.part", std::process::id())); + match std::fs::File::options().write(true).create_new(true).open(&part) { + Ok(file) => break (part, file), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && tries < 63 => tries += 1, + Err(e) => return Err(e), + } + }; + let written = std::io::Write::write_all(&mut file, &text); + drop(file); // `rename` replaces a grants file that is there, on Windows too (`MOVEFILE_REPLACE_EXISTING`). - std::fs::rename(&part, store).inspect_err(|_| { + written.and_then(|()| std::fs::rename(&part, store)).inspect_err(|_| { let _ = std::fs::remove_file(&part); }) } +/// The lock file beside the grants file at `store` (`Script Grants.lock`), locked until it is +/// dropped and waiting while another process holds it, so that processes that read and change the +/// grants file take turns. A change is not made when the lock cannot be taken. +#[cfg(not(target_arch = "wasm32"))] +fn lock_store(store: &Path) -> std::io::Result { + let lock = store.with_extension("lock"); + let opened = store + .parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(&lock)); + let file = opened.and_then(|f| f.lock().map(|()| f)); + if let Err(e) = &file { + log::warn!("can't lock {}: {e}", lock.display()); + } + file +} + +/// The browser has no folders to keep anything in. +#[cfg(target_arch = "wasm32")] +fn lock_store(_: &Path) -> std::io::Result { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) +} + /// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of /// its text, the path and whether it may be written (`script.grants`). pub(crate) fn stored_grants(data_dir: &Path) -> Vec { @@ -957,6 +1001,7 @@ pub(crate) fn stored_grants(data_dir: &Path) -> Vec { /// → how many were removed. pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); + let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); let kept: Vec = diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 2f2d7fe6f5..9b9cee9439 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -576,6 +576,43 @@ fn a_copy_of_a_link_that_leads_elsewhere_after_it_was_looked_up_copies_nothing() let _ = std::fs::remove_dir_all(base); } +/// The grants file is written through a temporary file of its own, so a temporary file another +/// process left beside it, or one an earlier write left under the name this write takes first, +/// does not stop a change and is left where it is. +#[test] +fn a_grants_change_does_not_use_another_writers_temporary_file() { + let base = folder("grants-part"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::fs::create_dir_all(base.join("settings/Script Grants.json.part/held")).unwrap(); + let next = crate::script::files::NEXT_PART.load(std::sync::atomic::Ordering::Relaxed); + let left_behind: Vec = + (next..next + 8).map(|n| base.join(format!("settings/Script Grants.json.{}-{n}.part", std::process::id()))).collect(); + for p in &left_behind { + write(p, b"earlier"); + } + assert_eq!(crate::script::files::revoke_grants(&data, None, None).unwrap(), 1); + let left: Value = serde_json::from_slice(&std::fs::read(base.join("settings/Script Grants.json")).unwrap()).unwrap(); + assert_eq!(left["grants"], json!([])); + assert!(left_behind.iter().all(|p| std::fs::read(p).is_ok_and(|b| b == b"earlier")), "files this write did not make stay"); + let _ = std::fs::remove_dir_all(base); +} + +/// A change to the grants file is not made when its lock cannot be taken. +#[test] +fn a_grants_change_without_its_lock_changes_nothing() { + let base = folder("grants-lock"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + std::fs::create_dir_all(base.join("settings/Script Grants.lock/held")).unwrap(); + assert!(crate::script::files::revoke_grants(&data, None, None).is_err()); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), text); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From 73ee0d79a6e57a18b2f8e50c543e4dce030bf2cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:52:03 -0800 Subject: [PATCH 019/138] i18n: Keyboard Shortcuts rows have names of their own in every language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With #7378's rows in place, Keyboard Shortcuts still showed 21 names on two rows each, in 10 languages. A catalog translated two English names the same way: the Scale and Zoom tools, the Column and Bar Graph tools and their stacked forms, the Pucker and Wrinkle tools, the Shear and Warp tools, Edit › Copy and Duplicate, and Pathfinder Unite and Merge. These rows now read differently in bs, fi, fr, ru, sv, uk, vi, zh-hans and zh-hant. The French Shear rows (Shear, Shear Tool, Shear… and Shear:) all use the new word, and the Bulgarian Revolve (Classic)… row uses the same words as Revolve and Revolve…. The Catalan rows for Saved View, Saved Selection and Open Recent File 2 and above had numbers out of order ("Saved View 10" read "Vista desada 2", and "Open Recent File 2" read "Obre el fitxer recent 12"). Each row now has its own number, and this removes the last 8 shared names. The ru and uk Line Graph Tool rows read as a bar graph and now read as a line graph. The uk Stacked Column Graph Tool and Perspective Selection Tool rows use «» quotes like the other tool rows. Tests: Keyboard Shortcuts shows no two rows with the same name in any language, and a plain row whose English ends with a number keeps that number in every catalog. --- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 124 +++++++++++++------------- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 8 +- crates/ui-egui/src/i18n/ru.tsv | 8 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tests.rs | 20 +++++ crates/ui-egui/src/i18n/uk.tsv | 12 +-- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/shortcut_editor.rs | 20 +++++ docs/target-app-parity.md | 1 + 14 files changed, 124 insertions(+), 83 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2089000a76..20dad5b53b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1140,7 +1140,7 @@ font-technology Variable Променливи Extrude & Bevel… Избутване и фасетка… 3D (Classic) 3D (класически) Extrude & Bevel (Classic)… Избутване и фасетка (класически)… - Revolve (Classic)… Завъртане (класическо)… + Revolve (Classic)… Завъртане около ос (класическо)… Rotate (Classic)… Ротация (класическа)… Surface Повърхност Wireframe Телена рамка diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f91fe245d6..f8e544ef5d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1450,7 +1450,7 @@ lighting Light Svjetlo Vertical Type Okomiti tekst Warp Tool Alat za iskrivljenje Width Tool Alat širina - Wrinkle Tool Alat za nabiranje + Wrinkle Tool Alat za nabore Zoom Tool Alat za zumiranje Action {n} Akcija {n} Begin Recording Započni snimanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e36b14eeb8..5f3c89348b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2930,35 +2930,35 @@ digits Malayalam Malaiàlam Open password: Contrasenya d’obertura: Open Paths Traçats oberts Open Recent File 1 Obre el fitxer recent 1 - Open Recent File 10 Obre el fitxer recent 2 - Open Recent File 11 Obre el fitxer recent 3 - Open Recent File 12 Obre el fitxer recent 4 - Open Recent File 13 Obre el fitxer recent 5 - Open Recent File 14 Obre el fitxer recent 6 - Open Recent File 15 Obre el fitxer recent 7 - Open Recent File 16 Obre el fitxer recent 8 - Open Recent File 17 Obre el fitxer recent 9 - Open Recent File 18 Obre el fitxer recent 10 - Open Recent File 19 Obre el fitxer recent 11 - Open Recent File 2 Obre el fitxer recent 12 - Open Recent File 20 Obre el fitxer recent 13 - Open Recent File 21 Obre el fitxer recent 14 - Open Recent File 22 Obre el fitxer recent 15 - Open Recent File 23 Obre el fitxer recent 16 - Open Recent File 24 Obre el fitxer recent 17 - Open Recent File 25 Obre el fitxer recent 18 - Open Recent File 26 Obre el fitxer recent 19 - Open Recent File 27 Obre el fitxer recent 20 - Open Recent File 28 Obre el fitxer recent 21 - Open Recent File 29 Obre el fitxer recent 22 - Open Recent File 3 Obre el fitxer recent 23 - Open Recent File 30 Obre el fitxer recent 24 - Open Recent File 4 Obre el fitxer recent 25 - Open Recent File 5 Obre el fitxer recent 26 - Open Recent File 6 Obre el fitxer recent 27 - Open Recent File 7 Obre el fitxer recent 28 - Open Recent File 8 Obre el fitxer recent 29 - Open Recent File 9 Obre el fitxer recent 30 + Open Recent File 10 Obre el fitxer recent 10 + Open Recent File 11 Obre el fitxer recent 11 + Open Recent File 12 Obre el fitxer recent 12 + Open Recent File 13 Obre el fitxer recent 13 + Open Recent File 14 Obre el fitxer recent 14 + Open Recent File 15 Obre el fitxer recent 15 + Open Recent File 16 Obre el fitxer recent 16 + Open Recent File 17 Obre el fitxer recent 17 + Open Recent File 18 Obre el fitxer recent 18 + Open Recent File 19 Obre el fitxer recent 19 + Open Recent File 2 Obre el fitxer recent 2 + Open Recent File 20 Obre el fitxer recent 20 + Open Recent File 21 Obre el fitxer recent 21 + Open Recent File 22 Obre el fitxer recent 22 + Open Recent File 23 Obre el fitxer recent 23 + Open Recent File 24 Obre el fitxer recent 24 + Open Recent File 25 Obre el fitxer recent 25 + Open Recent File 26 Obre el fitxer recent 26 + Open Recent File 27 Obre el fitxer recent 27 + Open Recent File 28 Obre el fitxer recent 28 + Open Recent File 29 Obre el fitxer recent 29 + Open Recent File 3 Obre el fitxer recent 3 + Open Recent File 30 Obre el fitxer recent 30 + Open Recent File 4 Obre el fitxer recent 4 + Open Recent File 5 Obre el fitxer recent 5 + Open Recent File 6 Obre el fitxer recent 6 + Open Recent File 7 Obre el fitxer recent 7 + Open Recent File 8 Obre el fitxer recent 8 + Open Recent File 9 Obre el fitxer recent 9 Open Recent Files Obre fitxers recents Open Swatch Library Obre la biblioteca de mostres Open Symbol Library Obre la biblioteca de símbols @@ -3865,42 +3865,42 @@ digits Malayalam Malaiàlam Saved Desat Saved recovery data for {title} S’han desat les dades de recuperació de {title} Saved Selection 1 Selecció desada 1 - Saved Selection 10 Selecció desada 2 - Saved Selection 11 Selecció desada 3 - Saved Selection 12 Selecció desada 4 - Saved Selection 13 Selecció desada 5 - Saved Selection 14 Selecció desada 6 - Saved Selection 15 Selecció desada 7 - Saved Selection 16 Selecció desada 8 - Saved Selection 17 Selecció desada 9 - Saved Selection 18 Selecció desada 10 - Saved Selection 19 Selecció desada 11 - Saved Selection 2 Selecció desada 12 - Saved Selection 20 Selecció desada 13 - Saved Selection 21 Selecció desada 14 - Saved Selection 22 Selecció desada 15 - Saved Selection 23 Selecció desada 16 - Saved Selection 24 Selecció desada 17 - Saved Selection 25 Selecció desada 18 - Saved Selection 3 Selecció desada 19 - Saved Selection 4 Selecció desada 20 - Saved Selection 5 Selecció desada 21 - Saved Selection 6 Selecció desada 22 - Saved Selection 7 Selecció desada 23 - Saved Selection 8 Selecció desada 24 - Saved Selection 9 Selecció desada 25 + Saved Selection 10 Selecció desada 10 + Saved Selection 11 Selecció desada 11 + Saved Selection 12 Selecció desada 12 + Saved Selection 13 Selecció desada 13 + Saved Selection 14 Selecció desada 14 + Saved Selection 15 Selecció desada 15 + Saved Selection 16 Selecció desada 16 + Saved Selection 17 Selecció desada 17 + Saved Selection 18 Selecció desada 18 + Saved Selection 19 Selecció desada 19 + Saved Selection 2 Selecció desada 2 + Saved Selection 20 Selecció desada 20 + Saved Selection 21 Selecció desada 21 + Saved Selection 22 Selecció desada 22 + Saved Selection 23 Selecció desada 23 + Saved Selection 24 Selecció desada 24 + Saved Selection 25 Selecció desada 25 + Saved Selection 3 Selecció desada 3 + Saved Selection 4 Selecció desada 4 + Saved Selection 5 Selecció desada 5 + Saved Selection 6 Selecció desada 6 + Saved Selection 7 Selecció desada 7 + Saved Selection 8 Selecció desada 8 + Saved Selection 9 Selecció desada 9 Saved Selections Seleccions desades Saved to User Defined: {} Desat a Definit per l’usuari: {} Saved View 1 Vista desada 1 - Saved View 10 Vista desada 2 - Saved View 11 Vista desada 3 - Saved View 12 Vista desada 4 - Saved View 13 Vista desada 5 - Saved View 14 Vista desada 6 - Saved View 15 Vista desada 7 - Saved View 16 Vista desada 8 - Saved View 17 Vista desada 9 - Saved View 18 Vista desada 10 + Saved View 10 Vista desada 10 + Saved View 11 Vista desada 11 + Saved View 12 Vista desada 12 + Saved View 13 Vista desada 13 + Saved View 14 Vista desada 14 + Saved View 15 Vista desada 15 + Saved View 16 Vista desada 16 + Saved View 17 Vista desada 17 + Saved View 18 Vista desada 18 Saved View 19 Vista desada 19 Saved View 2 Vista desada 2 Saved View 20 Vista desada 20 diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 5b3a784e5c..a1fda614b3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -296,7 +296,7 @@ Move Plane to Match Object Siirrä taso objektin mukaan Edit Text Muokkaa tekstiä Live Paint Elävä maalaus - Merge Yhdistä + Merge Sulauta Gap Options… Aukkojen asetukset… Gap Options Aukkojen asetukset Gap Detection Aukkojen tunnistus diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8282fb35e4..e2cbf7d54e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3294,9 +3294,9 @@ digits Malayalam Malayalam Shape Properties: Propriétés de la forme : Shaper Tool Outil Shaper Shapes Formes - Shear Déformation - Shear Tool Outil Déformation - Shear… Déformation… + Shear Cisaillement + Shear Tool Outil Cisaillement + Shear… Cisaillement… Shell Lower… Coquillage inférieur… Shell Upper… Coquillage supérieur… Shift Maj @@ -5916,7 +5916,7 @@ lighting Light Lumière Set: Jeu : Shades Tons foncés Shades of Gray Nuances de gris - Shear: Déformation : + Shear: Cisaillement : Shift+Click Maj+clic Shift+Drag Maj+glisser Shortcut Raccourci diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7a4e5dea9e..0a742330f0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -299,7 +299,7 @@ font-technology Variable Вариативные Background Contents Содержимое фона Background: Фон: Backspace Backspace - Bar Graph Tool Инструмент «Гистограмма» + Bar Graph Tool Инструмент «Линейчатая диаграмма» Baseline Базовая линия Baseline Shift Смещение базовой линии Basic Latin Основная латиница @@ -1914,7 +1914,7 @@ file-filter Templates Шаблоны Line Cut Разрезание линий Line Cut Tool Инструмент «Разрезание линий» Line Endings: Окончания линий: - Line Graph Tool Инструмент «Линейчатая диаграмма» + Line Graph Tool Инструмент «График» Line Segment Отрезок Line Segment Tool Инструмент «Отрезок» Line Segment Tool Options Параметры инструмента «Отрезок» @@ -3547,7 +3547,7 @@ digits Malayalam Малаялам Spread: Разворот: Square Квадрат Squeeze… Сжатие… - Stacked Bar Graph Tool Инструмент «Гистограмма с накоплением» + Stacked Bar Graph Tool Инструмент «Линейчатая диаграмма с накоплением» Stacked Column Graph Tool Инструмент «Гистограмма с накоплением» Stair Step Ступенчатый Standard Ligatures Стандартные лигатуры @@ -4067,7 +4067,7 @@ digits Malayalam Малаялам Zoom In Увеличить Zoom Out Уменьшить Zoom to Selection Масштаб по выделению - Zoom Tool Инструмент «Масштаб» + Zoom Tool Инструмент «Лупа» Zoom with Mouse Wheel Масштабировать колесом мыши Scroll Sideways with Cmd/Ctrl + Wheel Прокручивать по горизонтали колесом с Cmd/Ctrl Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 781ff50185..5f42591575 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -290,7 +290,7 @@ font-technology Variable Variabla Background Contents Bakgrundsinnehåll Background: Bakgrund: Backspace Backspace - Bar Graph Tool Stapeldiagramverktyg + Bar Graph Tool Verktyg för liggande stapeldiagram Baseline Baseline Baseline Shift Baslinjeförskjutning Basic Latin Grundläggande latin diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index dc42924e46..bc8f90bc90 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1001,6 +1001,26 @@ fn leading_term_agrees_within_each_catalog() { assert!(bad.is_empty(), "rows that name leading differently from the Leading field:\n{}", bad.join("\n")); } +/// A plain row whose English ends with a number, such as "Saved View 10", has that number in its +/// translation as a number of its own, so the rows of a numbered list do not swap or repeat names. +/// Messages are left out: "index must be ≥ 0" can be translated as "index must not be negative". +#[test] +fn numbered_rows_keep_their_number() { + let mut bad = Vec::new(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + for (_, src, tr) in entries.into_iter().filter(|(ctx, _, _)| ctx.is_empty()) { + let Some((_, n)) = src.rsplit_once(' ').filter(|(_, n)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())) else { + continue; + }; + if !tr.split(|c: char| !c.is_ascii_digit()).any(|run| run == n) { + bad.push(format!("{}: {src:?} → {tr:?}", l.code)); + } + } + } + assert!(bad.is_empty(), "numbered rows without their number:\n{}", bad.join("\n")); +} + /// No translated word mixes Latin, Cyrillic and Greek letters, such as a Latin "A" typed in place /// of a Cyrillic "А". A word written in one script, such as "PDF" or "X" in a Russian row, is /// allowed. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 19fcb74d61..8252477231 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -295,7 +295,7 @@ font-technology Variable Варіативні Background Contents Вміст фону Background: Фон: Backspace Backspace - Bar Graph Tool Інструмент «Гістограма» + Bar Graph Tool Інструмент «Лінійчата діаграма» Baseline Базова лінія Baseline Shift Зміщення базової лінії Basic Latin Основна латиниця @@ -1919,7 +1919,7 @@ file-filter Templates Шаблони Line Cut Розрізання ліній Line Cut Tool Інструмент «Розрізання ліній» Line Endings: Закінчення ліній: - Line Graph Tool Інструмент «Лінійчаста діаграма» + Line Graph Tool Інструмент «Графік» Line Segment Відрізок Line Segment Tool Інструмент «Відрізок» Line Segment Tool Options Параметри інструменту «Відрізок» @@ -2584,7 +2584,7 @@ diagnostics ui інтерфейс Perspective Grid Settings Параметри сітки перспективи Perspective Grid Tool Інструмент «Сітка перспективи» Perspective Plane Options… Параметри площини перспективи… - Perspective Selection Tool Інструмент "Виділення в перспективі" + Perspective Selection Tool Інструмент «Виділення в перспективі» Phone 390×844 Телефон 390×844 Picas Піки Pie Graph Tool Інструмент «Кругова діаграма» @@ -3554,8 +3554,8 @@ effect Points Точки Spread: Розворот: Square Квадрат Squeeze… Стиснення… - Stacked Bar Graph Tool Інструмент "Гістограма з накопиченням" - Stacked Column Graph Tool Інструмент "Гістограма з накопиченням" + Stacked Bar Graph Tool Інструмент «Лінійчата діаграма з накопиченням» + Stacked Column Graph Tool Інструмент «Гістограма з накопиченням» Stair Step Ступінчастий Standard Ligatures Стандартні лігатури Standard Vertical Roman Alignment Стандартне римське вертикальне вирівнювання @@ -4075,7 +4075,7 @@ effect Points Точки Zoom In Збільшити Zoom Out Зменшити Zoom to Selection Масштаб виділення - Zoom Tool Інструмент «Масштаб» + Zoom Tool Інструмент «Лупа» Zoom with Mouse Wheel Масштабувати колесом миші Scroll Sideways with Cmd/Ctrl + Wheel Прокручувати по горизонталі колесом із Cmd/Ctrl Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0abd3c75c9..c68cc185a8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2343,7 +2343,7 @@ digits Hindi Hindi Medium Thumbnail View Chế độ hình thu nhỏ vừa Medium Thumbnails Hình thu nhỏ vừa Menu Dialog Hộp thoại menu - Merge Hợp nhất + Merge Gộp Merge colors into one row Hợp nhất màu vào một hàng Merge Graphic Styles Hợp nhất kiểu đồ họa Merge Graphic Styles… Hợp nhất kiểu đồ họa… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 41c5d9a546..48ce9a041e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -876,7 +876,7 @@ antiAlias Sharp 锐利 Drop Shadow 制作阴影 Drop Shadow… 阴影… Duotone Gradients 双色调渐变 - Duplicate 复制 + Duplicate 创建副本 Duplicate and Offset 10 pt 复制并偏移 10 pt Duplicate Artboard 复制画板 Copy Artboard 拷贝画板 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index f06eed2e13..59f80fa58b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5173,7 +5173,7 @@ digits Malayalam 馬來亞拉姆數字 Zoom In 放大顯示 Zoom Out 縮小顯示 Zoom to Selection 縮放至選取範圍 - Zoom Tool 縮放工具 + Zoom Tool 縮放顯示工具 Zoom with Mouse Wheel 使用滑鼠滾輪縮放 Scroll Sideways with Cmd/Ctrl + Wheel 使用 Cmd/Ctrl + 滾輪水平捲動 Scrub Numeric Fields by Dragging 拖曳以調整數值欄位 diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 4e02180017..8847e13034 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -2680,6 +2680,26 @@ mod tests { assert!(d.str("__message").contains("was already used by Type › Fit Headline (type.fitHeadline) "), "{}", d.str("__message")); } + /// No two entries of Keyboard Shortcuts have the same name in any UI language: each catalog + /// translates two different English names two different ways. + #[test] + fn no_two_entries_have_the_same_name_in_any_language() { + let all = entries(); + let mut shared = vec![]; + let previous = crate::i18n::current(); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let mut by_name: HashMap> = HashMap::new(); + for e in all.iter() { + by_name.entry(shown_name(e)).or_default().push(e.key.as_str()); + } + shared.extend(by_name.into_iter().filter(|(_, keys)| keys.len() > 1).map(|(name, keys)| (lang.code(), name, keys))); + } + crate::i18n::set_current(previous); + shared.sort(); + assert!(shared.is_empty(), "{} names: {shared:#?}", shared.len()); + } + /// Two filter plug-ins with the same name in the same menu show their ids, and a third whose /// name is one of those names with the id stays apart from it. A filter with that name in /// another menu, or with a label that differs by its "…", shows no id. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1e96f34ed8..11de33d3fc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -920,6 +920,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The errors of the blend spine commands (Move Spine Point, Reshape Spine Segment, Add Spine Point and Delete Spine Point) show in the status bar in the interface language: each has a row in every catalog that translates all status and error messages and in Bulgarian (`blend_spine_param_errors_are_translated`). - 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 an SVG filter that the New or Edit button of Apply SVG Filter or an `svg.filter` effect refuses show in the status bar in the interface language: XML that cannot be read, a missing or too long id, an element or event attribute a filter does not take, an image that is not a `data:` URL, and the limits on primitives, `numOctaves`, `order`, `radius`, `stdDeviation`, `kernelUnitLength`, image pixels, nesting and size. Each has a row in every catalog that translates all status and error messages, and the limits, element and attribute names and the XML parser's position are kept as written (`svg_filter_refusals_are_translated_in_every_complete_catalog`, `svg_filter_refusals_translate_with_their_values`). Items side by side in a menu show different labels in every interface language (Effect › 3D and Materials › Revolve… and Rotate… in Turkish and Bulgarian, Effect › Warp and Distort, the Pathfinder effects, the Warp styles, Window › Attributes and Properties, and the whitespace characters), and no menu item shows a command id in place of its label (`menu_items_side_by_side_have_different_labels`, `menu_items_never_show_an_id`). + - Keyboard Shortcuts shows each entry under a name of its own in every interface language: the Scale and Zoom tools, the Column and Bar Graph tools and their stacked forms, the Pucker and Wrinkle tools, the Shear and Warp tools, Edit › Copy and Duplicate, Pathfinder Unite and Merge, and View › Saved View 2 to 17 have different names in every catalog (`no_two_entries_have_the_same_name_in_any_language`). The Line Graph tool reads as a line graph in Russian and Ukrainian, and in every catalog a row whose English name ends with a number keeps that number (`numbered_rows_keep_their_number`). - 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`). - 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`). From 64662b435b545bd6d6f47553f92032bba38a9055 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:32:04 -0800 Subject: [PATCH 020/138] Scripts: a file opened under a withdrawn grant is not read When a run evaluated code that withdrew a kept grant, a File opened under that grant still gave the bytes it held to read, readln and readch, and seek to the end showed its length. Those calls now give Script file access denied and set error, and eof is true. docs/mcp.md says so. --- crates/engine/src/script/files.rs | 37 +++++++++++++++++++++++----- crates/engine/src/tests/script_io.rs | 24 ++++++++++++++++++ crates/js/src/file_classes.rs | 7 +++++- docs/mcp.md | 3 ++- 4 files changed, 63 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ba1bc60827..be813e3a74 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -420,6 +420,12 @@ impl Disk { } } } + // Objects that hold a file the run may no longer read give none of it. + for o in self.open.values_mut() { + if o.read_from.as_deref().is_some_and(|p| !self.scope.allows(p)) { + o.unreadable = true; + } + } } /// Writes the evaluated code this run ran into the grants it kept with Always, so a later run @@ -1391,6 +1397,9 @@ struct Open { /// The grant the file was opened under was withdrawn while its changes could not be written: /// they are written again when the run ends, and the object takes no more writes. withdrawn: bool, + /// The run may no longer read the file the object holds: `read`, `readln`, `readch` and `seek` + /// give [`ACCESS_DENIED`], and `eof` is true. + unreadable: bool, } impl Open { @@ -1410,7 +1419,17 @@ impl Open { } else { (Encoding::Cp1252, 0) }; - Some(Self { bytes, pos, encoding, name: encoding.name().to_string(), target: None, read_from: None, dirty: false, withdrawn: false }) + Some(Self { + bytes, + pos, + encoding, + name: encoding.name().to_string(), + target: None, + read_from: None, + dirty: false, + withdrawn: false, + unreadable: false, + }) } /// Writes `text` at the position, over what is there and past the end, when it takes at most @@ -1593,6 +1612,12 @@ fn with_open(host: &Host, a: &[Data], f: impl FnOnce(&mut Open) -> Data) -> Data } } +/// [`with_open`] for a call that reads what the file holds: `{error}` [`ACCESS_DENIED`] when the +/// run may no longer read it. +fn with_readable(host: &Host, a: &[Data], f: impl FnOnce(&mut Open) -> Data) -> Data { + with_open(host, a, |file| if file.unreadable { error(ACCESS_DENIED) } else { f(file) }) +} + /// The first two arguments as path text, refused with a `RangeError` when either is too long. fn two_paths(a: &[Data]) -> Result<(String, String), HostError> { let (path, base) = (arg_text(a, 0), arg_text(a, 1)); @@ -2031,20 +2056,20 @@ pub(crate) fn dialog_filters(filter: &str) -> Vec<(String, Vec)> { fn read(host: &Host, a: &[Data]) -> Result { let max = arg_number(a, 1).filter(|n| *n >= 0.0).map(|n| n as usize); - Ok(with_open(host, a, |f| text_result(f.read(max)))) + Ok(with_readable(host, a, |f| text_result(f.read(max)))) } fn readln(host: &Host, a: &[Data]) -> Result { - Ok(with_open(host, a, |f| text_result(f.read_line()))) + Ok(with_readable(host, a, |f| text_result(f.read_line()))) } fn readch(host: &Host, a: &[Data]) -> Result { - Ok(with_open(host, a, |f| text_result(f.read_char()))) + Ok(with_readable(host, a, |f| text_result(f.read_char()))) } fn seek(host: &Host, a: &[Data]) -> Result { let (Some(pos), Some(mode)) = (arg_number(a, 1), arg_number(a, 2)) else { return Err(HostError::Type(BAD_SEEK.into())) }; - Ok(with_open(host, a, |f| { + Ok(with_readable(host, a, |f| { let base = match mode as u8 { 1 => f.pos as f64, 2 => f.bytes.len() as f64, @@ -2066,7 +2091,7 @@ fn tell(host: &Host, a: &[Data]) -> Result { } fn eof(host: &Host, a: &[Data]) -> Result { - Ok(Data::Bool(host.disk.borrow().open.get(&handle(a)).is_none_or(|f| f.pos >= f.bytes.len()))) + Ok(Data::Bool(host.disk.borrow().open.get(&handle(a)).is_none_or(|f| f.unreadable || f.pos >= f.bytes.len()))) } fn encoding(host: &Host, a: &[Data]) -> Result { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 9b9cee9439..ae782692f3 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1854,6 +1854,30 @@ fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { let _ = std::fs::remove_dir_all(base); } +/// A file opened for reading under a kept grant that new code withdraws gives no more of what it +/// holds. +#[test] +fn script_files_open_under_a_withdrawn_grant_are_not_read() { + let base = folder("grantwithdrawnread"); + let dir = base.join("picked"); + write(&dir.join("in.txt"), b"secret"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('r')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ var a = f.readch(); eval('1'); var r = f.read(), e = f.error; f.error = ''; vc.log([a, r, e, f.eof, f.seek(0, 2), f.error, f.tell()]); }}", + dir.join("in.txt").to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["s", "", DENIED, true, false, DENIED, 1]])); + let _ = std::fs::remove_dir_all(base); +} + /// The folder that holds the settings is kept out of every grant: a pick there gives `null` with the /// error, a grant written into the grants file for it is not taken, and the script cannot write the /// grants file through its data folder. diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f1bba51291..c962bf9679 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -887,7 +887,12 @@ fn seek(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult return Err(i.throw(ErrorType::Range, "File.seek: the mode must be 0, 1 or 2")); } let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) }; - host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)]) + let r = host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)])?; + // A seek the host refuses sets `error` and gives `false`. + if !outcome(i, o, &r)? { + return Ok(Value::Bool(false)); + } + Ok(r) } fn tell(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { diff --git a/docs/mcp.md b/docs/mcp.md index 1c49dde6c9..4562889e7e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2458,7 +2458,8 @@ VectorCraft writes files by these rules of its own: asks again. It is offered only for a script run from a file. The grant also keeps the SHA-256 of each source the run evaluated up to its end (a file `$.evalFile` ran, a string given to `eval` or `Function`, at most 256). A later run loses the grant before it evaluates a source the grant does not list, and from the start when its - `#targetengine` engine holds code the grant does not list, such as another script's. A kept grant stays on the + `#targetengine` engine holds code the grant does not list, such as another script's. A file opened under a + grant the run loses gives `Script file access denied` when it is read or `seek` is called after that. A kept grant stays on the real path that was allowed: when that path now leads elsewhere, through a link put in its place or in a folder above it, the grant is not used. - A command a script runs with `vc.run` reads and writes files only where the script's `File` and `Folder` objects From 1bf936defa9465d3f60d82ad2d2b8edbe17f00b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:05:20 -0800 Subject: [PATCH 021/138] Tests: the Enter-denies test removes its temporary folder --- crates/ui-egui/src/tests/script_run.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 202ac35c6f..882799385e 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -540,7 +540,8 @@ fn enter_in_a_scripts_file_dialog_denies() { let source = "vc.log(Folder.selectDialog('Pick'));"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); script_runs::poll(&mut app); - app.script_picked = vec![folder("enterdeny").to_string_lossy().into_owned()]; + let dir = folder("enterdeny"); + app.script_picked = vec![dir.to_string_lossy().into_owned()]; let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; @@ -551,6 +552,7 @@ fn enter_in_a_scripts_file_dialog_denies() { assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::PICKER_KIND), "the dialog closes"); finish(&mut app); assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(&dir); } /// Enter on the file dialog's focused Choose… button goes to that button, which opens the folder From 0854e12332785c2795124880e807653157cf3a0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 02:28:54 -0800 Subject: [PATCH 022/138] i18n: Georgian translates the messages no catalog had a row for The untranslated report listed 55 messages that none of the 23 message-checked catalogs translate. Open pull requests add Georgian rows for 53 of them; ka.tsv now has rows for the other two: document.activate's "`index` must be a whole number" and PDF export's warning about knockout groups with too many translucent elements. The report read the knockout warning wrongly. Its literal ends a line with `\`, which Rust drops along with the line break and the next line's leading whitespace, but the scanner kept both, so no catalog row could match the text the program shows. The scanner now joins such a literal as Rust does, with LF and CRLF line endings (message_scan_joins_a_literal_continued_on_the_next_line). Docs: docs/localization-parity.md (Georgian row, counted 2026-11-14), docs/target-app-parity.md. --- crates/ui-egui/src/i18n/ka.tsv | 4 ++++ crates/ui-egui/src/i18n/tests.rs | 19 ++++++++++++++++++- docs/localization-parity.md | 2 +- docs/target-app-parity.md | 1 + 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index fc649cd87a..1ff28d55bd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7612,3 +7612,7 @@ font-script Japanese იაპონური Grommets ლუვერები Grommet Inset ლუვერების დაშორება კიდიდან Diameter დიამეტრი + +# Messages of document.activate and of PDF export's knockout groups. +@msg `index` must be a whole number `index` უნდა იყოს მთელი რიცხვი +@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ერთმანეთზე გადაფარებული ნახევრად გამჭვირვალე ელემენტია, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები მთლიანად ჩაკვეთენ იმას, რასაც ფარავენ diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 4f9f03e5f6..68acecb418 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2702,6 +2702,21 @@ fn run() -> Result<()> { assert!(source_messages(code, &[], &Default::default()).is_empty()); } +/// A message split over lines with a `\` at the end of a line is read as Rust reads it: the line +/// break and the next line's leading whitespace are dropped, with LF and CRLF line endings, in a +/// constant and in a literal an error takes. +#[test] +fn message_scan_joins_a_literal_continued_on_the_next_line() { + for eol in ["\n", "\r\n"] { + let declared = format!("const LONG: &str = \"too many elements: \\{eol} drawn as a plain group\";{eol}"); + let consts = std::collections::BTreeMap::from_iter(str_consts(&declared).into_iter().map(|(name, value)| (name, vec![value]))); + assert_eq!(consts.get("LONG"), Some(&vec!["too many elements: drawn as a plain group".to_string()]), "{eol:?}"); + let code = format!("fn run() {{ let _ = Err(\"the file \\{eol}\t\t is too large\"); let _ = Err(LONG); }}{eol}"); + let found: std::collections::BTreeSet = source_messages(&code, &[], &consts).into_iter().collect(); + assert_eq!(found.iter().collect::>(), ["the file is too large", "too many elements: drawn as a plain group"], "{eol:?}"); + } +} + /// The scan reads the message of each of the plug-in host's [`ERROR_HELPERS`]: a literal, a /// `format!` string with or without a `&` before it, after the location of `out_err` (a /// `format!` string too), the number and range of `in_range`, the number and location of `unit`, @@ -4520,7 +4535,8 @@ fn without_test_module(text: &str) -> &str { text } -/// The text of a string literal whose opening quote was just read, escapes resolved. +/// The text of a string literal whose opening quote was just read, escapes resolved. A `\` at the +/// end of a line drops the line break and the whitespace that starts the next line, as Rust does. fn string_literal(s: &str) -> Option { let mut out = String::new(); let mut it = s.chars(); @@ -4530,6 +4546,7 @@ fn string_literal(s: &str) -> Option { '\\' => match it.next()? { 'n' => out.push('\n'), 't' => out.push('\t'), + '\n' | '\r' => it = it.as_str().trim_start_matches([' ', '\t', '\n', '\r']).chars(), c => out.push(c), }, c => out.push(c), diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 9080695a8e..50a2c8d18f 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -66,7 +66,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Swedish | `sv` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one/other plurals | full; native review welcome | | Bulgarian | `bg` | 5,245 rows, 763 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | full; native review welcome | -| Georgian | `ka` | 5,200 rows (counted 2026-10-21): menus, panels, dialogs, plurals (one count-neutral form) and messages, tested complete; reviewed by a native speaker | full | +| Georgian | `ka` | 7,512 rows, 1,640 of them `@msg` and 48 `@msgplural` (counted 2026-11-14): menus, panels, dialogs and plurals (one count-neutral form); the untranslated report lists 1,927 missing Georgian messages, and 53 messages that no language has a row for | full | | Turkish | `tr` | 5,558 rows, 880 of them `@msg` (counted 2026-10-28); 6 menu strings and the default swatch names still fall back to English | full | | Indonesian | `id` | 5,531 rows, 788 of them `@msg` (counted 2026-10-28): menus and `tl!` literals complete when counted; its messages are partial; one plural form | full | | Catalan | `ca` | 5,626 rows, 881 of them `@msg` (counted 2026-10-28): menus, `tl!` literals and messages complete when counted; one/other plurals; every `ca-*` locale resolves here | full; AI-drafted, native review welcome | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e36c7f318..3aa4727511 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -903,6 +903,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). + - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog (`ka`) translates the two messages the report then listed as missing from every language: `document.activate`'s `` `index` must be a whole number `` and PDF export's warning about knockout groups with too many translucent elements (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). See [localization-parity.md](localization-parity.md). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). - The Traditional Chinese catalog (`crates/ui-egui/src/i18n/zh-hant.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Traditional Chinese messages: open #7211, #7116 and #7330 add the rows for 38 of them, and the other 2 have no row in any catalog. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. From 6864086cda15fa4fad3f3c920550bf7b39cb3f80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 02:50:41 -0800 Subject: [PATCH 023/138] i18n: keep bracketed field names untranslated in fr rows --- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6fc56e60cb..83effda4cc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7593,7 +7593,7 @@ breakText Glyphs Glyphes @msg `alignOn` must be a string `alignOn` doit être une chaîne @msg `align` is start, center or end `align` vaut start, center ou end @msg `align` must be a string `align` doit être une chaîne -@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` doit être une liste de paires [sous-tracé, point d’ancrage] +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` doit être une liste de paires [subpath, anchor] @msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {k} @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @@ -7657,7 +7657,7 @@ breakText Glyphs Glyphes @msg `fidelity` must be from {lo} to {hi} pt `fidelity` doit être compris entre {lo} et {hi} pt @msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files` doit contenir de 1 à 1000 chemins de fichiers de police trouvés par la dernière recherche text.findFontFiles @msg `focal` and `radius` cannot be used together `focal` et `radius` ne peuvent pas être utilisés ensemble -@msg `focal` must be an array of [subpath, anchor] pairs `focal` doit être une liste de paires [sous-tracé, point d’ancrage] +@msg `focal` must be an array of [subpath, anchor] pairs `focal` doit être une liste de paires [subpath, anchor] @msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal` désigne [{si}, {ai}], qui n’est pas un point d’ancrage du tracé @msg `folder` must be an absolute folder path `folder` doit être le chemin absolu d’un dossier @msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes` doit être un objet de balises d’axe et de valeurs, comme {"wght"} From 74dd0fc9fe0c2a4a4da89b73ed2a78627fcdf5f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 02:53:22 -0800 Subject: [PATCH 024/138] Type: typing kept when a dialog or a panel previews keeps its warning and selection With Performance > Real-time Drawing and Editing off, the Type tool's typing waits to be applied until its session ends. Dialogs and panels that start a preview now begin it through a path that keeps the typing as its own undo step and shows the warning of the typing's preview in the status bar. When the typing cannot be kept, the effect dialogs' Preview, the Color Picker, Swatch Options and the font menus' preview show the error in the status bar and do not preview. - The font menus, the Effect Gallery, a paint for the characters the Type tool selected and an inline graphic inserted while typing apply the deferred typing first instead of dropping it. - The Character, Paragraph and Tabs panels, Bullets and Numbering, Justification and the inline graphic read the Type tool's selection in the typed text, after the typing is applied. - A live panel slider shows an error from ending its preview. --- crates/engine/src/cmd/inline.rs | 35 ++++--- crates/engine/src/cmd/textedit.rs | 5 +- crates/engine/src/session/edit.rs | 15 +++ crates/engine/src/tests/inline.rs | 25 +++++ crates/engine/src/tests/prefs.rs | 29 ++++++ crates/engine/src/tests/textedit.rs | 35 +++++++ crates/ui-egui/src/app/commands.rs | 26 +++++ .../ui-egui/src/dialogs/brush_replace_art.rs | 2 +- .../ui-egui/src/dialogs/bullets_numbering.rs | 3 +- crates/ui-egui/src/dialogs/color_picker.rs | 9 +- crates/ui-egui/src/dialogs/effect.rs | 13 ++- crates/ui-egui/src/dialogs/effect_gallery.rs | 44 ++++++++- crates/ui-egui/src/dialogs/form.rs | 99 ++++++++++++++++++- crates/ui-egui/src/dialogs/justification.rs | 3 +- crates/ui-egui/src/dialogs/simplify_slider.rs | 2 +- crates/ui-egui/src/dialogs/swatch_options.rs | 6 +- crates/ui-egui/src/font_menu.rs | 3 +- crates/ui-egui/src/panels.rs | 8 +- crates/ui-egui/src/panels/character.rs | 27 +++-- crates/ui-egui/src/panels/paragraph.rs | 3 +- crates/ui-egui/src/panels/tabs.rs | 3 +- docs/target-app-parity.md | 1 + 22 files changed, 348 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index db3e929952..bb4e4f2e8e 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -46,18 +46,22 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { }; let len = edit::runs_len(&t.runs); let from_tool = editing == Some(id); - let (a, b) = match p.get("at") { - None | Some(Value::Null) if from_tool => { - let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); - let (x, y) = (g("start"), g("end")); - (x.min(y), x.max(y)) - } - None | Some(Value::Null) => (len, len), - Some(v) => { - let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; - (at, at) - } + // Where the graphic goes in text `len` bytes long. + let range = |len: usize| -> Result<(usize, usize)> { + Ok(match p.get("at") { + None | Some(Value::Null) if from_tool => { + let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); + let (x, y) = (g("start"), g("end")); + (x.min(y), x.max(y)) + } + None | Some(Value::Null) => (len, len), + Some(v) => { + let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize; + (at, at) + } + }) }; + let (mut a, mut b) = range(len)?; let symbol = match str_param(p, "symbol") { Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(), Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))), @@ -75,11 +79,16 @@ fn insert_inline(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => 0.0, Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?, }; - // A typing session ends first: the insertion is a step of its own. + // A typing session ends first: the insertion is a step of its own. Typing that Real-time + // Drawing off left unapplied is applied first, and the caret is read in the typed text. let typing = tool.get("typing").and_then(Value::as_bool) == Some(true); if typing && from_tool { s.set_tool_option("commitTyping", &Value::Bool(true)); - s.commit_interaction()?; + super::settle_interaction(s)?; + let NodeKind::Text(t) = &s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.kind else { + return Err(bad(C, format!("node {} is not text", id.0))); + }; + (a, b) = range(edit::runs_len(&t.runs))?; } let caret = s.edit("Insert Inline Symbol", |d, _| { let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) }; diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 0fd7c7d97d..b4a5c9a6e1 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1808,13 +1808,14 @@ enum Step { BaselineShift, } -/// The Type tool's selected text while it edits (its typing session ends first: one undo step). +/// The Type tool's selected text while it edits (its typing session ends first: one undo step, +/// with typing that Real-time Drawing off left unapplied applied first). pub(crate) fn editing_range(s: &mut Session) -> Result> { let o = s.tool_options(); let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; if super::edit::typing_in_progress(s) { s.set_tool_option("commitTyping", &Value::Bool(true)); - s.commit_interaction()?; + super::edit::settle_interaction(s)?; } let at = |k: &str| byte_param(&o, k).unwrap_or(0); Ok(Some((id, at("start"), at("end")))) diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 73977f7d64..9679bbe2a0 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -255,6 +255,21 @@ impl Session { (r, settled) } + /// [`Session::begin_interaction`] for a dialog or a panel that starts a preview → the warnings + /// of the preview that keeping typing in progress applied, for its status bar. + pub fn begin_interaction_warned(&mut self, label: &str) -> Result> { + let (r, settled) = self.collect_settled_warnings(|s| s.begin_interaction(label)); + r.map(|()| settled) + } + + /// Keep typing in progress as one undo step, applying the preview Real-time Drawing off left + /// unapplied, and end the Type tool's typing session → the applied preview's warnings. Nothing + /// changes when no typing is in progress. + pub fn keep_typing(&mut self) -> Result> { + let (r, settled) = self.collect_settled_warnings(|s| if cmd::typing_in_progress(s) { cmd::settle_interaction(s) } else { Ok(()) }); + r.map(|()| settled) + } + pub fn begin_interaction(&mut self, label: &str) -> Result<()> { if self.script_running() { return Err(EngineError::Busy); diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index f7c72956ad..4e815ddb94 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -142,6 +142,31 @@ fn type_tool_inserts_at_its_caret_and_deletes_the_graphic_whole() { assert_eq!(inline_count(&obj(&s, id)), 1); } +/// With Performance › Real-time Drawing and Editing off, the typing waits for its session to end: +/// a graphic inserted while typing applies it first, as a step of its own, and goes in at the +/// caret after it. +#[test] +fn inserting_while_deferred_typing_keeps_the_typing() { + let mut s = session(); + s.prefs.real_time_drawing = false; + // The new type starts empty: the caret after "Pay " is past the end of the text until the + // typing is applied. + s.prefs.placeholder_text = false; + circle_symbol(&mut s, "Mana", 10.0); + s.execute("symbol.setCurrent", &json!({"name": "Mana"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0]; + s.tool_text("Pay ", v).unwrap(); + s.execute("text.insertInline", &json!({})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), format!("Pay {INLINE_CHAR}")); + let labels: Vec = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!(labels[labels.len() - 2..], ["Typing", "Insert Inline Symbol"], "{labels:?}"); +} + #[test] fn inline_graphics_follow_their_symbol() { let mut s = session(); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index d88b8250a2..42809b6953 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -2586,6 +2586,35 @@ fn settling_typing_for_a_tool_shows_its_preview_warning() { s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap(); } +/// Typing kept as its own step when a dialog or a panel begins its preview, or when the font menus +/// end the typing session, returns its applied preview's warning for the status bar. A preview +/// without a warning returns none, and with no typing in progress nothing is kept and no step is +/// added. +#[test] +fn settling_typing_for_a_dialog_returns_its_preview_warning() { + let warned = |w: &[String]| w.iter().any(|m| m.contains("type")); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let mut s = deferred_bloat("Typing", true, "selection"); + let before = steps(&s); + let w = s.begin_interaction_warned("Offset Path").unwrap(); + assert!(warned(&w), "{w:?}"); + assert_eq!(steps(&s), before + 1, "the typing is a step of its own"); + assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.as_str()), Some("Offset Path")); + + let mut s = deferred_bloat("Typing", true, "selection"); + let w = s.keep_typing().unwrap(); + assert!(warned(&w), "{w:?}"); + assert!(!s.in_interaction()); + assert_eq!(steps(&s), before + 1); + let w = s.keep_typing().unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(steps(&s), before + 1, "nothing in progress adds no step"); + + let mut s = deferred_bloat("Typing", false, "selection"); + let w = s.begin_interaction_warned("Offset Path").unwrap(); + assert!(w.is_empty(), "{w:?}"); +} + /// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does /// not replace full-resolution pixels already in the document. #[test] diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index adcc35d352..79f0503d1e 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3038,6 +3038,41 @@ fn a_previewed_transform_while_typing_keeps_the_typing() { assert!((left(&s, id) - 400.0).abs() < 1e-6); } +/// With Performance › Real-time Drawing and Editing off, the typing is applied when its session +/// ends. Ending it for another edit applies it first, as a step of its own: a dialog or a panel +/// beginning its preview, the font menus ([`Session::keep_typing`]), a paint for the selected +/// characters. +#[test] +fn ending_deferred_typing_for_another_edit_keeps_the_typing() { + let typed = |end: &dyn Fn(&mut Session)| { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "Hello", "the typing waits for its session to end"); + let steps = undo_labels(&s).len(); + end(&mut s); + assert_eq!(obj(&s, id).plain_text(), "Hello world"); + assert_eq!(undo_labels(&s)[steps], "Typing", "{:?}", undo_labels(&s)); + }; + typed(&|s| { + assert!(s.begin_interaction_warned("Fill Color").unwrap().is_empty()); + s.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + s.commit_interaction().unwrap(); + }); + typed(&|s| { + assert!(s.keep_typing().unwrap().is_empty()); + assert!(!s.in_interaction()); + }); + typed(&|s| { + s.execute("paint.setFill", &json!({"color": "#00a000"})).unwrap(); + }); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 50c7b1be30..ff2b5017bc 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -458,4 +458,30 @@ impl VectorcraftApp { pub fn status(&mut self, s: impl Into) { self.ui.status = s.into(); } + + /// Begin the interaction a dialog or a panel previews on. Typing in progress is kept as its own + /// undo step first, and the warning of the preview that keeping it applied shows in the status + /// bar, as it does when a tool's drag begins. On an error no interaction begins, so the caller + /// runs no preview. + pub(crate) fn begin_interaction(&mut self, label: &str) -> Result<(), String> { + let warnings = self.session.begin_interaction_warned(label).map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Keep typing in progress as one undo step and end the Type tool's typing session, with the + /// typing that Real-time Drawing off left unapplied applied first; its warning shows in the + /// status bar. + pub(crate) fn keep_typing(&mut self) -> Result<(), String> { + let warnings = self.session.keep_typing().map_err(|e| e.to_string())?; + self.show_warnings(warnings); + Ok(()) + } + + /// Each warning in the status bar in turn, as the tool's status requests show; the last stays. + fn show_warnings(&mut self, warnings: Vec) { + for w in warnings { + self.status(w); + } + } } diff --git a/crates/ui-egui/src/dialogs/brush_replace_art.rs b/crates/ui-egui/src/dialogs/brush_replace_art.rs index cc1a08b251..f1ebf1083f 100644 --- a/crates/ui-egui/src/dialogs/brush_replace_art.rs +++ b/crates/ui-egui/src/dialogs/brush_replace_art.rs @@ -44,7 +44,7 @@ pub fn replace(app: &mut VectorcraftApp, name: &str, ids: &[u64]) { return; } // A preview on a copy of the document checks the art without changing anything. - if !app.session.in_interaction() && app.session.begin_interaction("Replace Brush Art").is_ok() { + if !app.session.in_interaction() && app.begin_interaction("Replace Brush Art").is_ok() { let checked = app.session.preview("brush.replaceArt", ¶ms); // The interaction began above, on the active document: ending it puts that document back // as it was, and can fail only when no document is open, when there is nothing to put back. diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 43f15edbb8..5dd09dd8f3 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -85,8 +85,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app) { targets = json!({"ids": [id.0], "start": a, "end": b}); } let mut values = Map::new(); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index c4ef1a984d..9ce3085917 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -482,13 +482,18 @@ fn preview(app: &mut VectorcraftApp, d: &mut Dialog) { if unchanged || !selected { return; } - let _ = app.session.begin_interaction(if artboard { + let label = if artboard { "Artboard Options" } else if d.bool("stroke") { "Stroke Color" } else { "Fill Color" - }); + }; + // A failure to begin (typing that can't be kept) shows, and nothing previews. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return; + } if let Err(e) = app.session.preview(cmd, ¶ms) { app.status(e.to_string()); } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 777c872494..b5e3f5a174 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -41,7 +41,7 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } else if !app.session.in_interaction() && d.fields.get(TRIED) != Some(¶ms) { // Waits for another interaction to end: trying inside it would replace its preview and // cancel it. A failure to begin leaves no interaction: the preview below then reports it. - let _ = app.session.begin_interaction(&d.str("__label")); + let _ = app.begin_interaction(&d.str("__label")); match app.session.preview(cmd, ¶ms) { Ok(_) => { d.fields.remove(form::REFUSED); @@ -253,9 +253,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("preview".into(), json!(pv)); if pv && (changed || pv_changed || !app.session.in_interaction()) { let label = d.str("__label"); - let _ = app.session.begin_interaction(&label); - let (cmd, p) = command(d); - let _ = app.session.preview(cmd, &p); + // A failure to begin (typing that can't be kept) shows, and nothing previews. + match app.begin_interaction(&label) { + Ok(()) => { + let (cmd, p) = command(d); + let _ = app.session.preview(cmd, &p); + } + Err(e) => app.status(e), + } } else if !pv && pv_changed { let _ = app.session.cancel_interaction(); } diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 03c862171d..9b9851fb2e 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -215,11 +215,20 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value { } /// Live canvas preview of the stack (`command.batch` would settle the dialog interaction each frame). +/// Typing in progress is kept as its own undo step first; only the gallery's own earlier preview is +/// canceled. fn preview_stack_on_canvas(app: &mut VectorcraftApp, stack: &[StackEntry]) { + if let Err(e) = app.keep_typing() { + app.status(e); + return; + } if app.session.in_interaction() { let _ = app.session.cancel_interaction(); } - let _ = app.session.begin_interaction("Effect Gallery"); + if let Err(e) = app.begin_interaction("Effect Gallery") { + app.status(e); + return; + } for (i, entry) in stack.iter().enumerate() { let params = Value::Object(entry.params.clone()); if app.run("effect.apply", json!({ "effect": entry.effect, "params": params })).is_err() { @@ -666,6 +675,39 @@ mod tests { assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects.is_empty()); } + /// With Real-time Drawing off, typing in progress when the stack previews is kept as a step of + /// its own, not canceled with the gallery's earlier preview. + #[test] + fn stack_preview_keeps_typing_in_progress() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let id = vectorcraft_doc::NodeId(id); + let v = vectorcraft_engine::ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + let plain = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + }; + assert_eq!(plain(&app), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + app.run("ui.effectGalleryDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("stack".into(), json!([{ "effect": "artistic.cutout", "visible": true, "params": { "levels": 3 } }])); + frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Effect Gallery")); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(plain(&app), "Hello world"); + } + #[test] fn stack_ok_is_one_undo_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 033e194e50..45f73b12cb 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -1040,7 +1040,12 @@ fn preview_or_rollback(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: & pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option { let mut result = None; if d.fields.get(PREVIEWED) != Some(¶ms) || !app.session.in_interaction() { - let _ = app.session.begin_interaction(label); + // A failure to begin (typing that can't be kept) shows, and nothing previews on the + // interaction still in progress. + if let Err(e) = app.begin_interaction(label) { + app.status(e); + return None; + } match app.session.preview(cmd, ¶ms) { Ok(r) => { d.fields.remove(REFUSED); @@ -1167,6 +1172,98 @@ mod plugin_field_tests { } } +#[cfg(test)] +mod settled_typing_tests { + use super::*; + use vectorcraft_engine::{Session, ViewInfo}; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + /// An app with Real-time Drawing off and " world" typed after "Hello", not yet applied → the + /// type's id. + fn typing(app: &mut crate::VectorcraftApp) -> u64 { + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let id = app.run("text.create", json!({"x": 100, "y": 100, "text": "Hello", "size": 20})).unwrap()["id"].as_u64().unwrap(); + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(" world", v).unwrap(); + id + } + + fn plain(app: &crate::VectorcraftApp, id: u64) -> String { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } + } + + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts + /// from it; the status bar shows the warning of the typing's preview that keeping it applied. + #[test] + fn a_dialog_preview_keeps_the_typing_and_shows_its_warning() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + assert_eq!(plain(&app, id), "Hello", "the typing waits"); + let steps = app.session.active().unwrap().history.undo.len(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "the typing is a step of its own"); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Fill Color")); + + // The typing's deferred preview warns that type is skipped (as Bloat does with type selected). + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 300, "y": 200, "text": "Hi"})).unwrap(); + app.run("select.set", json!({"ids": [rect["id"], text["id"]]})).unwrap(); + app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap(); + app.session.begin_interaction("Typing").unwrap(); + let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0}); + app.session.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p)); + app.ui.status.clear(); + let mut d = Dialog::new("test", json!({})); + assert!(preview_now(&mut app, &mut d, "Fill Color", "paint.setFill", json!({"color": "#00a000"})).is_some()); + assert!(app.ui.status.contains("type"), "{:?}", app.ui.status); + } + + /// The font menus end the typing session before their preview: the typing Real-time Drawing + /// off left unapplied is kept as a step of its own. + #[test] + fn ending_typing_for_the_font_menus_keeps_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + let steps = app.session.active().unwrap().history.undo.len(); + crate::panels::character::end_typing(&mut app); + assert_eq!(plain(&app, id), "Hello world"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1); + assert!(st.interaction.is_none()); + assert_ne!(app.session.tool_options().get("typing").and_then(Value::as_bool), Some(true), "the typing session is over"); + } + + /// A Character panel change keeps the typing first and acts on the characters the Type tool + /// selected in the typed text, not on a selection cut short to the text before the typing. + #[test] + fn a_character_change_acts_on_characters_selected_in_the_typing() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let id = typing(&mut app); + app.session.set_tool_option("select", &json!({"start": 6, "end": 11})); + crate::panels::character::range_style(&mut app, json!({"underline": true})); + assert_eq!(plain(&app, id), "Hello world"); + let vectorcraft_doc::NodeKind::Text(t) = &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { + panic!("not text") + }; + let underlined: String = t.runs.iter().filter(|r| r.style.underline).map(|r| r.text.as_str()).collect(); + assert_eq!(underlined, "world"); + } +} + #[cfg(test)] mod typed_number_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index dc42dcff87..be997d7c75 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -90,8 +90,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; - if let Some((id, a, b)) = crate::panels::character::text_editing(app) { - crate::panels::character::end_typing(app); + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app) { targets = json!({"ids": [id.0], "start": a, "end": b}); // After Select All in threaded text: every paragraph of every frame ([`params`]). story = crate::panels::character::text_story(app).map(|_| id.0); diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index 88838585ee..4257c15177 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -87,7 +87,7 @@ impl Strip { /// The open strip `d` moves to the level `cmd {auto: true}` picks for the selection, and the /// canvas previews it → {level}. pub fn auto(&self, app: &mut VectorcraftApp, mut d: Dialog) -> Result { - let _ = app.session.begin_interaction(self.label); + app.begin_interaction(self.label)?; let r = app.session.preview(self.cmd, &json!({ "auto": true })).map_err(|e| e.to_string())?; let level = r["level"].as_f64().unwrap_or(self.default_level); d.fields.insert("level".into(), json!(level)); diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 9583b893ef..913a9126a8 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -123,8 +123,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("preview".into(), json!(pv)); } if pv && (changed || pv_changed || !app.session.in_interaction()) { - let _ = app.session.begin_interaction("Swatch Options"); - if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) { + // A failure to begin (typing that can't be kept) shows, and nothing previews. + if let Err(e) = app.begin_interaction("Swatch Options") { + app.status(e); + } else if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) { app.status(e.to_string()); } } else if !pv && pv_changed { diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 9b829114c2..fd78474f00 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -1698,7 +1698,8 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, pick: FontPic FontPick::Preview(f, style) => { if !previewing { crate::panels::character::end_typing(app); - if app.session.begin_interaction("Font").is_err() { + if let Err(e) = app.begin_interaction("Font") { + app.status(e); return; } crate::panels::set_pstate(ctx, PREVIEWING, true); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 71019385b6..f12a7f623a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -478,12 +478,14 @@ pub(crate) fn live_run(app: &mut VectorcraftApp, label: &str, cmd: &str, params: match phase { Live::Idle => {} Live::Dragging | Live::Released => { - if app.session.begin_interaction(label).is_ok() { + if app.begin_interaction(label).is_ok() { if let Err(e) = app.session.preview(cmd, ¶ms) { app.ui.status = e.to_string(); } - if phase == Live::Released { - app.session.commit_interaction().ok(); + if phase == Live::Released + && let Err(e) = app.session.commit_interaction() + { + app.ui.status = e.to_string(); } app.sync_views(); } else if phase == Live::Released { diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 0cb47e6542..dd6e230008 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -242,14 +242,13 @@ pub(crate) fn format(app: &mut VectorcraftApp, p: Value) { /// has selected (the whole text when nothing is selected) while it edits text, else /// `text.setFormat` on the selected stories ([`selected_stories`]). pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result { - let Some((id, a, b)) = text_editing(app) else { + let Some((id, a, b)) = text_editing_kept(app) else { target_selected_stories(app, &mut p); return app.run("text.setFormat", p); }; if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { return story_style(app, first, p); } - end_typing(app); p["id"] = json!(id.0); if b > a { p["start"] = json!(a); @@ -300,7 +299,7 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, mut p: Value) { /// and Optical set no space (#5111); nowhere to set at an empty line's start. Else it is a /// character attribute like the others: the selected range, or all the text. fn set_kerning(app: &mut VectorcraftApp, value: Value) { - let Some((id, a, b)) = text_editing(app) else { + let Some((id, a, b)) = text_editing_kept(app) else { format(app, json!({"kerning": value})); return; }; @@ -310,7 +309,6 @@ fn set_kerning(app: &mut VectorcraftApp, value: Value) { } let Some(NodeKind::Text(t)) = app.session.active().and_then(|st| st.doc.node(id)).map(|n| &n.kind) else { return }; let Some((target, before)) = vectorcraft_text::edit::caret_kerning_target(&t.plain_text(), a) else { return }; - end_typing(app); let params = if before { json!({"id": id.0, "start": target.start, "end": target.end, "kerningBefore": value.as_f64().unwrap_or(0.0)}) } else { @@ -505,12 +503,11 @@ pub(crate) fn toggle_underline(app: &mut VectorcraftApp) -> Result a { @@ -534,6 +531,13 @@ pub(crate) fn text_editing(app: &VectorcraftApp) -> Option<(NodeId, usize, usize Some((id, g("start"), g("end"))) } +/// [`text_editing`] after [`end_typing`], for an edit of the text: the selection is read in the +/// text with the typing applied, which Real-time Drawing off leaves unapplied until then. +pub(crate) fn text_editing_kept(app: &mut VectorcraftApp) -> Option<(NodeId, usize, usize)> { + end_typing(app); + text_editing(app) +} + /// The frames of the threaded story whose whole text the Type tool has selected after Select All, /// in the order of the edited frame's thread as the document holds it now; `None` when its /// selection is in one type object. @@ -606,9 +610,15 @@ fn story_style(app: &mut VectorcraftApp, first: NodeId, mut p: Value) -> Result< app.run("text.setRangeStyle", p) } -/// Close the Type tool's typing session (one undo step) before another command edits the text. +/// Close the Type tool's typing session (one undo step) before another command edits the text. The +/// typing Real-time Drawing off left unapplied is applied first; when it can't be kept, the error +/// shows and the session goes on. pub(crate) fn end_typing(app: &mut VectorcraftApp) { if app.session.tool_options().get("typing").and_then(Value::as_bool) == Some(true) { + if let Err(e) = app.keep_typing() { + app.status(e); + return; + } app.session.set_tool_option("commitTyping", &json!(true)); app.session.commit_interaction().ok(); app.sync_views(); @@ -1196,9 +1206,8 @@ pub(crate) fn axis_sliders(app: &mut VectorcraftApp, ui: &mut Ui, face: &vectorc /// Set Variable Font settings `axes` on the text the panel acts on, live while a slider drags. fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { - match text_editing(app) { + match text_editing_kept(app) { Some((id, a, b)) => { - end_typing(app); let mut q = json!({"id": id.0, "fontAxes": axes}); // After Select All in threaded text: every frame of the story. if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index e02d81e14c..232de0a65f 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -86,8 +86,7 @@ pub(crate) fn run_on_paragraphs(app: &mut VectorcraftApp, cmd: &str, p: Value) - /// [`run_on_paragraphs`], with the Selection tool on the selected type objects alone unless /// `stories`. fn run_on(app: &mut VectorcraftApp, cmd: &str, mut p: Value, stories: bool) -> Result { - if let Some((id, a, b)) = super::character::text_editing(app) { - super::character::end_typing(app); + if let Some((id, a, b)) = super::character::text_editing_kept(app) { match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => p["ids"] = json!(story.iter().map(|f| f.0).collect::>()), diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 00814646c5..187ce21c42 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -423,8 +423,7 @@ fn stops_json(stops: &[TabStop]) -> Value { /// frame of the selected stories ([`super::character::selected_stories`]). Returns false when it /// fails. fn apply(app: &mut VectorcraftApp, stops: &[TabStop]) -> bool { - if let Some((id, a, b)) = super::character::text_editing(app) { - super::character::end_typing(app); + if let Some((id, a, b)) = super::character::text_editing_kept(app) { let p = match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => json!({"stops": stops_json(stops), "ids": story.iter().map(|f| f.0).collect::>()}), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e36c7f318..d04b193f6d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1981,6 +1981,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged. - **The warning of a preview applied when a command ends a drag:** a preview that Real-time Drawing off left unapplied, and that Undo, Clear History or another command applies before it runs, keeps its warning: the command's result carries it as `previewWarning`, and as `warning` when the command has none of its own, and the status bar shows it, as releasing the drag shows it. Typing kept as its own step when a tool's drag begins, or when Cmd lends the Selection tool, shows its applied preview's warning in the status bar too. Regressions: `settling_a_deferred_preview_keeps_its_warning` and `settling_typing_for_a_tool_shows_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `settled_warnings_join_the_result` in `crates/engine/src/session/execute.rs`. Scores and hours unchanged. +- **Typing kept when a dialog or a panel previews, with Real-time Drawing off:** a dialog's Preview, a panel's live slider, the Effect Gallery's preview, the font menus' preview, a paint for the characters the Type tool selected and an inline graphic inserted while typing first apply the typing that Real-time Drawing off left unapplied, as an undo step of its own, and the status bar shows that typing's preview warning. The Character, Paragraph and Tabs panels, Bullets and Numbering, Justification and the inline graphic then act on the characters the Type tool selected in the typed text. When the typing can't be kept, the status bar shows the error and the dialog's preview does not start. Regressions: `settling_typing_for_a_dialog_returns_its_preview_warning` in `crates/engine/src/tests/prefs.rs`, `ending_deferred_typing_for_another_edit_keeps_the_typing` in `crates/engine/src/tests/textedit.rs`, `inserting_while_deferred_typing_keeps_the_typing` in `crates/engine/src/tests/inline.rs`, `settled_typing_tests` in `crates/ui-egui/src/dialogs/form.rs`, `stack_preview_keeps_typing_in_progress` in `crates/ui-egui/src/dialogs/effect_gallery.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged. From 22b8c6ce5a98dc53e9eccd5e52b121a288445c08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 04:51:10 -0800 Subject: [PATCH 025/138] Part of #978: the Color Wheel panel offers a box view with a color field and a channel strip The Color Wheel panel's menu gains Wheel View and Box View, and Box Channel with Hue, Saturation, Brightness, Red, Green and Blue while the box shows. The box takes the wheel's place: a color field with a 22 pt channel strip at its right. The field shows the other two components on the Color Picker's axes (Hue: saturation across and brightness up; Red: blue across and green up). A click or drag in the field sets those two, and the strip sets the channel; a drag is one undo step, and picks go through the same paint commands and color model rules as the wheel's. With no color to edit, the field and the strip show no markers and read 0 to screen readers, as the wheel does. ui.colorWheel {view?, channel?} sets the view and the channel and returns them. Params that are not an object, another key or a value off the list are an error and change nothing. Both settings are kept with the preferences, and a saved value the build does not know reads as that key's default without losing the other preferences. The strip takes the arrow keys after a click and offers screen readers its increment, decrement and set-value actions. The Color Picker's channel slider uses the same widget, so it now takes the arrow keys and offers those actions too. New strings have rows in the complete catalogs, and docs/mcp.md and docs/control-protocol.md describe the command. --- crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/color_picker.rs | 34 +- crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/ka.tsv | 7 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels.rs | 3 + crates/ui-egui/src/panels/color_wheel.rs | 193 +++++++++- .../src/panels/tests_color_wheel_box.rs | 353 ++++++++++++++++++ crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/widgets.rs | 6 +- crates/ui-egui/src/widgets/color.rs | 52 ++- docs/control-protocol.md | 4 +- docs/mcp.md | 5 + docs/target-app-parity.md | 2 +- 42 files changed, 845 insertions(+), 19 deletions(-) create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_box.rs diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index a6bc021fdc..943faa4782 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1320,6 +1320,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), + ( + "ui.colorWheel", + "Color Wheel Options", + "", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + ), ( "ui.savePdfDialog", "Save PDF Dialog", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5afad21b0d..acecdfc236 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -24,7 +24,7 @@ pub mod bullets_numbering; pub mod char_style_options; pub mod color_balance; pub mod color_guide_options; -mod color_picker; +pub(crate) mod color_picker; mod command; pub mod composite_fonts; pub mod confirm; diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index c4ef1a984d..992c986035 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -101,11 +101,22 @@ impl Channel { Channel::Green => "G", } } - fn is_hsb(self) -> bool { + /// The channel's name, translated: Hue, Saturation, Brightness, Red, Green or Blue. + pub(crate) fn name(self) -> &'static str { + match self { + Channel::Hue => tl!("Hue"), + Channel::Saturation => tl!("Saturation"), + Channel::Brightness => tl!("Brightness"), + Channel::Red => tl!("Red"), + Channel::Green => tl!("Green"), + Channel::Blue => tl!("Blue"), + } + } + pub(crate) fn is_hsb(self) -> bool { matches!(self, Channel::Hue | Channel::Saturation | Channel::Brightness) } /// Indices of (slider, field x, field y) into the channel's space: [h, s, b] or [r, g, b]. - fn axes(self) -> (usize, usize, usize) { + pub(crate) fn axes(self) -> (usize, usize, usize) { match self { Channel::Hue => (0, 1, 2), Channel::Saturation => (1, 0, 2), @@ -117,7 +128,7 @@ impl Channel { } /// The color field's axes (across, up) as keys and screen readers see them: hue in degrees, /// saturation and brightness in percent, red, green and blue from 0 to 255. - fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { + pub(crate) fn field_axes(self) -> [widgets::FieldAxis<'static>; 2] { let axis = |i: usize| { let (name, units, suffix) = match (self.is_hsb(), i) { (true, 0) => (tl!("Hue"), 360.0, "°"), @@ -393,10 +404,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color); let (v, suffix, max) = channel_value(channel, &p); let shown = widgets::SliderValue::field(v as f64, 0.0..=max as f64, suffix, 0); - if let (Some(z), _) = - widgets::channel_slider_valued(ui, "cp-slider", tl!(channel.label()), Some(shown), z, vec2(SLIDER_W, side), &track) - { - pick = Some(field_pick(channel, z, x, y)); + match widgets::channel_slider_stepped( + ui, + "cp-slider", + tl!(channel.label()), + Some(shown), + z, + true, + vec2(SLIDER_W, side), + &track, + ) { + (Some(z), ..) => pick = Some(field_pick(channel, z, x, y)), + (None, _, Some(v)) => pick = Some(field_pick(channel, (v / max as f64) as f32, x, y)), + _ => {} } } }); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8cb531e411..348ac7b881 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -557,6 +557,11 @@ font-technology Variable Променливи Saturation and brightness Насищане и яркост Color field Цветово поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Изглед „Колело“ + Box View Изглед „Квадрат“ + Box Channel Канал на квадрата + Color box Цветови квадрат + Color Wheel Options Опции на цветното колело Color Type: Цветен тип: Color: Цвят: Colorize Оцветяване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 57790c64c6..3b1a9e001c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -735,6 +735,11 @@ Saturation and brightness Zasićenje i svjetlina Color field Polje boje {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Prikaz kotača + Box View Prikaz kvadrata + Box Channel Kanal kvadrata + Color box Kvadrat boje + Color Wheel Options Opcije kotača boja CSS Properties CSS svojstva Document Info Informacije o dokumentu Flattener Preview Pregled spljoštavanja @@ -4644,6 +4649,8 @@ imageTrace Outline Obris @msg `{min_key}` is greater than `{max_key}` `{min_key}` je veće od `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` navedite barem jedno od `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe +@msg `view` must be wheel or box `view` mora biti wheel ili box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 592de77eed..488b46c4f5 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -819,6 +819,11 @@ antiAlias Sharp Nítid Saturation and brightness Saturació i lluentor Color field Camp de color {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Visualització de roda + Box View Visualització de quadre + Box Channel Canal del quadre + Color box Quadre de color + Color Wheel Options Opcions de la roda de colors Color Type: Tipus de color: Color wheel Roda de color Color: Color: @@ -5265,6 +5270,8 @@ digits Malayalam Malaiàlam @msg a negative `aspect` applies to conic gradients un `aspect` negatiu s’aplica als degradats cònics @msg `focal` applies to radial gradients `focal` s’aplica als degradats radials @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` ha de ser wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bde13aa090..6a57e90e37 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -748,6 +748,11 @@ Saturation and brightness Sytost a jas Color field Barevné pole {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Zobrazení kola + Box View Zobrazení čtverce + Box Channel Kanál čtverce + Color box Barevný čtverec + Color Wheel Options Možnosti barevného kola CSS Properties Vlastnosti CSS Document Info Informace o dokumentu Flattener Preview Náhled sloučení @@ -4807,6 +4812,8 @@ imageTrace Outline Obrys @msg `{min_key}` is greater than `{max_key}` `{min_key}` je větší než `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` zadejte alespoň jeden z parametrů `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe +@msg `view` must be wheel or box `view` musí být wheel nebo box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f320896f62..54a79e38e5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -693,6 +693,11 @@ Saturation and brightness Mætning og lysstyrke Color field Farvefelt {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hjulvisning + Box View Kvadratvisning + Box Channel Kvadratets kanal + Color box Farvekvadrat + Color Wheel Options Indstillinger for farvehjul CSS Properties CSS-egenskaber Document Info Dokumentoplysninger Flattener Preview Udjævningsforhåndsvisning @@ -5633,6 +5638,8 @@ mark-style Japanese Japansk @msg the file's variable library couldn't be read: the Variables panel doesn't list it filens variabelbibliotek kunne ikke læses: variabelpanelet viser det ikke @msg a variable of unknown kind can't be bound to objects en variabel af ukendt type kan ikke bindes til objekter @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe +@msg `view` must be wheel or box `view` skal være wheel eller box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9ca688e1b5..ab77cb0dd7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -550,6 +550,11 @@ font-technology Variable Variabel Saturation and brightness Sättigung und Helligkeit Color field Farbauswahlfeld {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Kreisansicht + Box View Quadratansicht + Box Channel Kanal des Quadrats + Color box Farbquadrat + Color Wheel Options Optionen für den Farbkreis Color Type: Farbart: Color: Farbe: Colorize Einfärben @@ -4420,6 +4425,8 @@ theme Appearance Erscheinungsbild @msg `{min_key}` is greater than `{max_key}` `{min_key}` ist größer als `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` geben Sie mindestens einen der Parameter `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` an @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein +@msg `view` must be wheel or box `view` muss wheel oder box sein +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 776c992e7c..a1a203a257 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -532,6 +532,11 @@ font-technology Variable Μεταβλητές Saturation and brightness Κορεσμός και φωτεινότητα Color field Πεδίο χρώματος {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Προβολή τροχού + Box View Προβολή τετραγώνου + Box Channel Κανάλι τετραγώνου + Color box Τετράγωνο χρώματος + Color Wheel Options Επιλογές χρωματικού τροχού Color Type: Τύπος χρώματος: Color: Χρώμα: Colorize Χρωματισμός @@ -6091,6 +6096,8 @@ effect Points Σημεία @msg Unknown dimension option {k} Άγνωστη επιλογή διάστασης {k} @msg Unknown dimension orientation Άγνωστος προσανατολισμός διάστασης @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe +@msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box +@msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 935d011e72..45fd0d8235 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -572,6 +572,11 @@ font-technology Variable Variables Saturation and brightness Saturación y brillo Color field Campo de color {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Vista de rueda + Box View Vista de cuadro + Box Channel Canal del cuadro + Color box Cuadro de color + Color Wheel Options Opciones de la rueda de color Color Type: Tipo de color: Color: Color: Colorize Colorear @@ -4497,6 +4502,8 @@ axis Both Ambos @msg `{min_key}` is greater than `{max_key}` `{min_key}` es mayor que `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indica al menos uno de `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` debe ser wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 684589a9a1..f6db5b8ee1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -739,6 +739,11 @@ Saturation and brightness Kylläisyys ja kirkkaus Color field Värikenttä {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Ympyränäkymä + Box View Ruutunäkymä + Box Channel Ruudun kanava + Color box Väriruutu + Color Wheel Options Väriympyrän asetukset CSS Properties CSS-ominaisuudet Document Info Asiakirjan tiedot Flattener Preview Litistyksen esikatselu @@ -6102,6 +6107,8 @@ mark-style Japanese Japanilainen @msg Unknown dimension option {k} Tuntematon mitoitusasetus {k} @msg Unknown dimension orientation Tuntematon mitan suunta @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe +@msg `view` must be wheel or box `view`-arvon on oltava wheel tai box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9ceca79c90..ae0bf3b436 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -573,6 +573,11 @@ font-technology Variable Variables Saturation and brightness Saturation et luminosité Color field Champ de couleur {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Affichage roue + Box View Affichage carré + Box Channel Couche du carré + Color box Carré de couleur + Color Wheel Options Options de la roue chromatique Color Type: Type de couleur : Color: Couleur : Colorize Coloriser @@ -4486,6 +4491,8 @@ axis Both Les deux @msg `{min_key}` is greater than `{max_key}` `{min_key}` est supérieur à `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indiquez au moins l’un des paramètres `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe +@msg `view` must be wheel or box `view` doit valoir wheel ou box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 716d851655..f38612601c 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4224,6 +4224,11 @@ {kind} Gradient {kind} ગ્રેડિયન્ટ {kind}, {model} {kind}, {model} {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View વ્હીલ વ્યૂ + Box View બૉક્સ વ્યૂ + Box Channel બૉક્સ ચેનલ + Color box રંગ બૉક્સ + Color Wheel Options રંગ વ્હીલ વિકલ્પો {name} (spot) {name} (સ્પૉટ) {pages} in all, {count} per copy કુલ {pages}, પ્રતિ નકલ {count} {page} of {count} {count} માંથી {page} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 64873c5e2d..624671acca 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -943,6 +943,11 @@ antiAlias Sharp शार्प Saturation and brightness सैचुरेशन और ब्राइटनेस Color field कलर फ़ील्ड {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View व्हील व्यू + Box View बॉक्स व्यू + Box Channel बॉक्स चैनल + Color box कलर बॉक्स + Color Wheel Options कलर व्हील ऑप्शन्स Color Type: रंग का प्रकार: Color wheel कलर व्हील Color: रंग: @@ -6157,6 +6162,8 @@ antiAlias Sharp शार्प @msg `mode` must be "handles", "straight" or "smooth" `mode` को "handles", "straight" या "smooth" होना चाहिए @msg `mode` must be "straight", "bezier" or "arc" `mode` को "straight", "bezier" या "arc" होना चाहिए @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए +@msg `view` must be wheel or box `view` को wheel या box होना चाहिए +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e1ddc72b93..3e8a200697 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -748,6 +748,11 @@ font-technology Variable Változó Saturation and brightness Telítettség és fényesség Color field Színmező {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Körnézet + Box View Négyzetnézet + Box Channel Négyzet csatornája + Color box Színnégyzet + Color Wheel Options Színkör beállításai Color Type: Színtípus: Color: Szín: Colorization Színezés @@ -4922,6 +4927,8 @@ imageTrace Outline Körvonal @msg `{min_key}` is greater than `{max_key}` `{min_key}` nagyobb, mint `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` adj meg legalább egyet ezek közül: `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell +@msg `view` must be wheel or box `view`: wheel vagy box kell +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 208877f673..2107a23bf0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -693,6 +693,11 @@ Saturation and brightness Saturasi dan kecerahan Color field Kolom warna {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Tampilan roda + Box View Tampilan kotak + Box Channel Saluran kotak + Color box Kotak warna + Color Wheel Options Opsi roda warna CSS Properties Properti CSS Document Info Info dokumen Flattener Preview Pratinjau perata @@ -5633,6 +5638,8 @@ mark-style Japanese Jepang @msg the file's variable library couldn't be read: the Variables panel doesn't list it pustaka variabel file tidak dapat dibaca: panel Variabel tidak menampilkannya @msg a variable of unknown kind can't be bound to objects variabel bertipe tidak dikenal tidak dapat diikat ke objek @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe +@msg `view` must be wheel or box `view` harus wheel atau box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1252743764..f75dc629db 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -572,6 +572,11 @@ font-technology Variable Variabili Saturation and brightness Saturazione e luminosità Color field Campo colore {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Vista ruota + Box View Vista riquadro + Box Channel Canale del riquadro + Color box Riquadro colore + Color Wheel Options Opzioni ruota dei colori Color Type: Tipo di colore: Color: Colore: Colorize Colora @@ -4549,6 +4554,8 @@ axis Both Entrambi @msg `{min_key}` is greater than `{max_key}` `{min_key}` è maggiore di `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` indica almeno uno tra `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe +@msg `view` must be wheel or box `view` deve essere wheel o box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 97a91c1ed2..67072cc8b3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -763,6 +763,11 @@ digits Malayalam マラヤーラム数字 Saturation and brightness 彩度と明るさ Color field カラーフィールド {name1} {value1}, {name2} {value2} {name1} {value1}、{name2} {value2} + Wheel View ホイール表示 + Box View ボックス表示 + Box Channel ボックスのチャンネル + Color box カラーボックス + Color Wheel Options カラーホイールオプション CSS Properties CSS プロパティ Document Info ドキュメント情報 Flattener Preview 分割・統合プレビュー @@ -5009,6 +5014,8 @@ swatch Bright Violet ビビッドバイオレット @msg No saved views (View → New View…) 保存した表示はありません (表示 → 新規表示…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` には、メニュー項目がダイアログを開くコマンドを指定してください (ui.menuDialog を参照) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください +@msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9891fa66f2..c8513b84c3 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -659,6 +659,11 @@ Saturation and brightness გაჯერება და სიკაშკაშე Color field ფერის ველი {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View წრის ხედი + Box View კვადრატის ხედი + Box Channel კვადრატის არხი + Color box ფერის კვადრატი + Color Wheel Options ფერთა წრის პარამეტრები CSS Properties CSS თვისებები Document Info დოკუმენტის ინფორმაცია Flattener Preview გაბრტყელების წინასწარი ნახვა @@ -5787,6 +5792,8 @@ imageTrace Outline კონტური Color Panel Options ფერის პანელის პარამეტრები @msg `{key}` must be an array of these names: {_1} `{key}` უნდა იყოს ამ სახელების მასივი: {_1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe +@msg `view` must be wheel or box `view` უნდა იყოს wheel ან box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0cdcda85c8..8aa0bc41ca 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -756,6 +756,11 @@ digits Malayalam 말라얄람어 Saturation and brightness 채도 및 밝기 Color field 색상 필드 {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View 휠 보기 + Box View 상자 보기 + Box Channel 상자 채널 + Color box 색상 상자 + Color Wheel Options 색상환 옵션 CSS Properties CSS 속성 Document Info 문서 정보 Flattener Preview 병합 미리 보기 @@ -4936,6 +4941,8 @@ theme Appearance 외관 @msg No saved views (View → New View…) 저장된 보기가 없습니다(보기 → 새 보기…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command`는 메뉴 항목이 대화상자를 여는 명령이어야 합니다(ui.menuDialog 참조) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다 +@msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다 +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 50bd43201b..de5b7a3cf6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1211,6 +1211,11 @@ Saturation and brightness Verzadiging en helderheid Color field Kleurveld {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Wielweergave + Box View Vakweergave + Box Channel Kanaal van het vak + Color box Kleurvak + Color Wheel Options Opties voor kleurenwiel CSS Properties CSS-eigenschappen Document Info Documentinfo Flattener Preview Afvlakvoorbeeld @@ -6210,6 +6215,8 @@ mark-style Japanese Japans @msg the file's variable library couldn't be read: the Variables panel doesn't list it de variabelenbibliotheek van het bestand kan niet worden ingelezen: het Variabelen-paneel toont die niet @msg a variable of unknown kind can't be bound to objects een variabele van onbekend type kan niet aan objecten worden gekoppeld @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn +@msg `view` must be wheel or box `view` moet wheel of box zijn +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 891e916724..f9bdc664f1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -697,6 +697,11 @@ Saturation and brightness Nasycenie i jasność Color field Pole koloru {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Widok koła + Box View Widok kwadratu + Box Channel Kanał kwadratu + Color box Kwadrat koloru + Color Wheel Options Opcje koła kolorów CSS Properties Właściwości CSS Document Info Informacje o dokumencie Flattener Preview Podgląd spłaszczania @@ -4631,6 +4636,8 @@ imageTrace Outline Kontur @msg `{min_key}` is greater than `{max_key}` `{min_key}` jest większe niż `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` podaj co najmniej jeden z parametrów `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe +@msg `view` must be wheel or box `view` musi mieć wartość wheel lub box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e45bf18d42..07cd9c6fd6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -517,6 +517,11 @@ antiAlias Sharp Nítido Saturation and brightness Saturação e Brilho Color field Campo de Cor {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Exibição em Roda + Box View Exibição em Caixa + Box Channel Canal da Caixa + Color box Caixa de cor + Color Wheel Options Opções da Roda de Cores Color Type: Tipo de Cor: Color blindness – Deuteranopia-type Daltonismo – tipo deuteranopia Color blindness – Protanopia-type Daltonismo – tipo protanopia @@ -6090,6 +6095,8 @@ mark-style Japanese Japonesas two points, then move and click to place an aligned, horizontal or vertical dimension | em dois pontos, depois mova e clique para posicionar uma cota alinhada, horizontal ou vertical | Color Panel Options Opções do Painel Cor @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe +@msg `view` must be wheel or box `view` deve ser wheel ou box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue @msg the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b260a39c0f..fcf44192cd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -570,6 +570,11 @@ font-technology Variable Вариативные Saturation and brightness Насыщенность и яркость Color field Цветовое поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Вид «Круг» + Box View Вид «Квадрат» + Box Channel Канал квадрата + Color box Цветовой квадрат + Color Wheel Options Параметры цветового круга Color Type: Тип цвета: Color: Цвет: Colorize Тонировать @@ -4534,6 +4539,8 @@ axis Both Оба @msg `{min_key}` is greater than `{max_key}` `{min_key}` больше, чем `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` укажите хотя бы один из параметров `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe +@msg `view` must be wheel or box `view` должно быть wheel или box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 3854b8d56f..d68878734e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -559,6 +559,11 @@ font-technology Variable Variabla Saturation and brightness Mättnad och ljusstyrka Color field Färgfält {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hjulvy + Box View Rutvy + Box Channel Rutans kanal + Color box Färgruta + Color Wheel Options Alternativ för färghjulet Color Type: Färgtyp: Color: Färg: Colorize Färglägg @@ -6092,6 +6097,8 @@ theme Appearance Utseende @msg Unknown dimension option {k} Okänt måttalternativ {k} @msg Unknown dimension orientation Okänd måttriktning @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe +@msg `view` must be wheel or box `view` måste vara wheel eller box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 17575e2732..b3c88cc563 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -553,6 +553,11 @@ font-technology Variable Değişken Saturation and brightness Doygunluk ve parlaklık Color field Renk seçim alanı {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Tekerlek Görünümü + Box View Kutu Görünümü + Box Channel Kutu Kanalı + Color box Renk kutusu + Color Wheel Options Renk Tekerleği Seçenekleri Color Type: Renk Türü: Color: Renk: Colorize Renklendir @@ -4254,6 +4259,8 @@ axis Both Her İkisi @msg `{min_key}` is greater than `{max_key}` `{min_key}`, `{max_key}` değerinden büyük @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` şunlardan en az birini verin: `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır +@msg `view` must be wheel or box `view` wheel veya box olmalıdır +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a92fb0329b..0ab6257df4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -566,6 +566,11 @@ font-technology Variable Варіативні Saturation and brightness Насиченість і яскравість Color field Колірне поле {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Вигляд «Коло» + Box View Вигляд «Квадрат» + Box Channel Канал квадрата + Color box Колірний квадрат + Color Wheel Options Параметри колірного кола Color Type: Тип кольору: Color: Колір: Colorize Тонувати @@ -4533,6 +4538,8 @@ axis Both Обидві @msg `{min_key}` is greater than `{max_key}` `{min_key}` більше за `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` укажіть принаймні один із параметрів `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe +@msg `view` must be wheel or box `view` має бути wheel або box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2f53625bf8..80cc4951cf 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -659,6 +659,11 @@ font-technology Variable Biến thiên Saturation and brightness Độ bão hòa và độ sáng Color field Vùng chọn màu {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} + Wheel View Hiển thị bánh xe + Box View Hiển thị hộp + Box Channel Kênh của hộp + Color box Hộp màu + Color Wheel Options Tùy chọn bánh xe màu Color Type: Loại màu: Color: Màu: Colorization Tô màu @@ -4582,6 +4587,8 @@ theme Appearance Giao diện @msg `{min_key}` is greater than `{max_key}` `{min_key}` lớn hơn `{max_key}` @msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` hãy cung cấp ít nhất một trong `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe +@msg `view` must be wheel or box `view` phải là wheel hoặc box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8a7b09aa41..9561a51baf 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -518,6 +518,11 @@ antiAlias Sharp 锐利 Saturation and brightness 饱和度和亮度 Color field 颜色区域 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} + Wheel View 色轮视图 + Box View 方块视图 + Box Channel 方块色版 + Color box 颜色方块 + Color Wheel Options 色轮选项 Color Type: 颜色类型: Color: 颜色: Colorize 上色 @@ -4692,6 +4697,8 @@ imageTrace Outline 轮廓 @msg No saved views (View → New View…) 没有已保存的视图 (视图 → 新建视图…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` 必须是其菜单项会打开对话框的命令 (请参阅 ui.menuDialog) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe +@msg `view` must be wheel or box `view` 必须是 wheel 或 box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4deead50de..7489e3d4d9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -535,6 +535,11 @@ font-technology Variable 可變 Saturation and brightness 飽和度和亮度 Color field 顏色區域 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} + Wheel View 色輪檢視 + Box View 方塊檢視 + Box Channel 方塊色版 + Color box 顏色方塊 + Color Wheel Options 色輪選項 Color Type: 顏色類型: Color: 顏色: Colorize 上色 @@ -2406,6 +2411,8 @@ file-filter Templates 範本 @msg No saved views (View → New View…) 沒有已儲存的檢視 (檢視 → 新增檢視…) @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` 必須是選單項目會開啟對話框的指令 (請參閱 ui.menuDialog) @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe +@msg `view` must be wheel or box `view` 必須是 wheel 或 box +@msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7b7f7a6b21..ff6c3531c0 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -943,6 +943,7 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::color_guide::set_limit(app, p), "ui.colorPanel" => crate::panels::color::command(app, p), "ui.colorRgbPercent" => crate::panels::color::rgb_percent_command(app, p), + "ui.colorWheel" => crate::panels::color_wheel::command(app, p), "ui.savePdfDialog" => crate::dialogs::open_save_pdf(app, p), "file.exportAs" if s("path").is_none() => { crate::dialogs::open_export_as(app, s("format").as_deref(), p); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4a8e9910cb..d36ecae60f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1321,6 +1321,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} switch the Color panel's R, G and B between percent and 0 to 255, as a double-click right of an RGB field does (ui.colorPanel {rgbPercent}); the color does not change, and the choice is kept with the preferences; a parameter is an error and changes nothing → true when they show in percent", ), + ( + "ui.colorWheel", + "Color Wheel Options", + "", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + ), ( "ui.savePdfDialog", "Save PDF Dialog", diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 71019385b6..d12c89d2af 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -238,6 +238,7 @@ pub fn panel_menu_items(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) -> bool "attributes" => attributes::menu(app, ui), svg_interactivity::ID => svg_interactivity::menu(app, ui), "colorThemes" => color_themes::menu(app, ui), + color_wheel::ID => color_wheel::menu(app, ui), "layers" => layers::menu(app, ui), links::ID => links::menu(app, ui), asset_export::ID => asset_export::menu(app, ui), @@ -695,6 +696,8 @@ mod tests_brush_libraries; #[cfg(test)] mod tests_color_wheel; #[cfg(test)] +mod tests_color_wheel_box; +#[cfg(test)] mod tests_constrain; #[cfg(test)] mod tests_css_properties; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index a2108d8cf8..31522578e5 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -6,8 +6,15 @@ //! space: an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch //! becomes a process color in the document's color mode. The HSB picked last stays while the //! objects, the proxy, the color and the color settings are unchanged, so a gray keeps its hue. +//! +//! The panel menu's Box View puts a box in the wheel's place: a color field with a vertical +//! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation, +//! Brightness, Red, Green or Blue). The field shows the other two components on the Color +//! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`). -use egui::{Ui, UiBuilder}; +use egui::{Ui, UiBuilder, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; @@ -15,11 +22,189 @@ use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; use super::{pstate, set_pstate}; use crate::VectorcraftApp; -use crate::widgets::{self, FieldAxis, Live}; +use crate::dialogs::color_picker::Channel; +use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item}; pub const ID: &str = "colorWheel"; /// The widest the wheel is drawn. const MAX_WHEEL: f32 = 200.0; +/// The width of the box's channel strip, its arrows included. +const STRIP: f32 = 22.0; +/// The space between the box's field and its channel strip. +const STRIP_GAP: f32 = 6.0; + +/// What the panel shows right of the proxy: the wheel, or the box (a color field and a channel +/// strip). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum View { + #[default] + Wheel, + Box, +} + +impl View { + pub const ALL: [View; 2] = [View::Wheel, View::Box]; + + pub fn id(self) -> &'static str { + match self { + View::Wheel => "wheel", + View::Box => "box", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|v| v.id() == s) + } +} + +/// The panel's settings, kept with the preferences (`UiState::color_wheel`, `ui.colorWheel`). +/// Each key reads on its own, and a value this build does not know reads as the key's default. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Settings { + #[serde(deserialize_with = "deserialize_view")] + pub view: View, + #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] + pub channel: Channel, +} + +fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(View::parse).unwrap_or_default()) +} + +fn serialize_channel(c: &Channel, s: S) -> Result { + s.serialize_str(c.id()) +} + +fn deserialize_channel<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(Channel::parse).unwrap_or_default()) +} + +/// Serde reader for the saved settings ([`crate::UiState::color_wheel`]): a value that is not an +/// object reads as the defaults, so it doesn't lose the rest of the preferences. +pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(serde_json::from_value(v).unwrap_or_default()) +} + +/// `ui.colorWheel {view?, channel?}`: show the wheel or the box, and pick the box's channel. Keys +/// left out keep their values; params that are not an object, another key or a value off the list +/// are an error and change nothing. → the settings. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { + const KEYS: [&str; 2] = ["view", "channel"]; + match p { + Value::Null => {} + Value::Object(o) => { + if let Some(key) = o.keys().find(|k| !KEYS.contains(&k.as_str())) { + return Err(format!("unknown parameter `{key}`; the command takes: {}", KEYS.join(", "))); + } + } + got => return Err(format!("the params must be an object, not {got}")), + } + let mut set = app.ui.color_wheel.clone(); + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => set.view = v.as_str().and_then(View::parse).ok_or("`view` must be wheel or box")?, + } + match p.get("channel") { + None | Some(Value::Null) => {} + Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, + } + app.ui.color_wheel = set; + Ok(json!(app.ui.color_wheel)) +} + +/// The panel menu: Wheel View and Box View, and Box Channel while the box shows. +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let set = app.ui.color_wheel.clone(); + for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { + if menu_item(ui, label, true, set.view == view) { + command(app, &json!({ "view": view.id() })).ok(); + } + } + ui.add_enabled_ui(set.view == View::Box, |ui| { + ui.menu_button(format!(" {}", tl!("Box Channel")), |ui| { + for ch in Channel::ALL { + if menu_item(ui, ch.name(), true, ch == set.channel) { + command(app, &json!({ "channel": ch.id() })).ok(); + } + } + }); + }); +} + +/// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, +/// or red, green and blue. +fn box_values(ch: Channel, hsb: [f32; 3]) -> [f32; 3] { + if ch.is_hsb() { [hsb[0] / 360.0, hsb[1], hsb[2]] } else { hsb_to_rgb(hsb) } +} + +/// The strip's value and the field's point (x across, y down; 0 to 1 each) of HSB `hsb` in the box +/// of channel `ch`. +pub(crate) fn box_pos(ch: Channel, hsb: [f32; 3]) -> (f32, f32, f32) { + let v = box_values(ch, hsb); + let (z, x, y) = ch.axes(); + (v[z], v[x], 1.0 - v[y]) +} + +/// The HSB at strip value `z` and field point (x, y) in the box of channel `ch`: the inverse of +/// [`box_pos`]. A pick in an RGB channel that has no hue (a gray) keeps the hue of `was`. +pub(crate) fn box_pick(ch: Channel, z: f32, x: f32, y: f32, was: [f32; 3]) -> [f32; 3] { + let (zi, xi, yi) = ch.axes(); + let mut v = [0.0; 3]; + v[zi] = z; + v[xi] = x; + v[yi] = 1.0 - y; + let v = v.map(|c| c.clamp(0.0, 1.0)); + if ch.is_hsb() { + return [v[0] * 360.0, v[1], v[2]]; + } + let hsb = rgb_to_hsb(v); + if hsb[1] <= 0.0 || hsb[2] <= 0.0 { [was[0], hsb[1], hsb[2]] } else { hsb } +} + +/// The number the strip of channel `ch` reads to screen readers for HSB `hsb`, its suffix and its +/// largest value: hue in degrees, saturation and brightness in percent, red, green and blue from 0 +/// to 255. +fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { + let (units, suffix) = match ch { + Channel::Hue => (360.0, "°"), + Channel::Saturation | Channel::Brightness => (100.0, "%"), + Channel::Red | Channel::Green | Channel::Blue => (255.0, ""), + }; + let (z, _, _) = box_pos(ch, hsb); + (f64::from(z) * units, suffix, units) +} + +/// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with +/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, +/// and its phase. +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { + let (z, x, y) = box_pos(ch, hsb); + let mut pick = None; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = STRIP_GAP; + let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); + let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); + if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { + pick = Some((box_pick(ch, z, x, y, hsb), phase)); + } + // The hue strip shows the whole spectrum; the others change only their own component. + let track = |z: f32| widgets::hsb32(if ch == Channel::Hue { [z * 360.0, 1.0, 1.0] } else { box_pick(ch, z, x, y, hsb) }); + let (v, suffix, max) = strip_number(ch, hsb); + let shown = SliderValue::field(v, 0.0..=max, suffix, 0); + match widgets::channel_slider_stepped(ui, "color-wheel-strip", ch.name(), Some(shown), z, marked, vec2(STRIP, size), &track) { + (Some(z), phase, _) => pick = Some((box_pick(ch, z, x, y, hsb), phase)), + (None, _, Some(v)) => pick = Some((box_pick(ch, (v / max) as f32, x, y, hsb), Live::Released)), + _ => {} + } + }); + pick +} + /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; @@ -132,6 +317,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::proxy(app, ui, 40.0); }); let size = ui.available_width().min(MAX_WHEEL); + if app.ui.color_wheel.view == View::Box { + pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); + return; + } let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked); let square = widgets::ring_square(ring.rect); let mut field_ui = ui.new_child(UiBuilder::new().id_salt("color-wheel-square").max_rect(square)); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs new file mode 100644 index 0000000000..d3866fd5d9 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -0,0 +1,353 @@ +//! The Color Wheel panel's box view drawn headless: `ui.colorWheel`, the field and the strip of +//! each channel, the panel menu, the saved settings, the arrow keys and what screen readers read, +//! and the Color Picker's channel slider, which is the same widget as the strip. + +use egui::accesskit::{Action, ActionData, ActionRequest}; +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_color::cms; +use vectorcraft_engine::Session; + +use super::color_wheel::{Settings, View, box_pick, box_pos, display_hsb, show}; +use crate::VectorcraftApp; +use crate::dialogs::color_picker::Channel; + +/// An app with a selected rectangle filled with `fill`, its Color Wheel panel on the box of +/// `channel`. +fn app(fill: serde_json::Value, channel: &str) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": fill})).unwrap(); + app.run("ui.colorWheel", json!({"view": "box", "channel": channel})).unwrap(); + app +} + +/// The panel in a 260-point-wide flyout, with the app's shortcuts after it as in a frame of the app. +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +fn rect_of(h: &Harness<'static, VectorcraftApp>, label: &str) -> Rect { + h.get_by_label(label).rect() +} + +/// The point (x across, y up; 0..1 each) of `r`. +fn at(r: Rect, x: f32, y: f32) -> Pos2 { + Pos2::new(r.left() + x * r.width(), r.bottom() - y * r.height()) +} + +fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool) { + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2) { + press(h, pos, true); + press(h, pos, false); + h.run_steps(1); +} + +/// A drag through `points`, pressed at the first and released at the last. +fn drag(h: &mut Harness<'static, VectorcraftApp>, points: &[Pos2]) { + let (Some(first), Some(last)) = (points.first(), points.last()) else { return }; + press(h, *first, true); + for p in points { + for _ in 0..2 { + h.event(Event::PointerMoved(*p)); + h.run_steps(1); + } + } + press(h, *last, false); + h.run_steps(1); +} + +fn key(h: &mut Harness<'static, VectorcraftApp>, key: egui::Key) { + h.key_press_modifiers(Modifiers::NONE, key); + h.run_steps(1); +} + +fn fill(app: &VectorcraftApp) -> Color { + crate::panels::current_paints(app).0.color().expect("a solid fill") +} + +fn hsb(c: &Color) -> [f32; 3] { + display_hsb(&cms::active(), c) +} + +fn rgb(c: &Color) -> [f32; 3] { + cms::active().display_rgb(c) +} + +fn near(a: [f32; 3], b: [f32; 3], tol: f32) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() <= tol) +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// With Hue as the channel and a red fill, the field's top-left corner is white, its top-right +/// corner red and its bottom edge black. +#[test] +fn the_hue_box_picks_saturation_across_and_brightness_up() { + let mut h = harness(app(json!("#ff0000"), "hue")); + let field = rect_of(&h, "Color box"); + click(&mut h, field.left_top() + vec2(0.2, 0.2)); + assert!(near(rgb(&fill(h.state())), [1.0, 1.0, 1.0], 0.01), "{:?}", rgb(&fill(h.state()))); + click(&mut h, field.right_top() + vec2(-0.2, 0.2)); + assert!(near(rgb(&fill(h.state())), [1.0, 0.0, 0.0], 0.01), "the hue is kept through white: {:?}", rgb(&fill(h.state()))); + click(&mut h, at(field, 0.5, 0.0) + vec2(0.0, -0.2)); + assert!(near(rgb(&fill(h.state())), [0.0, 0.0, 0.0], 0.01), "{:?}", rgb(&fill(h.state()))); +} + +/// Red puts blue across and green up, as the Color Picker's field does, and red stays as it was. +#[test] +fn the_red_box_puts_blue_across_and_green_up() { + let mut h = harness(app(json!([0.2, 0.4, 0.6]), "red")); + let field = rect_of(&h, "Color box"); + let red = rgb(&fill(h.state()))[0]; + click(&mut h, at(field, 0.75, 0.25)); + assert!(near(rgb(&fill(h.state())), [red, 0.25, 0.75], 0.01), "{:?}", rgb(&fill(h.state()))); + let read = h.get_by_label("Color box").value().unwrap_or_default(); + assert!(read.starts_with("Blue ") && read.contains(", Green "), "{read}"); +} + +/// A drag in the field is one undo step, and a drag on the strip sets the third component. +#[test] +fn a_drag_in_the_field_is_one_undo_step_and_the_strip_sets_the_channel() { + let mut h = harness(app(json!([0.6, 0.3, 0.3]), "hue")); + let field = rect_of(&h, "Color box"); + let undo = undo_len(h.state()); + drag(&mut h, &[at(field, 0.2, 0.2), at(field, 0.5, 0.5), at(field, 0.8, 0.9)]); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + assert!(near(hsb(&fill(h.state())), [0.0, 0.8, 0.9], 0.01), "{:?}", hsb(&fill(h.state()))); + let strip = rect_of(&h, "Hue"); + drag(&mut h, &[strip.center_bottom() + vec2(0.0, -1.0), strip.center()]); + let after = hsb(&fill(h.state())); + assert!((after[0] - 180.0).abs() < 2.0 && (after[1] - 0.8).abs() < 0.01 && (after[2] - 0.9).abs() < 0.01, "{after:?}"); + assert_eq!(undo_len(h.state()), undo + 2); +} + +/// After a click on the strip, ↑ raises the channel by one unit, and the strip declares its range +/// and its adjust actions to screen readers. +#[test] +fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { + let mut h = harness(app(json!([0.6, 0.3, 0.3]), "brightness")); + let strip = rect_of(&h, "Brightness"); + click(&mut h, at(strip, 0.5, 0.5)); + let b = (hsb(&fill(h.state()))[2] * 100.0).round(); + key(&mut h, egui::Key::ArrowUp); + assert!((hsb(&fill(h.state()))[2] * 100.0 - (b + 1.0)).abs() < 0.01, "{:?}", hsb(&fill(h.state()))); + let node = h.get_by_label("Brightness").accesskit_node(); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a))); + assert_eq!((node.data().min_numeric_value(), node.data().max_numeric_value()), (Some(0.0), Some(100.0))); + let (target_node, target_tree) = node.locate(); + let data = Some(ActionData::NumericValue(25.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(1); + assert!((hsb(&fill(h.state()))[2] - 0.25).abs() < 0.01, "{:?}", hsb(&fill(h.state()))); +} + +/// `ui.colorWheel` sets the keys it is given and keeps the others, `{}` reads them, a value off the +/// list answers an error that names the accepted values and changes nothing, and `ui.inspect` +/// reports the settings. +#[test] +fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"})); + assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"})); + assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"})); + let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); + assert_eq!(e, "`view` must be wheel or box"); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err(); + assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing"); + let ui = crate::control::inspect(&app, &egui::Context::default()); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"})); +} + +/// The command's errors are translated in the catalogs that translate status and error messages, +/// and each translation keeps the accepted values. +#[test] +fn ui_color_wheel_errors_are_translated() { + let errors = [ + ("`view` must be wheel or box", &["wheel", "box"][..]), + ("`channel` must be hue, saturation, brightness, red, green or blue", &["hue", "saturation", "brightness", "red", "green", "blue"][..]), + ]; + for code in [ + "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", + "ca", "nl", "bs", "da", "id", + ] { + let lang = crate::i18n::Lang::from_code(code).expect("registered"); + for (error, values) in errors { + let shown = crate::i18n::message(lang, error); + assert_ne!(shown, error, "{code}"); + assert!(values.iter().all(|v| shown.contains(v)), "{code}: {shown}"); + } + } +} + +/// Params that are not an object, and a key the command does not take, are errors that change +/// nothing. +#[test] +fn ui_color_wheel_rejects_other_params() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap(); + let e = app.run("ui.colorWheel", json!("box")).unwrap_err(); + assert_eq!(e, "the params must be an object, not \"box\""); + let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); + assert_eq!(e, "the params must be an object, not [1]"); + let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel"); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing"); +} + +/// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does, +/// and its actions still set the fill from the last solid color the box shows. +#[test] +fn with_a_none_fill_the_strip_reads_zero_and_its_actions_set_the_fill() { + let mut app = app(json!("#ff0000"), "brightness"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let mut h = harness(app); + assert_eq!(h.get_by_label("Color box").value(), None, "no marker in the field"); + let node = h.get_by_label("Brightness").accesskit_node(); + assert_eq!(node.data().numeric_value(), Some(0.0), "no value on the strip"); + let last = hsb(&h.state().session.last_solid); + let (target_node, target_tree) = node.locate(); + let data = Some(ActionData::NumericValue(25.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(1); + assert!(near(hsb(&fill(h.state())), [last[0], last[1], 0.25], 0.01), "{last:?} → {:?}", hsb(&fill(h.state()))); +} + +/// `ui.colorWheel` answers every junk parameter without a panic. +#[test] +fn ui_color_wheel_answers_junk_params_without_a_panic() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3; + let mut app = app(json!("#336699"), "hue"); + for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) { + let _ = app.run("ui.colorWheel", p); + } +} + +/// The settings survive a JSON round trip of the preferences, and a saved value this build does +/// not know reads as the key's default without losing the other preferences. +#[test] +fn the_settings_are_kept_and_read_leniently() { + let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() }; + let saved = serde_json::to_value(&ui).unwrap(); + let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(back.color_wheel, ui.color_wheel); + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "triangle", "channel": 7, "later": true}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings::default()); + assert!(back.color_rgb_percent, "the other preferences are kept"); + // Each key reads on its own: an unknown channel does not reset a known view, or the reverse. + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "box", "channel": 7}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() }); + let mut odd = saved.clone(); + odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue }); + let mut odd = saved; + odd["color_wheel"] = json!("box"); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings::default()); + assert!(back.color_rgb_percent); +} + +/// The panel menu lists Wheel View and Box View with the shown one checked, and Box Channel; its +/// items set the view and the channel. +#[test] +fn the_panel_menu_switches_the_view_and_the_channel() { + let mut app = app(json!("#ff0000"), "hue"); + app.run("ui.colorWheel", json!({"view": "wheel"})).unwrap(); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which draw the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + assert!(super::panel_menu_items(app, ui, super::color_wheel::ID)); + }, + app, + ); + h.run_steps(3); + assert!(h.query_by_label("✓ Wheel View").is_some()); + h.get_by_label(" Box View").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.view, View::Box); + assert!(h.query_by_label("✓ Box View").is_some()); +} + +/// Every channel's box puts each color back where it reads it, and the strip's value is the +/// channel's own component. +#[test] +fn box_pick_inverts_box_pos_for_every_channel() { + for ch in Channel::ALL { + for hsb in [[30.0, 0.6, 0.8], [200.0, 0.25, 0.5], [300.0, 1.0, 1.0]] { + let (z, x, y) = box_pos(ch, hsb); + let back = box_pick(ch, z, x, y, [0.0, 0.0, 0.0]); + assert!(near(back, hsb, 1e-3), "{ch:?}: {hsb:?} → {back:?}"); + } + } + // A gray picked in an RGB channel keeps the hue it had. + assert_eq!(box_pick(Channel::Red, 0.5, 0.5, 0.5, [120.0, 0.3, 0.3])[0], 120.0); +} + +/// The Color Picker's channel slider is the same widget as the strip: after a click on it, ↑ raises +/// its channel by one unit. +#[test] +fn the_color_pickers_channel_slider_takes_the_arrow_keys() { + let mut app = app(json!([0.6, 0.3, 0.3]), "hue"); + app.run("ui.colorPicker", json!({})).unwrap(); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(1000.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + // The H field beside the values has the same name; the slider is the tall one. + let rail = h.get_all_by_label("H").map(|n| n.rect()).find(|r| r.height() > 100.0).expect("the channel slider"); + click(&mut h, rail.center()); + let picked = |h: &Harness<'static, VectorcraftApp>| -> [f32; 3] { + serde_json::from_value(h.state().ui.dialog.as_ref().unwrap().fields["__hsb"].clone()).unwrap() + }; + let before = picked(&h); + key(&mut h, egui::Key::ArrowUp); + let after = picked(&h); + assert!((after[0] - (before[0].round() + 1.0)).abs() < 1e-3, "{before:?} → {after:?}"); + assert!(near([0.0, after[1], after[2]], [0.0, before[1], before[2]], 1e-4), "{before:?} → {after:?}"); + let slider = h.get_all_by_label("H").find(|n| n.rect().height() > 100.0).expect("the channel slider"); + let node = slider.accesskit_node(); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a))); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index a29ca50e41..d1722e8b72 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -734,6 +734,10 @@ pub struct UiState { /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub color_rgb_percent: bool, + /// Color Wheel panel: the wheel or the box, and the box's channel (`ui.colorWheel`, + /// [`crate::panels::color_wheel::deserialize_settings`]). + #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] + pub color_wheel: crate::panels::color_wheel::Settings, /// Swatches panel: Show Recent Colors in its panel menu, which draws the panel's Recent Colors /// row (#6617; read as [`Self::color_show_recent_colors`] is). Separate from the Color panel's. #[serde(default = "yes", deserialize_with = "crate::panels::color::deserialize_show_recent_colors")] @@ -1206,6 +1210,7 @@ impl Default for UiState { color_hide_options: false, color_show_recent_colors: true, color_rgb_percent: false, + color_wheel: Default::default(), swatches_show_recent_colors: true, svg_options: Value::Null, place_link: true, diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 36145224d5..2ace2c7a67 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -35,9 +35,9 @@ pub(crate) use buttons::{button_width, icon_button_info, primary_button_width, s use chips::gradient_chip_colors; pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, gradient_chip, paint_chip, proxy_chip, swatch_tile}; pub use color::{ - FieldAxis, Live, RingResponse, SliderValue, WheelResponse, channel_slider, channel_slider_named, channel_slider_valued, color_field, color_mesh, - color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, - region_texture, ring_square, segment_color, segmented_wheel, stepped_area, + FieldAxis, Live, RingResponse, SliderValue, WheelResponse, channel_slider, channel_slider_named, channel_slider_stepped, channel_slider_valued, + color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, + hsb32, hue_ring, region_texture, ring_square, segment_color, segmented_wheel, stepped_area, }; pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase}; pub use drag::{ diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index f3d34d23e8..f7c1d9365b 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -499,23 +499,67 @@ pub fn channel_slider_valued( size: Vec2, track: &dyn Fn(f32) -> Color32, ) -> (Option, Live) { + let id = id_with(ui.scope_id(), id); + let (_, picked, phase) = channel_rail(ui, id, name, shown, value, true, size, track); + (picked, phase) +} + +/// [`channel_slider_valued`] that also responds to the keyboard and to screen readers' actions as +/// the rail of [`color_slider_stepped`] does: a click or a drag gives it the keyboard focus, and +/// while it has the focus ↑ and → raise the number `shown` holds and ↓ and ← lower it. When not +/// `marked`, the rail draws no arrows and screen readers read 0, as [`hue_ring`] does, while the +/// keys and actions still step from `shown`. Returns the new value from 0 to 1 that a click or a +/// drag gives, its phase, and the number in `shown`'s units that a key or an action gives. +#[allow(clippy::too_many_arguments)] +pub fn channel_slider_stepped( + ui: &mut Ui, + id: impl std::hash::Hash, + name: &str, + shown: Option, + value: f32, + marked: bool, + size: Vec2, + track: &dyn Fn(f32) -> Color32, +) -> (Option, Live, Option) { + let id = id_with(ui.scope_id(), id); + let read = if marked { shown.clone() } else { shown.as_ref().map(|s| SliderValue { value: 0.0, text: None, ..s.clone() }) }; + let (resp, picked, phase) = channel_rail(ui, id, name, read, value, marked, size, track); + let stepped = slider_keys(ui, &resp, shown); + (picked, phase, stepped.filter(|_| picked.is_none())) +} + +/// The vertical rail of [`channel_slider_valued`] with the id `id`, with its arrows at `value` +/// when `marked`: its response, the new value from 0 to 1 that a click or drag gives and the +/// phase. +#[allow(clippy::too_many_arguments)] +fn channel_rail( + ui: &mut Ui, + id: egui::Id, + name: &str, + shown: Option, + value: f32, + marked: bool, + size: Vec2, + track: &dyn Fn(f32) -> Color32, +) -> (Response, Option, Live) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); - let resp = ui.interact(rect, id_with(ui.scope_id(), id), Sense::click_and_drag()); + let resp = ui.interact(rect, id, Sense::click_and_drag()); let bar = rect.shrink2(vec2(6.0, 0.0)); gradient_strip(ui, bar, (bar.height() / 2.0).ceil().max(2.0) as usize, true, track); ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); let y = bar.bottom() - value.clamp(0.0, 1.0) * bar.height(); let fill = if resp.dragged() || resp.hovered() { t.text_strong } else { t.icon }; - for (x, d) in [(rect.left(), 1.0), (rect.right(), -1.0)] { + for (x, d) in [(rect.left(), 1.0), (rect.right(), -1.0)].into_iter().filter(|_| marked) { let tip = pos2(x + d * 5.0, y); ui.painter().add(egui::Shape::convex_polygon(vec![tip, pos2(x, y + 4.0 * d), pos2(x, y - 4.0 * d)], fill, Stroke::NONE)); } slider_info(ui, &resp, name, shown); - match pointer_phase(&resp) { + let (picked, phase) = match pointer_phase(&resp) { Some((p, phase)) => (Some(((bar.bottom() - p.y) / bar.height()).clamp(0.0, 1.0)), phase), None => (None, Live::Idle), - } + }; + (resp, picked, phase) } /// A hex colour field (`E67828`, no `#`) after a `#` label. Returns the text on commit when it diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cc52d58ed7..bb13e0d5f5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -265,7 +265,9 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?}` shows the wheel or the box (a +color field with a channel strip at its right) and picks the box's channel; it returns the settings, and `ui.inspect` +reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, diff --git a/docs/mcp.md b/docs/mcp.md index eb60457600..12c1f38184 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -620,6 +620,11 @@ applied colors still join the list while it is hidden. `ui.colorPanel {"rgbPerce RGB fields in percent, as a double-click right of an RGB field does, and `false` shows them from 0 to 255 again. `ui.colorRgbPercent` (Toggle RGB Percent in the command palette and Keyboard Shortcuts) switches between the two and answers true when the fields show in percent. +`ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's +strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` +shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off +the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with +the preferences. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ad7e9f4eab..e34f814534 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1502,7 +1502,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. Scores and estimates are unchanged. + - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. From b12c2c482c5e2b7bb789342344ce2c6690dcf8b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:40:47 -0800 Subject: [PATCH 026/138] Tests: the clipboard and Image Trace notes rows are found by their text --- crates/ui-egui/src/i18n/tests.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ab8aa4daca..a6e15ffd62 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2584,11 +2584,17 @@ fn counted_status_messages_take_the_plural_form() { assert_eq!(crate::dialogs::missing_links::changed_on_disk_status(2), COUNTED_STATUS_MESSAGES[2].1); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 1, "a note"), COUNTED_STATUS_MESSAGES[4].0); assert_eq!(crate::io::exported_with_notes("/out/a.svg", 2, "a note"), COUNTED_STATUS_MESSAGES[4].1); - let n = COUNTED_STATUS_MESSAGES.len(); - let owned = |(one, other): (&str, &str)| (one.to_string(), other.to_string()); - assert_eq!((copied_with_notes(false, 1, "a note"), copied_with_notes(false, 2, "a note")), owned(COUNTED_STATUS_MESSAGES[n - 3])); - assert_eq!((copied_with_notes(true, 1, "a note"), copied_with_notes(true, 2, "a note")), owned(COUNTED_STATUS_MESSAGES[n - 2])); - assert_eq!((traced_with_notes(1, "a note"), traced_with_notes(2, "a note")), owned(COUNTED_STATUS_MESSAGES[n - 1])); + // Each pair is found in the list by its text. + let listed = |got: (String, String), want: (&str, &str)| { + assert_eq!((got.0.as_str(), got.1.as_str()), want); + assert!(COUNTED_STATUS_MESSAGES.contains(&want), "{want:?} is not in COUNTED_STATUS_MESSAGES"); + }; + let copied = (copied_with_notes(false, 1, "a note"), copied_with_notes(false, 2, "a note")); + listed(copied, ("Copied with 1 note: a note", "Copied with 2 notes: a note")); + let cut = (copied_with_notes(true, 1, "a note"), copied_with_notes(true, 2, "a note")); + listed(cut, ("Cut with 1 note: a note", "Cut with 2 notes: a note")); + let traced = (traced_with_notes(1, "a note"), traced_with_notes(2, "a note")); + listed(traced, ("Traced with 1 note: a note", "Traced with 2 notes: a note")); // A note that holds placeholder text is not filled in again. assert_eq!(copied_with_notes(true, 3, "{n} {first}"), "Cut with 3 notes: {n} {first}"); assert_eq!(message(de(), &traced_with_notes(2, "{n}")), "Mit 2 Hinweisen nachgezeichnet: {n}"); From 8afbcacea529b1e589aa9c9ab25a400907427d1d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:16:38 -0800 Subject: [PATCH 027/138] i18n: catalogs keep one row for the message, and Gujarati Attributes differs from Properties Five catalogs (cs, fr, ko, nl, zh-hant) held two rows for the message "give one element" after the merge of main, which bundled_catalogs_are_consistent refuses. Each keeps the row main has. In Gujarati, Window > Attributes and Window > Properties showed the same word, which menu_items_side_by_side_have_different_labels refuses. Attributes now reads as its transliteration. --- crates/ui-egui/src/i18n/cs.tsv | 1 - crates/ui-egui/src/i18n/fr.tsv | 1 - crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 1 - crates/ui-egui/src/i18n/nl.tsv | 1 - crates/ui-egui/src/i18n/zh-hant.tsv | 1 - 6 files changed, 1 insertion(+), 6 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8e8cd97d4d..62a515f6a2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5994,7 +5994,6 @@ mark-style Japanese Japonské @msg a 3D effect on a group's fill or stroke draws nothing 3D efekt na výplni nebo tahu skupiny nic nekreslí @msg a 3D effect on a group's fill or stroke draws nothing to export 3D efekt na výplni nebo tahu skupiny nekreslí nic k exportu @msg The 3D object is too complex to export 3D objekt je pro export příliš složitý -@msg give one element zadejte jeden prvek @msg the element needs an id, the filter's name prvek potřebuje id, název filtru @msg an SVG filter's id is at most {MAX_NAME} characters id filtru SVG má nejvýše {MAX_NAME} znaků @msg <{_1}> isn't an element of an SVG filter <{_1}> není prvkem filtru SVG diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dac7cc5a1f..786de59089 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5562,7 +5562,6 @@ lighting Light Lumière @msg a 3D effect on a group's fill or stroke draws nothing un effet 3D sur le fond ou le contour d'un groupe ne dessine rien @msg a 3D effect on a group's fill or stroke draws nothing to export un effet 3D sur le fond ou le contour d'un groupe ne dessine rien à exporter @msg The 3D object is too complex to export L'objet 3D est trop complexe pour être exporté -@msg give one element indiquez un seul élément @msg the element needs an id, the filter's name l’élément doit avoir un id, le nom du filtre @msg an SVG filter's id is at most {MAX_NAME} characters l’id d’un filtre SVG compte au plus {MAX_NAME} caractères @msg <{_1}> isn't an element of an SVG filter <{_1}> n’est pas un élément de filtre SVG diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 716d851655..5ea47ab195 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -329,7 +329,7 @@ Attach Objects on Path પાથ પર ઑબ્જેક્ટ જોડો Attach to Active Plane સક્રિય સમતલ પર જોડો Attribute: ગુણધર્મ: - Attributes ગુણધર્મો + Attributes એટ્રિબ્યુટ્સ Author Title: લેખકનું શીર્ષક: Author: લેખક: Auto ઑટો diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index d2b30609b8..482b819173 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5571,7 +5571,6 @@ lighting Light 광원 @msg a 3D effect on a group's fill or stroke draws nothing 그룹의 칠이나 획에 있는 3D 효과는 아무것도 그리지 않습니다 @msg a 3D effect on a group's fill or stroke draws nothing to export 그룹의 칠이나 획에 있는 3D 효과는 내보낼 것을 그리지 않습니다 @msg The 3D object is too complex to export 3D 개체가 너무 복잡하여 내보낼 수 없습니다 -@msg give one element 요소를 하나 지정하세요 @msg the element needs an id, the filter's name 요소에는 필터 이름인 id가 필요합니다 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 필터의 id는 최대 {MAX_NAME}자입니다 @msg <{_1}> isn't an element of an SVG filter <{_1}>은(는) SVG 필터의 요소가 아닙니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0b05fcaaa9..3cdac52058 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7751,7 +7751,6 @@ mark-style Japanese Japans @msg a 3D effect on a group's fill or stroke draws nothing een 3D-effect op de vulling of contour van een groep tekent niets @msg a 3D effect on a group's fill or stroke draws nothing to export een 3D-effect op de vulling of contour van een groep tekent niets om te exporteren @msg The 3D object is too complex to export Het 3D-object is te complex om te exporteren -@msg give one element geef één -element op @msg the element needs an id, the filter's name het -element heeft een id nodig, de naam van het filter @msg an SVG filter's id is at most {MAX_NAME} characters de id van een SVG-filter is hoogstens {MAX_NAME} tekens lang @msg <{_1}> isn't an element of an SVG filter <{_1}> is geen element van een SVG-filter diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c12fe4bc1f..e2b4f89b5c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5699,7 +5699,6 @@ lighting Light 光源 @msg a 3D effect on a group's fill or stroke draws nothing 群組填色或筆畫上的 3D 效果不會繪製任何內容 @msg a 3D effect on a group's fill or stroke draws nothing to export 群組填色或筆畫上的 3D 效果沒有可匯出的內容 @msg The 3D object is too complex to export 3D 物件過於複雜,無法匯出 -@msg give one element 請提供一個 元素 @msg the element needs an id, the filter's name 元素需要 id,也就是濾鏡的名稱 @msg an SVG filter's id is at most {MAX_NAME} characters SVG 濾鏡的 id 最多 {MAX_NAME} 個字元 @msg <{_1}> isn't an element of an SVG filter <{_1}> 不是 SVG 濾鏡的元素 From dd08ea5f78b88b11ce5293d6cc4869f4134a2bee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:16:39 -0800 Subject: [PATCH 028/138] Keyboard Shortcuts: text.convertListToText is listed under Type The engine command had no menu path, so Keyboard Shortcuts grouped it by its id as Text > Convert to Text, next to the menu command's Type > Convert to Text. In 18 languages Text and Type are the same word, and the two rows showed one name. text.convertListToText now has the menu path Type, as text.fitHeadline has. The editor lists it as Type > Convert to Text and the menu command as Type > Bullets and Numbering > Convert to Text. command_list reports the menu Type for it. --- crates/engine/src/cmd/panelcmds.rs | 2 +- crates/ui-egui/src/shortcut_editor.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 2383d05a3a..5dae5d3b86 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -74,7 +74,7 @@ pub fn specs() -> Vec { cmd!( "text.convertListToText", "Convert to Text", - [], + ["Type"], None, "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index cee783d159..56ebed4e43 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -2741,6 +2741,8 @@ mod tests { assert_eq!(shown("file.new"), Some(("File".into(), "New…".into(), true))); assert_eq!(shown("text.fitHeadline"), Some(("Type".into(), "Fit Headline".into(), false))); assert_eq!(shown("type.fitHeadline"), Some(("Type".into(), "Fit Headline".into(), true))); + assert_eq!(shown("text.convertListToText"), Some(("Type".into(), "Convert to Text".into(), false))); + assert_eq!(shown("type.convertListToText"), Some(("Type › Bullets and Numbering".into(), "Convert to Text".into(), false))); for id in ["file.exportInBackground", "file.openInBackground"] { assert_eq!(shown(id), Some(("File".into(), "Continue in Background".into(), true)), "{id}"); } From 8047847792af9b953d62b84f5d07c62d0ec90bc3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:18:57 -0800 Subject: [PATCH 029/138] Status bar: Copy, Cut and Image Trace notes follow status changes, not only the text Copy and Cut record how many times the status has been set when they run. Their clipboard formats' notes now stay out when anything set the status in between, including a message with the same text, such as File > New clearing an empty status bar. An Image Trace without notes clears the counted message and hover notes that an earlier trace left, while nothing has set the status since. Any other message stays. File > New, choosing a data set and `ui.set`'s `status` set the status through `VectorcraftApp::status`, so these changes are counted. --- crates/ui-egui/src/app/commands.rs | 28 ++++++++++++++++++-------- crates/ui-egui/src/control.rs | 2 +- crates/ui-egui/src/sysclip.rs | 24 ++++++++++++++-------- crates/ui-egui/src/tests/sysclip.rs | 21 +++++++++++++++++++ crates/ui-egui/src/tests/trace_runs.rs | 22 ++++++++++++++++++++ crates/ui-egui/src/trace_runs.rs | 3 +++ 6 files changed, 83 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index ae2b0ea3b2..71b81f4745 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -263,7 +263,7 @@ impl VectorcraftApp { self.show_trace_notes(v); } if id == "file.new" { - self.ui.status.clear(); + self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). if v["previewMode"] == "pixel" { self.ui.view.pixel_preview = true; @@ -272,7 +272,7 @@ impl VectorcraftApp { // Choosing a data set, or stepping to one, clears the status bar. The reply's `warning` // below then shows when no object is bound to a variable the data set has a value for. if matches!(id, "dataset.select" | "dataset.next" | "dataset.prev") { - self.ui.status.clear(); + self.status(""); } // A font applied with Character's font menu or Find Font's Change becomes the newest recent font. // Find Font's Change records the family the text now carries (any name of it is stored as its @@ -306,7 +306,7 @@ impl VectorcraftApp { } // The message the Copy or Cut leaves is the one its clipboard formats' notes may replace. if copied { - self.clipboard_publishing.ran_with_status(&self.ui.status); + self.clipboard_publishing.ran_with_status(&self.ui); } r } @@ -322,13 +322,25 @@ impl VectorcraftApp { } /// Image Trace's notes in `reply` (a large image traces more slowly, or was scaled down): the - /// first of them and how many there are, with the rest for the message's hover. Without notes - /// the status bar keeps its message. + /// first of them and how many there are, with the rest for the message's hover. Without notes, + /// the message an earlier trace's notes left is cleared while nothing has set the status since, + /// and any other message stays. fn show_trace_notes(&mut self, reply: &Value) { let notes = io::notes_of(reply); - if let Some(first) = notes.first() { - let status = crate::trace_runs::traced_with_notes(notes.len(), first); - io::show_with_notes(self, status, notes); + match notes.first() { + Some(first) => { + let status = crate::trace_runs::traced_with_notes(notes.len(), first); + io::show_with_notes(self, status, notes); + self.trace_runs.notes_status = Some((self.ui.status.clone(), self.ui.status_sets)); + } + None => { + // Only while nothing has set the status since. + let left = self.trace_runs.notes_status.take(); + if left.is_some_and(|(status, sets)| status == self.ui.status && sets == self.ui.status_sets) { + self.status(""); + self.ui.status_notes = None; + } + } } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 26f67a0365..0b1dd4f3c9 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -2079,7 +2079,7 @@ fn set_ui(app: &mut VectorcraftApp, req: &ControlRequest) -> Outcome { r = app.run("window.panel", json!({"panel": pn})); } if let Some(st) = s("status") { - app.ui.status = st.to_string(); + app.status(st); } for (k, flag) in [ ("rulers", "view.rulers"), diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 0210a14294..218f235e98 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -103,9 +103,10 @@ pub(crate) struct Publishing { /// The latest one's formats could not be written: what the system clipboard held when the /// write failed, and the text of those formats. unwritten: Option<(Held, String)>, - /// The status bar's message when the latest one ran. Its formats' notes replace the message - /// only while the status bar still shows it. - status: String, + /// The status bar's message when the latest one ran, with [`crate::state::UiState::status_sets`] + /// then. Its formats' notes replace the message only while the status bar still shows it and + /// nothing has set the status since. + status: (String, u64), } impl Publishing { @@ -120,10 +121,17 @@ impl Publishing { self.latest.load(Ordering::SeqCst) } - /// `status` is the status bar's message the latest Copy or Cut left, which its formats' notes + /// `ui`'s status bar message is the one the latest Copy or Cut left, which its formats' notes /// may replace. - pub(crate) fn ran_with_status(&mut self, status: &str) { - status.clone_into(&mut self.status); + pub(crate) fn ran_with_status(&mut self, ui: &crate::state::UiState) { + ui.status.clone_into(&mut self.status.0); + self.status.1 = ui.status_sets; + } + + /// Does `ui`'s status bar still show the message the latest Copy or Cut left, with nothing + /// setting the status since? + fn shows_status(&self, ui: &crate::state::UiState) -> bool { + ui.status == self.status.0 && ui.status_sets == self.status.1 } } @@ -225,7 +233,7 @@ impl VectorcraftApp { let n = latest.fetch_add(1, Ordering::SeqCst).wrapping_add(1); self.clipboard_publishing.pending = true; self.clipboard_publishing.unwritten = None; - self.clipboard_publishing.ran_with_status(&self.ui.status); + self.clipboard_publishing.ran_with_status(&self.ui); // What the clipboard holds at the Copy or Cut: a copy made elsewhere before the write is newer. let before = self.services.system_clipboard.as_deref_mut().map(Held::now); let (tx, made) = channel(); @@ -277,7 +285,7 @@ impl VectorcraftApp { // The PNG's and PDF's notes (an image that couldn't be decoded, type in the // fallback font), unless another message has replaced the Copy or Cut's since. Ok(warnings) => { - if app.ui.status == app.clipboard_publishing.status { + if app.clipboard_publishing.shows_status(&app.ui) { show_copy_notes(app, cut, warnings); } } diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 0efb576fd9..021f75e7b9 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -449,6 +449,27 @@ fn a_copy_note_does_not_replace_a_newer_message() { assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Saved /out/a.vectorcraft", &None)); } +/// A message set while a Copy's formats are made on the worker stays even when its text is the +/// Copy's: an empty status bar set again, or File › New clearing it. +#[test] +fn a_copy_note_does_not_replace_a_message_with_the_same_text() { + for then in ["status", "file.new"] { + let (mut app, board, hold) = app_with_busy_worker(""); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + app.status(""); + run(&mut app, "edit.copy", json!({})); + if then == "status" { + app.status(""); + } else { + run(&mut app, "file.new", json!({})); + } + drop(hold); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG], "{then}"); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None), "{then}"); + } +} + /// Text copied in a field or with the Type tool after Copy, before the formats are written: they /// are not written, the system clipboard keeps the text, and Paste takes it. #[test] diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index 6da8e8a60e..6b3a9c91a9 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -148,6 +148,28 @@ fn a_trace_shows_how_many_notes_it_has() { } } +/// A trace without notes clears the message an earlier trace's notes left, with its hover notes, +/// and leaves any other message, one with the same text set since included. +#[test] +fn a_trace_without_notes_clears_an_earlier_traces_notes() { + let mut app = app(); + let earlier = "Traced with 2 notes: a note"; + for (then, kept) in [(None, ""), (Some("Ready"), "Ready"), (Some(earlier), earlier)] { + app.status(earlier); + app.trace_runs.notes_status = Some((earlier.to_string(), app.ui.status_sets)); + if let Some(then) = then { + app.status(then); + } + app.ui.status_notes = Some((app.ui.status.clone(), vec!["a note".to_string(), "another".to_string()])); + let v = app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + assert_eq!(v["warnings"], json!([]), "{then:?}"); + assert_eq!(app.ui.status, kept, "{then:?}"); + assert_eq!(app.ui.status_notes.is_none(), kept.is_empty(), "{then:?}"); + assert_eq!(app.trace_runs.notes_status, None, "{then:?}"); + app.run("edit.undo", json!({})).unwrap(); + } +} + /// Nothing to trace fails at once, before anything runs. #[test] fn nothing_to_trace_fails_at_once() { diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index 4055c15e1d..0a36fbcf14 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -75,6 +75,9 @@ pub struct TraceRuns { next_id: u64, /// Set by unit tests whose app traces off the UI thread. pub(crate) off_the_ui_thread: bool, + /// The status bar's message the latest Image Trace with notes left, with + /// [`crate::state::UiState::status_sets`] then. + pub(crate) notes_status: Option<(String, u64)>, } /// The status bar's line after an Image Trace with `n` notes, the first of them `first`. From 4b0a5f53e42204400798245b83222ab1522017f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:57:00 -0800 Subject: [PATCH 030/138] Status bar: a Copy or Cut without notes clears an earlier one's notes A Copy or Cut whose formats have no notes clears the counted message and hover notes that an earlier Copy or Cut left, while nothing has set the status since. A Copy of ruler guides alone does the same. Any other message stays. An Image Trace that made no paths shows its first note as it is, without "Traced with {n} notes", and keeps every note for the hover. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/ui-egui/src/app/commands.rs | 32 ++++++++++------------ crates/ui-egui/src/io.rs | 4 ++- crates/ui-egui/src/io/save.rs | 10 +++++++ crates/ui-egui/src/sysclip.rs | 17 ++++++++++-- crates/ui-egui/src/tests/sysclip.rs | 28 +++++++++++++++++-- crates/ui-egui/src/tests/sysclip_guides.rs | 14 +++++++++- crates/ui-egui/src/tests/trace_runs.rs | 31 +++++++++++---------- docs/mcp.md | 4 +-- docs/target-app-parity.md | 2 +- 9 files changed, 99 insertions(+), 43 deletions(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 71b81f4745..48870a0d02 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -322,26 +322,22 @@ impl VectorcraftApp { } /// Image Trace's notes in `reply` (a large image traces more slowly, or was scaled down): the - /// first of them and how many there are, with the rest for the message's hover. Without notes, - /// the message an earlier trace's notes left is cleared while nothing has set the status since, - /// and any other message stays. + /// first of them and how many there are, with the rest for the message's hover. A trace that + /// made no paths shows its first note as it is. Without notes, the message an earlier trace's + /// notes left is cleared while nothing has set the status since, and any other message stays. fn show_trace_notes(&mut self, reply: &Value) { let notes = io::notes_of(reply); - match notes.first() { - Some(first) => { - let status = crate::trace_runs::traced_with_notes(notes.len(), first); - io::show_with_notes(self, status, notes); - self.trace_runs.notes_status = Some((self.ui.status.clone(), self.ui.status_sets)); - } - None => { - // Only while nothing has set the status since. - let left = self.trace_runs.notes_status.take(); - if left.is_some_and(|(status, sets)| status == self.ui.status && sets == self.ui.status_sets) { - self.status(""); - self.ui.status_notes = None; - } - } - } + let left = self.trace_runs.notes_status.take(); + let Some(first) = notes.first() else { + io::clear_notes_left(self, left); + return; + }; + let status = match reply["paths"].as_u64() { + Some(0) => first.clone(), + _ => crate::trace_runs::traced_with_notes(notes.len(), first), + }; + io::show_with_notes(self, status, notes); + self.trace_runs.notes_status = Some((self.ui.status.clone(), self.ui.status_sets)); } fn set_command_warning(&mut self, id: &str, warning: &str) { diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index ee083d7d44..e0a515a19e 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -36,7 +36,9 @@ pub use open::{ pub(crate) use open::{open_file, opened_with_notes}; pub(crate) use save::save_current; pub use save::{ask_format_options, ask_pdf_options, remember_active_artboard, remember_view, save, save_pdf}; -pub(crate) use save::{export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to}; +pub(crate) use save::{ + clear_notes_left, export_path, is_web, notes_of, report_saved, show_with_notes, target_path, write_named, write_reporting, write_to, +}; #[cfg(test)] pub(crate) use save::{report_write_error, saved_status}; diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 6e38e8cc63..0512a224a6 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -499,6 +499,16 @@ pub(crate) fn show_with_notes(app: &mut VectorcraftApp, status: String, notes: V app.ui.status_notes = (!notes.is_empty()).then(|| (app.ui.status.clone(), notes)); } +/// Clear the status bar's message and its hover notes when `left` is still what the status bar +/// shows: a message with notes, and [`crate::state::UiState::status_sets`] when it was shown. +/// A message set since stays, one with the same text included. +pub(crate) fn clear_notes_left(app: &mut VectorcraftApp, left: Option<(String, u64)>) { + if left.is_some_and(|(status, sets)| status == app.ui.status && sets == app.ui.status_sets) { + app.status(""); + app.ui.status_notes = None; + } +} + /// [`report_saved`]'s message. pub(crate) fn saved_status(path: &str, r: &Value) -> String { let warnings = notes_of(r); diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 218f235e98..e2115e1ed6 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -107,6 +107,9 @@ pub(crate) struct Publishing { /// then. Its formats' notes replace the message only while the status bar still shows it and /// nothing has set the status since. status: (String, u64), + /// The status bar's message the latest Copy or Cut with notes left, with + /// [`crate::state::UiState::status_sets`] then. + notes_status: Option<(String, u64)>, } impl Publishing { @@ -147,12 +150,18 @@ pub(crate) fn copied_with_notes(cut: bool, n: usize, first: &str) -> String { } /// Show a Copy's (or with `cut`, a Cut's) formats' `notes` in the status bar: the first of them -/// and how many there are, with the rest for the message's hover. Without notes the status bar -/// keeps its message. +/// and how many there are, with the rest for the message's hover. Without notes, the message an +/// earlier Copy's or Cut's notes left is cleared while nothing has set the status since, and any +/// other message stays. pub(crate) fn show_copy_notes(app: &mut VectorcraftApp, cut: bool, notes: Vec) { - let Some(first) = notes.first() else { return }; + let left = app.clipboard_publishing.notes_status.take(); + let Some(first) = notes.first() else { + crate::io::clear_notes_left(app, left); + return; + }; let status = copied_with_notes(cut, notes.len(), first); crate::io::show_with_notes(app, status, notes); + app.clipboard_publishing.notes_status = Some((app.ui.status.clone(), app.ui.status_sets)); } /// Does a flavour of type `mime` load with `clipboard.importImage` ([`import_command`])? @@ -219,6 +228,8 @@ impl VectorcraftApp { // what another app copied before, and what another app copies after still wins (#3226). if !self.session.clipboard.has_art() { self.clear_system_clipboard(); + // Guides have no formats, so this Copy or Cut has no notes. + show_copy_notes(self, cut, vec![]); return; } if self.services.system_clipboard.is_none() { diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 021f75e7b9..609001bc9f 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -379,7 +379,7 @@ fn a_copy_while_the_worker_saves_writes_the_formats_at_once() { } /// A PNG whose header reads but whose pixel data is cut short, which the renderer can't decode. -fn cut_short_png() -> Vec { +pub(super) fn cut_short_png() -> Vec { let mut png = Vec::new(); image::RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255])) .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) @@ -388,7 +388,7 @@ fn cut_short_png() -> Vec { } /// The PNG's note on an image the renderer can't decode. -const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; +pub(super) const UNDECODED: &str = "an image couldn't be decoded and is missing from the picture"; /// Copy of an image the renderer can't decode: the PNG leaves it out, and once the formats are /// written the status bar says the Copy (or Cut) has 1 note and shows it, made at once or on the @@ -470,6 +470,30 @@ fn a_copy_note_does_not_replace_a_message_with_the_same_text() { } } +/// A Copy without notes clears the message an earlier Copy's notes left, with its hover notes, +/// made at once or on the worker. It leaves any other message, one with the same text set since +/// included. +#[test] +fn a_copy_without_notes_clears_an_earlier_copys_notes() { + let earlier = format!("Copied with 1 note: {UNDECODED}"); + for worker in [false, true] { + for (then, kept) in [(None, ""), (Some("Ready"), "Ready"), (Some(earlier.as_str()), earlier.as_str())] { + let (mut app, _) = if worker { app_with_worker() } else { app() }; + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + assert_eq!(app.ui.status, earlier, "worker {worker}, {then:?}"); + if let Some(then) = then { + app.status(then); + app.ui.status_notes = None; + } + copy_rect(&mut app); + background::wait_all(&mut app); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (kept, &None), "worker {worker}, {then:?}"); + } + } +} + /// Text copied in a field or with the Type tool after Copy, before the formats are written: they /// are not written, the system clipboard keeps the text, and Paste takes it. #[test] diff --git a/crates/ui-egui/src/tests/sysclip_guides.rs b/crates/ui-egui/src/tests/sysclip_guides.rs index 50c4535c37..f078ec5972 100644 --- a/crates/ui-egui/src/tests/sysclip_guides.rs +++ b/crates/ui-egui/src/tests/sysclip_guides.rs @@ -10,7 +10,7 @@ use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::clipboard::{PNG, TEXT}; -use crate::tests_sysclip::{app, app_with_busy_worker, copy_elsewhere, copy_rect, count, frame, pasted, run, written}; +use crate::tests_sysclip::{UNDECODED, app, app_with_busy_worker, copy_elsewhere, copy_rect, count, cut_short_png, frame, pasted, run, written}; use crate::{Services, VectorcraftApp, background}; fn guides(app: &VectorcraftApp) -> usize { @@ -42,6 +42,18 @@ fn a_guides_only_copy_pastes_the_guides_not_what_another_app_copied_before() { assert_eq!((guides(&app), count(&app)), (3, 0)); } +/// A guides-only Copy has no notes: it clears the message an earlier Copy's notes left. +#[test] +fn a_guides_only_copy_clears_an_earlier_copys_notes() { + let (mut app, _) = app(); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, "edit.copy", json!({})); + background::wait_all(&mut app); + assert_eq!(app.ui.status, format!("Copied with 1 note: {UNDECODED}")); + copy_guide(&mut app, 120.0); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("", &None)); +} + #[test] fn what_another_app_copies_after_a_guides_only_copy_is_pasted() { let (mut app, board) = app(); diff --git a/crates/ui-egui/src/tests/trace_runs.rs b/crates/ui-egui/src/tests/trace_runs.rs index 6b3a9c91a9..cf16a01090 100644 --- a/crates/ui-egui/src/tests/trace_runs.rs +++ b/crates/ui-egui/src/tests/trace_runs.rs @@ -111,6 +111,7 @@ fn without_threads_make_traces_at_once() { /// A trace's notes: the status bar names how many there are and the first of them, and keeps them /// all, in the reply's order, for the message's hover. Make and Make and Expand, at once, off the /// UI thread and from the Image Trace panel; a trace without notes leaves the status bar empty. +/// A trace that made no paths shows its first note as it is, and keeps them all for the hover. #[test] fn a_trace_shows_how_many_notes_it_has() { let mut app = app(); @@ -118,24 +119,24 @@ fn a_trace_shows_how_many_notes_it_has() { let mut png = vec![]; img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let data = vectorcraft_format::base64_encode(&png); - let p = json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "keepColors": ["#ff00ff", "#00ffff"]}}); + let slow = "The image is 1501 × 20 pixels, more than 1500 on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster."; + let some = ("#000000", "keepColors: none of the colors the trace found matches #00ffff, so nothing of it is traced."); + let none = ("#ff00ff", "Nothing was traced: none of the colors the trace found matches keepColors (#ff00ff, #00ffff)."); for (command, threaded, from_panel) in [("imageTrace.make", false, false), ("imageTrace.make", true, false), ("imageTrace.makeAndExpand", true, true)] { - app.run("file.place", json!({"name": "wide.png", "dataBase64": data, "link": false})).unwrap(); - app.trace_runs.off_the_ui_thread = threaded; - app.ui.status.clear(); - trace_runs::start(&mut app, command, p.clone(), from_panel).unwrap(); - wait(&mut app); - let notes = [ - "Nothing was traced: none of the colors the trace found matches keepColors (#ff00ff, #00ffff).", - "The image is 1501 × 20 pixels, more than 1500 on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster.", - ] - .map(String::from) - .to_vec(); - let status = format!("Traced with 2 notes: {}", notes[0]); - assert_eq!(app.ui.status, status, "{command}, threaded {threaded}"); - assert_eq!(app.ui.status_notes, Some((status, notes)), "{command}, threaded {threaded}"); + for (keep, first) in [some, none] { + app.run("file.place", json!({"name": "wide.png", "dataBase64": data, "link": false})).unwrap(); + app.trace_runs.off_the_ui_thread = threaded; + app.ui.status.clear(); + let p = json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "keepColors": [keep, "#00ffff"]}}); + trace_runs::start(&mut app, command, p, from_panel).unwrap(); + wait(&mut app); + let notes = [first, slow].map(String::from).to_vec(); + let status = if keep == some.0 { format!("Traced with 2 notes: {first}") } else { first.to_string() }; + assert_eq!(app.ui.status, status, "{command}, threaded {threaded}"); + assert_eq!(app.ui.status_notes, Some((status, notes)), "{command}, threaded {threaded}"); + } } // The 40 × 40 px image of [`app`] traces without notes: the status bar stays empty. let mut app = self::app(); diff --git a/docs/mcp.md b/docs/mcp.md index e5dad39780..916a0d78d6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7302,8 +7302,8 @@ area). Each one has a query command: transparent around them). As in `document.export`, the PDF's and the PNG's replies list their notes in `warnings` (type written in the fallback font…; the PNG's also say when an image couldn't be decoded). After Copy or Cut the app shows the first note of the PDF and PNG it offers in the status bar and how many there are, and hovering the message lists -them all, unless another message has replaced the Copy or Cut's while the formats were made. The `clipboard.export*` -replies still list every note. +them all, unless another message has replaced the Copy or Cut's while the formats were made. A Copy or Cut without +notes clears the notes message that an earlier Copy or Cut left. The `clipboard.export*` replies still list every note. What other apps copied goes into the clipboard with `clipboard.importSvg`, `clipboard.importPdf {dataBase64, page?, password?, editingData?}` (the page's objects; with `editingData: true` the data is a `.ai` or `.ait` file, and every diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 95bc0672d2..2631dd8956 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -606,7 +606,7 @@ since 2026-10-01. - **Clipped bottom-bar text (#6622):** A Help Bar hint wider than the window, such as the Dimension tool's hint in an 800-point window, ends in an ellipsis, as the status message does. In a narrow status bar the tool name ends in an ellipsis and leaves the status message its room. Resting the pointer on a clipped hint, tool name or message shows the full text in a tooltip that wraps within the window. Text that fits shows no tooltip, and screen readers receive the full text. Scores and estimates are unchanged. - **Notes of an open in the status bar:** After File › Open the status message names the first note that says reading the file left something out (the notes that make Save ask before writing over the file), else the first note, and counts them all. With several notes, resting the pointer on the message lists them in that order, as many as fit in the window and at most 30, then how many more. Screen readers receive the list after the message. Scores and estimates are unchanged. - **Notes of a save or an export in the status bar:** After Save, Save As, Save a Copy, Save as Template, Save a Timestamped Copy, Save as PDF, Export As, Export Selection, Export for Screens, Asset Export, Save for Web, Preview in Browser, Save for Office Documents, Text Export Options, a print to a file or the CSS Properties panel's export, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order the reply gives them (a save's notes start with what the format loses), as it lists an open's notes. Scores and estimates are unchanged. -- **Notes of a Copy, a Cut or an Image Trace in the status bar:** After Copy or Cut (also of artboards and of text in the Type tool) writes its formats to the system clipboard, and after Image Trace's Make or Make and Expand, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order they were made, as it lists a save's notes. A message shown while the clipboard formats were being made stays in place of the Copy's or Cut's notes. Scores and estimates are unchanged. +- **Notes of a Copy, a Cut or an Image Trace in the status bar:** After Copy or Cut (also of artboards and of text in the Type tool) writes its formats to the system clipboard, and after Image Trace's Make or Make and Expand, the status message names the first note and counts them all. With several notes, resting the pointer on the message lists them in the order they were made, as it lists a save's notes. A message shown while the clipboard formats were being made stays in place of the Copy's or Cut's notes. A Copy, Cut or trace without notes clears the notes message that an earlier one left, and leaves any other message. A trace that makes no paths shows its first note without the count. Scores and estimates are unchanged. - **What a save or an export loses, named first:** Each writer marks its notes as a loss (something of the document the file leaves out or writes differently) or a note on the options (an option it didn't apply or applied another way while the art reaches the file as it looks, or something an option turns off). The replies of the save and export commands list the losses first, each kind in the order given, across every file an export writes. The status message after a save or an export then names a loss when there is one: an export to lossy WebP of type in a font that isn't installed names the fallback-font note instead of the lossy WebP note. A print to a file and the print preview list theirs the same way: art outside the imageable area, type in a fallback font and transparency flattened for PostScript come before notes such as a fixed flatness that isn't written or copies per sheet that don't fit. Scores and estimates are unchanged. - **Canvas review follow-up:** Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Controlled-worker regression checks oversized width and height, high DPI and the render transform without allocating oversized images. Scores and estimates are unchanged. From 4d39068dfe12f176b6cee58debc86b99bc258df4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:59:44 -0800 Subject: [PATCH 031/138] i18n: the menu id test finds an id shown in backticks menu_items_never_show_an_id looked for a dotted id outside backticks only, so a label that was an id in backticks, or an effect id with no dot, passed. It now reads the label with its backticks removed and compares it with the item's command or effect id. --- crates/ui-egui/src/i18n/tests.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index fc98bdcff9..eb6b0cde72 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1690,6 +1690,26 @@ fn menu_items_side_by_side_have_different_labels() { assert!(same.is_empty(), "{} pairs of menu items look alike:\n{}", same.len(), same.join("\n")); } +/// Whether a menu label shows an id: a dotted command id, inside backticks or outside them, or +/// `key`, the command or effect id of its item, on its own. +fn label_shows_an_id(label: &str, key: &str) -> bool { + let plain = label.replace('`', " "); + !command_ids(&plain).is_empty() || plain.trim() == key +} + +#[test] +fn label_shows_an_id_finds_ids_in_backticks_and_bare_keys() { + let key = "type.convertListToText"; + assert!(label_shows_an_id("type.convertListToText", key)); + assert!(label_shows_an_id("`type.convertListToText`", key)); + assert!(label_shows_an_id("`type.convertListToText", key)); + assert!(label_shows_an_id("Convert (`slice.list`)", key)); + assert!(label_shows_an_id("roughen", "roughen")); + assert!(label_shows_an_id("`roughen`", "roughen")); + assert!(!label_shows_an_id("Convert to Text", key)); + assert!(!label_shows_an_id("Roughen…", "roughen")); +} + /// Menu items show words, never the command or effect id their catalog row is keyed by. #[test] fn menu_items_never_show_an_id() { @@ -1698,7 +1718,7 @@ fn menu_items_never_show_an_id() { if let crate::menus::Item::Cmd(l, id, p) = item { let key = menu_item_effect(id, p).unwrap_or(id); let shown = shown_menu_label(lang, item).unwrap_or_default(); - if !command_ids(shown).is_empty() && command_ids(l).is_empty() { + if label_shows_an_id(shown, key) && !label_shows_an_id(l, key) { out.push(format!("{}: {l:?} ({key}) shows {shown:?}", lang.0.code)); } } From 674b3ba6753430cd1e1f1237f5b4aeb939dd9a4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:59:43 -0800 Subject: [PATCH 032/138] Color Wheel: an action on the strip without a marker applies its number With a None fill, a set-value action, a key or an increment on the box view's channel strip that leaves the number at the last solid color's value now sets the fill, as the field and the hue ring do. --- .../src/panels/tests_color_wheel_box.rs | 21 ++++++++++++ crates/ui-egui/src/widgets/color.rs | 32 ++++++++++++------- 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index d3866fd5d9..0b59a44d98 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -235,6 +235,27 @@ fn with_a_none_fill_the_strip_reads_zero_and_its_actions_set_the_fill() { assert!(near(hsb(&fill(h.state())), [last[0], last[1], 0.25], 0.01), "{last:?} → {:?}", hsb(&fill(h.state()))); } +/// With None, a screen reader's set-value action or an increment at the top of the strip sets the +/// fill, even when the number equals the last solid color's. +#[test] +fn with_a_none_fill_the_strip_applies_an_action_that_leaves_its_number() { + let mut app = app(json!("#ff0000"), "brightness"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let mut h = harness(app); + let last = hsb(&h.state().session.last_solid); + assert!((last[2] - 1.0).abs() < 0.01, "{last:?}"); + for (action, data) in [(Action::SetValue, Some(ActionData::NumericValue(100.0))), (Action::Increment, None)] { + h.state_mut().run("paint.setFill", json!({"none": true})).unwrap(); + h.run_steps(1); + let (target_node, target_tree) = h.get_by_label("Brightness").accesskit_node().locate(); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action, data })); + h.run_steps(1); + let paint = crate::panels::current_paints(h.state()).0; + let c = paint.color().unwrap_or_else(|| panic!("{action:?} left the fill as {paint:?}")); + assert!(near(hsb(&c), last, 0.01), "{action:?}: {last:?} → {:?}", hsb(&c)); + } +} + /// `ui.colorWheel` answers every junk parameter without a panic. #[test] fn ui_color_wheel_answers_junk_params_without_a_panic() { diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index f7c1d9365b..535bb70b0a 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -141,7 +141,7 @@ pub fn color_slider_stepped( ) -> (Option, Live, Option) { let id = id_with(ui.scope_id(), id); let (resp, picked, phase) = color_rail(ui, id, name, shown.clone(), value, width, track); - let stepped = slider_keys(ui, &resp, shown); + let stepped = slider_keys(ui, &resp, shown, false); (picked, phase, stepped.filter(|_| picked.is_none())) } @@ -152,12 +152,13 @@ pub fn color_slider_stepped( /// `shown`'s units that a key or an action gives. pub fn stepped_area(ui: &Ui, resp: &Response, name: &str, shown: Option) -> Option { slider_info(ui, resp, name, shown.clone()); - slider_keys(ui, resp, shown) + slider_keys(ui, resp, shown, false) } /// The focus, keys, actions and focus outline of [`color_slider_stepped`] on the control `resp`: -/// the number a key or an action gives. -fn slider_keys(ui: &Ui, resp: &Response, shown: Option) -> Option { +/// the number a key or an action gives. With `always`, a key or an action that leaves the number +/// as it was still gives it. +fn slider_keys(ui: &Ui, resp: &Response, shown: Option, always: bool) -> Option { let id = resp.id; // Focus a click or a drag gave shows no outline until a key steps the rail: the outline tells // a keyboard user where the focus is, and after a drag it only framed the rail. @@ -177,7 +178,7 @@ fn slider_keys(ui: &Ui, resp: &Response, shown: Option) -> Option(by_pointer)); @@ -190,8 +191,9 @@ fn slider_keys(ui: &Ui, resp: &Response, shown: Option) -> Option Option { +/// readers' actions on it ([`color_slider_stepped`]); `None` when they leave it as it was, unless +/// `always` and a key or an action came. +fn rail_step(ui: &Ui, id: egui::Id, focused: bool, always: bool, s: &SliderValue) -> Option { use egui::accesskit::{Action, ActionData}; use egui::{Event, Key}; let (lo, hi) = (*s.range.start(), *s.range.end()); @@ -208,6 +210,8 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Option return true, } + asked = true; false }); }); @@ -246,8 +251,9 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option 0; + v = by(v, up as f64 - down as f64).clamp(lo, hi); // The last set-value request this frame. let set = i.accesskit_action_requests(id, Action::SetValue).last().and_then(|request| match request.data { Some(ActionData::NumericValue(value)) if value.is_finite() => Some(value), @@ -260,9 +266,10 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Date: Sat, 14 Nov 2026 10:26:53 -0800 Subject: [PATCH 033/138] i18n: the hu and ja catalogs carry one "give one element" row The merge of main left two copies of the message in hu and ja, and bundled_catalogs_are_consistent failed on the duplicate. The copy this branch added is removed and main's row stays. --- crates/ui-egui/src/i18n/hu.tsv | 1 - crates/ui-egui/src/i18n/ja.tsv | 1 - 2 files changed, 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d5fd6a6199..d3c2cc01e5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5977,7 +5977,6 @@ imageTrace Outline Körvonal @msg a 3D effect on a group's fill or stroke draws nothing a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmit @msg a 3D effect on a group's fill or stroke draws nothing to export a csoport kitöltésén vagy körvonalán lévő 3D effektus nem rajzol semmi exportálhatót @msg The 3D object is too complex to export A 3D objektum túl összetett az exportáláshoz -@msg give one element adjon meg egy elemet @msg the element needs an id, the filter's name a elemnek id kell, a szűrő neve @msg an SVG filter's id is at most {MAX_NAME} characters egy SVG-szűrő id-je legfeljebb {MAX_NAME} karakter @msg <{_1}> isn't an element of an SVG filter a(z) <{_1}> nem SVG-szűrő eleme diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 206101305c..6285dcb929 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5652,7 +5652,6 @@ lighting Light ライト @msg a 3D effect on a group's fill or stroke draws nothing グループの塗りまたは線にある 3D 効果は何も描画しません @msg a 3D effect on a group's fill or stroke draws nothing to export グループの塗りまたは線にある 3D 効果には書き出せる描画がありません @msg The 3D object is too complex to export 3D オブジェクトが複雑すぎるため書き出せません -@msg give one element 要素を 1 つ指定してください @msg the element needs an id, the filter's name 要素には id (フィルターの名前) が必要です @msg an SVG filter's id is at most {MAX_NAME} characters SVG フィルターの id は {MAX_NAME} 文字までです @msg <{_1}> isn't an element of an SVG filter <{_1}> は SVG フィルターの要素ではありません From cefaeefca942b8978110dc79193ae10730c8991d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:38:25 -0800 Subject: [PATCH 034/138] Scripts: grants kept earlier in a run keep the code evaluated before a later one Keeping a second grant with Always marked all the code the run had evaluated as recorded, so the run's end skipped the grants kept before it, and they kept the code list from when they were kept. The next run that evaluated that code withdrew them. Keeping a grant now writes the current code list into the grants the run kept before it as well. --- crates/engine/src/script/files.rs | 12 +++++++++- crates/engine/src/tests/script_io.rs | 35 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index be813e3a74..216e27f677 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -569,7 +569,7 @@ impl Disk { /// Adds grants of `paths` (with `write`, folders when `folder`) for this script to the grants /// file, with the code the run has evaluated so far, written whole to a file beside it that then - /// takes its place. + /// takes its place. The grants the run kept before are given the same code. fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; // A grants file that is there but cannot be read is left as it is. @@ -577,6 +577,16 @@ impl Disk { let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); + // The grants this run kept before take the code evaluated since, as the run's end would + // have given them. + for g in &mut grants { + if g["script"] == *script + && g["sha256"] == *hash + && self.kept.iter().any(|(p, w, f)| g["path"] == *shown(p) && g["write"] == *w && g["folder"] == *f) + { + g["code"] = serde_json::json!(code); + } + } for p in paths { let path = shown(p); grants diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index ae782692f3..4463c19e97 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1766,6 +1766,41 @@ fn script_file_grants_keep_the_code_evaluated_after_the_dialog() { let _ = std::fs::remove_dir_all(base); } +/// A grant kept with Always before a second one is kept in the same run also keeps the code the +/// run evaluated between the two, so the next run that evaluates it keeps both grants. +#[test] +fn script_file_grants_kept_earlier_in_a_run_keep_the_code_evaluated_before_a_later_grant() { + let base = folder("grantbetween"); + let first = base.join("picked/a.txt"); + let second = base.join("picked/b.txt"); + write(&first, b"a"); + write(&second, b"b"); + let text = format!( + "var a = new File({:?}); var ka = a.open('r');\n\ + if (!ka) File.openDialog('a');\n\ + var between = eval('new File(a.fsName).open(\"r\")');\n\ + var b = new File({:?}); var kb = b.open('r');\n\ + if (!kb) File.openDialog('b');\n\ + vc.log([ka, between, kb, new File(a.fsName).open('r')]);", + first.to_string_lossy(), + second.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![first.to_string_lossy().into_owned()], always: true })); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![second.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, true, false, true]])); + start_framed(&mut s, &base, &text); + assert_eq!( + pump_to_picker(&mut s).unwrap().unwrap()["log"], + json!([[true, true, true, true]]), + "the first grant keeps the code evaluated before the second" + ); + let _ = std::fs::remove_dir_all(base); +} + /// Code another script left in a named engine withdraws a script's kept grants in that engine. #[test] fn script_file_grants_are_withdrawn_by_code_another_script_left_in_the_engine() { From d435ae1a27abf9b9efdd01ab771663d9ef22e3a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:32:26 -0800 Subject: [PATCH 035/138] Scripts: an open file that is renamed is read under its new path's rules `rename` moved the write path of open File objects but left the path they were read from at the old name. When new code then withdrew the kept grant for the folder, a grant the run still held for the old path let the object go on giving the file's bytes. The read path now moves with the write path. --- crates/engine/src/script/files.rs | 13 +++++++++---- crates/engine/src/tests/script_io.rs | 29 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 216e27f677..19c1a37409 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1844,11 +1844,16 @@ fn rename(host: &Host, a: &[Data]) -> Result { if std::fs::rename(&from, &to).is_err() { return Ok(error(WRITE_FAILED)); } - // Open objects of the file, or of files in the folder, write to the new path. - for file in disk.open.values_mut() { - if let Some(rest) = file.target.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { - file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); + // Open objects of the file, or of files in the folder, write to the new path, and the rules for + // reading apply to them there. + let moved = |p: &mut Option| { + if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + *p = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } + }; + for file in disk.open.values_mut() { + moved(&mut file.target); + moved(&mut file.read_from); } // The old path no longer holds the file, so the report names it as well as the new one. disk.wrote(&from); diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 4463c19e97..1943a11bab 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1913,6 +1913,35 @@ fn script_files_open_under_a_withdrawn_grant_are_not_read() { let _ = std::fs::remove_dir_all(base); } +/// A file opened for reading and then renamed is read under the rules for its new path: when new code +/// withdraws the kept grant for its folder, a grant the run still holds for its old path does not let +/// the object give more of it. +#[test] +fn script_files_renamed_while_open_are_read_under_their_new_path() { + let base = folder("grantwithdrawnrenamed"); + let dir = base.join("picked"); + let file = dir.join("in.txt"); + write(&file, b"secret"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('r')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ var a = f.readch(); File.openDialog('p'); var n = new File(f.fsName).rename('r.txt'); eval('1');\n\ + var r = f.read(), e = f.error; vc.log([a, n, r, e]); }}", + file.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![file.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["s", true, "", DENIED]])); + let _ = std::fs::remove_dir_all(base); +} + /// The folder that holds the settings is kept out of every grant: a pick there gives `null` with the /// error, a grant written into the grants file for it is not taken, and the script cannot write the /// grants file through its data folder. From 907a75971085ef82f0c2d2e609a98fe0442da735 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:31:05 -0800 Subject: [PATCH 036/138] Unit Converter: one length in every unit, read from and applied to the selection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Unit Converter › Unit Converter Panel opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha). A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, and Width or Height picks which one the fields show; the size read is dropped when the document, its selection, Use Preview Bounds or Measure Type by Glyph Bounds changes. Apply sets that side through object.setBounds as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and Transform Object Only, Pattern Only or Both), as one undo step, and adds none when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on, and is named with its unit for screen readers. - addon.units.convert {value, unit?} gives a length in every unit, and addon.units.selectionSize {} gives the selection's width and height the same way. Neither changes the document. convert reads at most 1024 bytes and 128 + - * / signs. - The decimal comma rule of the number fields moves from ui-egui to vectorcraft_doc::decimal_point, so the command reads "0,5 mm" as the fields do. - The Transform panel's pattern switches are built by with_pattern_switches, which run_transform and Apply share. Closes #5528, as proposed by @ruchirguitar. --- ROADMAP.md | 1 + crates/doc/src/lib.rs | 2 +- crates/doc/src/units.rs | 30 ++ crates/engine/src/cmd/addons.rs | 2 + crates/engine/src/cmd/addons/units.rs | 124 ++++++++ crates/engine/src/cmd/addons/units/tests.rs | 200 ++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 2 + crates/engine/tests/command_sweep.rs | 6 + crates/ui-egui/src/addons.rs | 2 + crates/ui-egui/src/addons/units.rs | 194 +++++++++++ crates/ui-egui/src/addons/units/tests.rs | 301 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/transform.rs | 10 +- crates/ui-egui/src/state.rs | 1 + crates/ui-egui/src/widgets/numeric.rs | 24 +- docs/mcp.md | 39 +++ docs/target-app-parity.md | 4 + 45 files changed, 1080 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/cmd/addons/units.rs create mode 100644 crates/engine/src/cmd/addons/units/tests.rs create mode 100644 crates/ui-egui/src/addons/units.rs create mode 100644 crates/ui-egui/src/addons/units/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index dabed3eb94..0ed5bbd6b9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -130,6 +130,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c286492236..9e31f8e6c4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -158,7 +158,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, parse_number}; +pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 234513df1d..052830ef0f 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -308,6 +308,36 @@ fn percent(s: &str) -> Option { } } +/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` +/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed +/// after the value the field shows) is 100 mm (#5684). A number written with both separators has +/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a +/// number that reads as thousands ([`thousands`]). +pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { + if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } +} + +/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three +/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it +/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are +/// decimals). +fn thousands(text: &str) -> bool { + let number = text.trim().trim_start_matches('-'); + let Some((whole, rest)) = number.split_once(',') else { return false }; + let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); + (1..=3).contains(&whole.len()) + && whole.bytes().all(|b| b.is_ascii_digit()) + && !whole.starts_with('0') + && part.len() == 3 + && unit.trim().chars().all(char::is_alphabetic) +} + +/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length +/// near the largest number in points is too large in Q and Ha. +pub fn finite_in_every_unit(pt: f64) -> bool { + pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite()) +} + /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as /// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. pub fn parse_number(s: &str) -> Option { diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 66c67651a3..e1e31ebdfb 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -13,6 +13,7 @@ mod pen; mod select; mod shapes; mod typetools; +mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; @@ -32,5 +33,6 @@ pub fn specs() -> Vec { v.extend(select::specs()); v.extend(shapes::specs()); v.extend(typetools::specs()); + v.extend(units::specs()); v } diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs new file mode 100644 index 0000000000..5d362a0acb --- /dev/null +++ b/crates/engine/src/cmd/addons/units.rs @@ -0,0 +1,124 @@ +//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once. +//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and +//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type +//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]). +//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform +//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the +//! UI's; the panel applies a length to the selection with `object.setBounds`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit}; +use vectorcraft_render::effects; + +use super::super::{CommandSpec, always, bad, cmd, has_selection}; +use crate::{Result, Session}; + +const CONVERT: &str = "addon.units.convert"; +const SELECTION_SIZE: &str = "addon.units.selectionSize"; +/// The most characters of a refused value an error message shows. +const SHOWN_CHARS: usize = 64; +/// The longest `value` or `unit` text `addon.units.convert` reads, in bytes. +const MAX_TEXT_LEN: usize = 1024; +/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one +/// level of recursion per sign. +const MAX_OPERATORS: usize = 128; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "addon.units.convert", + "Convert Units", + [], + None, + "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + always, + convert + ), + cmd!( + query "addon.units.selectionSize", + "Selection Size in Units", + [], + None, + "{} the selection's width and height as the Transform panel shows them (its bounding box, rotated with rotated objects; with Use Preview Bounds, the visual bounds; with anchor points selected (Direct Selection), the box around those points), each as addon.units.convert gives it → {width: {points, units}, height: {points, units}}", + has_selection, + selection_size + ), + ] +} + +/// The length `pt` (points) in every unit of [`Unit::EAST_ASIAN`]: `{points, units: [{unit, +/// label, number, text}]}`. +pub fn in_every_unit(pt: f64) -> Value { + let units: Vec = + Unit::EAST_ASIAN.iter().map(|u| json!({"unit": u.key(), "label": u.label(), "number": u.number(pt), "text": u.format(pt)})).collect(); + json!({ "points": pt, "units": units }) +} + +/// The unit `p` gives for a number without a suffix (points when left out). +fn unit_param(p: &Value) -> Result { + let Some(given) = p.get("unit").filter(|u| !u.is_null()) else { return Ok(Unit::Points) }; + let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian); + named.ok_or_else(|| { + let u = match given { + Value::String(s) => clipped(s).escape_debug().to_string(), + other => shown(other), + }; + bad(CONVERT, format!("unknown units `{u}`")) + }) +} + +fn convert(_: &mut Session, p: &Value) -> Result { + let unit = unit_param(p)?; + let Some(v) = p.get("value").filter(|v| !v.is_null()) else { + return Err(bad(CONVERT, "missing `value`")); + }; + let pt = match v { + Value::String(s) if readable(s) => unit.parse(&decimal_point(s)), + Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)), + _ => None, + }; + let pt = pt.filter(|&pt| finite_in_every_unit(pt)); + pt.map(in_every_unit).ok_or_else(|| { + let v = shown(v); + bad(CONVERT, format!("`value` must be a number, not {v}")) + }) +} + +/// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` +/// signs? +fn readable(s: &str) -> bool { + s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS +} + +/// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON, +/// an array as `[…]` and an object as `{…}`. +fn shown(v: &Value) -> String { + match v { + Value::String(s) => Value::String(clipped(s)).to_string(), + Value::Array(_) => "[…]".into(), + Value::Object(_) => "{…}".into(), + other => other.to_string(), + } +} + +/// `s` cut at [`SHOWN_CHARS`] characters, with "…" when it is longer. +fn clipped(s: &str) -> String { + match s.char_indices().nth(SHOWN_CHARS) { + Some((at, _)) => format!("{}…", s.get(..at).unwrap_or_default()), + None => s.to_string(), + } +} + +fn selection_size(s: &mut Session, _: &Value) -> Result { + let st = s.doc()?; + let measure = s.bounds_measure(); + let b = match effects::preview::anchor_bounds_with(&st.selection, &st.doc, measure) { + Some(r) => Some(OrientedBox::aligned(r)), + None => s.transform_box(&st.selection.objects), + }; + let b = b.ok_or_else(|| bad(SELECTION_SIZE, "nothing selected"))?; + Ok(json!({ "width": in_every_unit(b.rect.width()), "height": in_every_unit(b.rect.height()) })) +} diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs new file mode 100644 index 0000000000..2b572c3d11 --- /dev/null +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -0,0 +1,200 @@ +//! Unit Converter's commands: a length in every unit, read as number fields read it, the selection's +//! size as the Transform panel measures it, bad params refused, and nothing in the document changed. + +use serde_json::{Value, json}; +use vectorcraft_doc::Unit; + +use crate::{EngineError, Session}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn convert(s: &mut Session, p: Value) -> Value { + s.execute("addon.units.convert", &p).unwrap() +} + +/// The row of `r` for the unit with key `key`. +fn row<'a>(r: &'a Value, key: &str) -> &'a Value { + r["units"].as_array().unwrap().iter().find(|u| u["unit"] == key).unwrap_or_else(|| panic!("{key} in {r}")) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn a_length_comes_back_in_every_unit_in_order() { + let mut s = session(); + let r = convert(&mut s, json!({"value": "10mm"})); + assert!(near(r["points"].as_f64().unwrap(), 720.0 / 25.4)); + let keys: Vec<&str> = r["units"].as_array().unwrap().iter().map(|u| u["unit"].as_str().unwrap()).collect(); + assert_eq!(keys, Unit::EAST_ASIAN.map(Unit::key)); + assert_eq!(row(&r, "millimeters")["number"], "10"); + assert_eq!(row(&r, "millimeters")["text"], "10 mm"); + assert_eq!(row(&r, "centimeters")["text"], "1 cm"); + assert_eq!(row(&r, "inches")["text"], "0.3937 in"); + assert_eq!(row(&r, "points")["text"], "28.346 pt"); + assert_eq!(row(&r, "q")["text"], "40 Q"); + assert_eq!(row(&r, "ha")["text"], "40 H"); + assert_eq!(row(&r, "pixels")["number"], row(&r, "points")["number"], "pixels are points"); + assert_eq!(row(&r, "feetInches")["label"], "Feet & Inches"); + // Each row is what a field of that unit shows for the length. + for u in Unit::EAST_ASIAN { + let pt = 720.0 / 25.4; + assert_eq!(row(&r, u.key())["text"], u.format(pt), "{u:?}"); + assert_eq!(row(&r, u.key())["number"], u.number(pt), "{u:?}"); + } +} + +#[test] +fn values_read_as_number_fields_read_them() { + let mut s = session(); + let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap(); + assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "2p6"})), 30.0)); + assert!(near(pt(&mut s, json!({"value": "1080/2 px"})), 540.0)); + assert!(near(pt(&mut s, json!({"value": "3cm*50%"})), 1.5 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": "13q"})), 13.0 * 72.0 / 101.6)); + // A number without a unit is in `unit`, points by default. + assert!(near(pt(&mut s, json!({"value": 12})), 12.0)); + assert!(near(pt(&mut s, json!({"value": 2, "unit": "in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "2", "unit": "Inches"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": "3+1", "unit": "cm"})), 4.0 * 72.0 / 2.54)); + assert!(near(pt(&mut s, json!({"value": 6, "unit": "ha"})), 6.0 * 72.0 / 101.6)); + assert!(near(pt(&mut s, json!({"value": 1, "unit": "feetInches"})), 864.0)); + // A suffix wins over `unit`. + assert!(near(pt(&mut s, json!({"value": "1in", "unit": "mm"})), 72.0)); + // A decimal comma reads as a point, as in the number fields. + assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0)); + assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); + // A sum of 128 signs still reads. + assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); +} + +#[test] +fn keys_the_commands_do_not_take_are_refused() { + let s = session(); + s.check_params("addon.units.convert", &json!({"value": 1, "unit": "mm"})).unwrap(); + s.check_params("addon.units.selectionSize", &json!({})).unwrap(); + for (id, p) in [ + ("addon.units.convert", json!({"value": 1, "units": "mm"})), + ("addon.units.convert", json!({"value": 1, "ids": [1]})), + ("addon.units.selectionSize", json!({"ids": [1]})), + ("addon.units.selectionSize", json!({"value": 1})), + ] { + match s.check_params(id, &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, id, "{p}"), + other => panic!("{id} {p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_follows_preview_bounds_and_selected_anchors() { + let mut s = session(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id], "weight": 10})).unwrap(); + let wh = |s: &mut Session| { + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) + }; + assert_eq!(wh(&mut s), (72.0, 36.0), "geometric bounds"); + // Use Preview Bounds: the stroke's outer half on every side. + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap(); + let (w, h) = wh(&mut s); + assert!(near(w, 82.0) && near(h, 46.0), "{w} × {h}"); + s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": false})).unwrap(); + // Two neighboring anchors selected (Direct Selection): the box around them, one edge of the + // rectangle. + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let (w, h) = wh(&mut s); + assert!((near(w, 72.0) && near(h, 0.0)) || (near(w, 0.0) && near(h, 36.0)), "{w} × {h}"); +} + +#[test] +fn it_needs_no_document_and_changes_nothing() { + let mut s = Session::new(); + assert!(near(convert(&mut s, json!({"value": "1in"}))["points"].as_f64().unwrap(), 72.0)); + let mut s = session(); + let (before, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + convert(&mut s, json!({"value": "5mm"})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn bad_values_and_units_are_refused() { + let mut s = session(); + for p in [ + json!({}), + json!({"value": null}), + json!({"value": "abc"}), + json!({"value": "10 furlongs"}), + json!({"value": "1in/0"}), + json!({"value": "1e400"}), + // Finite in points, too large in Q and Ha. + json!({"value": 1.5e308}), + json!({"value": "1.5e308"}), + // A thousands comma is refused, as the number fields refuse it. + json!({"value": "1,000 mm"}), + json!({"value": "1,000.5"}), + // A long expression is refused instead of exhausting the stack. + json!({"value": format!("1{}", "+1".repeat(200_000))}), + json!({"value": format!("1{}", "+1".repeat(129))}), + json!({"value": true}), + json!({"value": [1]}), + json!({"value": 1, "unit": "furlongs"}), + json!({"value": 1, "unit": 5}), + json!({"value": 1, "unit": ["mm"]}), + ] { + match s.execute("addon.units.convert", &p) { + Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"), + other => panic!("{p}: expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn a_long_value_or_unit_is_refused_with_a_short_message() { + let mut s = session(); + let long = "9".repeat(100_000); + for (p, says) in [ + (json!({"value": long.clone()}), format!("`value` must be a number, not \"{}…\"", "9".repeat(64))), + (json!({"value": [long.clone()]}), "`value` must be a number, not […]".to_string()), + (json!({"value": 1, "unit": long.clone()}), format!("unknown units `{}…`", "9".repeat(64))), + (json!({"value": 1, "unit": "furlongs"}), "unknown units `furlongs`".to_string()), + (json!({"value": "a\"b\nc"}), "`value` must be a number, not \"a\\\"b\\nc\"".to_string()), + ] { + match s.execute("addon.units.convert", &p) { + Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().ends_with(&says), "{e}"), + other => panic!("expected BadParams, got {other:?}"), + } + } +} + +#[test] +fn the_selection_size_is_the_transform_panels() { + let mut s = session(); + assert!(s.execute("addon.units.selectionSize", &json!({})).is_err(), "nothing selected"); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(row(&r["width"], "inches")["text"], "1 in"); + assert_eq!(row(&r["height"], "picas")["text"], "3 p"); + // A turned object keeps its own sides, as the Transform panel's W and H show them. + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let r = s.execute("addon.units.selectionSize", &json!({})).unwrap(); + let b = s.transform_box(&s.doc().unwrap().selection.objects).unwrap(); + assert!(near(r["width"]["points"].as_f64().unwrap(), b.rect.width())); + assert!(near(r["width"]["points"].as_f64().unwrap(), 72.0)); + assert!(near(r["height"]["points"].as_f64().unwrap(), 36.0)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the rotation is a step"); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..71c0e1a011 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -77,6 +77,8 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.shapes.star", "addon.type.releasePath", "addon.type.textTweaker", + "addon.units.convert", + "addon.units.selectionSize", "appearance.addEffect", "appearance.addFill", "appearance.addStroke", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 797ca39f52..0ea1350d78 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -925,6 +925,12 @@ fn structured_junk() { ("addon.type.releasePath", json!({"mode": "text", "keepOriginal": false, "id": 2})), ("addon.type.releasePath", json!({"mode": ["both"], "keepOriginal": "no", "ids": "all", "id": -1})), ("addon.type.releasePath", json!({"mode": "nope", "keepOriginal": 1e308, "ids": [1.5, null, "x"]})), + // Unit Converter add-on. + ("addon.units.convert", json!({"value": f64::MAX, "unit": "yards"})), + ("addon.units.convert", json!({"value": "1e308m*1e308", "unit": "q"})), + ("addon.units.convert", json!({"value": "-2p6/0", "unit": ["mm"]})), + ("addon.units.convert", json!({"value": [1], "unit": 5})), + ("addon.units.selectionSize", json!({"ids": [u64::MAX]})), // Cutting Tools add-on: Stencil Bridges. ("addon.cutting.bridges", json!({"width": 0.01, "count": 16, "direction": "shortest", "keepOriginal": true})), ("addon.cutting.bridges", json!({"width": 1000, "count": 1, "direction": "horizontal", "keepOriginal": false})), diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index 522f82bd2b..3d706881c1 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -14,6 +14,7 @@ pub mod pen; pub mod select; pub mod shapes; pub mod typetools; +pub mod units; use crate::menus::Item; @@ -34,6 +35,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sub("Type Tools", typetools::menu()), + Item::Sub("Unit Converter", units::menu()), Item::Sep, ] } diff --git a/crates/ui-egui/src/addons/units.rs b/crates/ui-egui/src/addons/units.rs new file mode 100644 index 0000000000..2e2801a2ca --- /dev/null +++ b/crates/ui-egui/src/addons/units.rs @@ -0,0 +1,194 @@ +//! Unit Converter in the interface: its submenu (Object › Plug-ins › Unit Converter), which opens +//! the panel, and the panel. The panel shows one length in every unit of +//! [`Unit::EAST_ASIAN`], one number field each. A value typed in any field (units and arithmetic, +//! as every number field reads them) updates the others as it is typed; text that does not read +//! leaves them as they were. From Selection reads the selection's width and height +//! (`addon.units.selectionSize`), and Width or Height picks which of the two the fields show; the +//! size read is dropped when the document, its selection or the bounds measure changes. Apply gives the selection that +//! width or height through `object.setBounds` as the Transform panel's W or H field does (its +//! reference point, Constrain Width and Height Proportions and Transform Object Only, Pattern +//! Only or Both), as one undo step. Each field's copy button puts its value on the clipboard, with +//! its unit when Copy with Units is on. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{Unit, finite_in_every_unit}; + +use crate::VectorcraftApp; +use crate::menus::Item; +use crate::panels::transform; +use crate::panels::{pstate, set_pstate}; +use crate::widgets; + +/// The panel's id (`window.panel {panel: "unitConverter"}`). +pub const ID: &str = "unitConverter"; +/// The command that measures the selection. +pub const SELECTION_SIZE: &str = "addon.units.selectionSize"; + +/// Where the panel keeps its length and choices (panel state). +const STATE: &str = "unit-converter"; +/// A row (label, field, copy button and two gaps) is 214 pt wide, inside the 240 pt body of the +/// default 260 pt floating panel with room for its scroll bar. +const LABEL_W: f32 = 90.0; +const FIELD_W: f32 = 90.0; + +/// Object › Plug-ins › Unit Converter. +pub fn menu() -> Vec { + vec![Item::Cmd("Unit Converter Panel", "window.panel", json!({ "panel": ID }))] +} + +/// The selection's side the fields show and Apply sets. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +pub(crate) enum Side { + #[default] + Width, + Height, +} + +impl Side { + /// `object.setBounds`'s param for this side. + fn key(self) -> &'static str { + match self { + Side::Width => "width", + Side::Height => "height", + } + } +} + +/// The panel's length and choices. +#[derive(Clone, Default, Debug, PartialEq)] +pub(crate) struct Converter { + /// The length (points), none until one is typed or read from the selection. + pub points: Option, + /// The selection's width and height (points) From Selection last read. + pub size: Option<(f64, f64)>, + /// The active document's uid and revision, and the bounds measure (Use Preview Bounds, + /// glyph bounds), when [`Converter::size`] was read. + pub read_at: Option, + /// Which of them the fields show, and the side Apply sets. + pub side: Side, + /// Copy puts the unit after the number. + pub with_units: bool, +} + +impl Converter { + /// Show `side`: the fields take that side of the size From Selection read, if any. + pub fn pick(&mut self, side: Side) { + self.side = side; + if let Some((w, h)) = self.size { + self.points = Some(if side == Side::Width { w } else { h }); + } + } + + /// A length typed in a field: after From Selection it replaces the side shown, so picking the + /// other side and back keeps it. + pub fn set(&mut self, pt: f64) { + self.points = Some(pt); + if let Some((w, h)) = &mut self.size { + *(if self.side == Side::Width { w } else { h }) = pt; + } + } + + /// Drop the size From Selection read when the active document is no longer the one it was + /// read from or is measured another way (`now`: its uid and revision, which a change to the + /// selection also moves, and the bounds measure). The length the fields show stays. + pub fn follow(&mut self, now: Option) { + if self.size.is_some() && self.read_at != now { + self.size = None; + self.read_at = None; + } + } + + /// What the copy button of the field in `unit` puts on the clipboard. + pub fn copied(&self, unit: Unit) -> Option { + self.points.map(|pt| if self.with_units { unit.format(pt) } else { unit.number(pt) }) + } +} + +/// A document's uid and revision, and the bounds measure. +pub(crate) type ReadAt = (u64, u64, vectorcraft_effects::preview::Measure); + +/// The active document's uid and revision, and the bounds measure. +pub(crate) fn document_now(app: &VectorcraftApp) -> Option { + app.session.active().map(|st| (st.uid, st.revision, app.session.bounds_measure())) +} + +/// From Selection: read the selection's width and height into `st`, and show the side picked. +pub(crate) fn from_selection(app: &mut VectorcraftApp, st: &mut Converter) -> Result<(), String> { + let r = app.run(SELECTION_SIZE, json!({}))?; + if let (Some(w), Some(h)) = (r["width"]["points"].as_f64(), r["height"]["points"].as_f64()) { + st.size = Some((w, h)); + st.read_at = document_now(app); + st.pick(st.side); + } + Ok(()) +} + +/// Apply: give the selection the length as its width or height, as the Transform panel's W or H +/// field does: from its reference point (a symbol instance's registration point with Use +/// Registration Point for Symbol on), with the other side following under Constrain Width and +/// Height Proportions, and with the panel menu's Transform Object Only, Pattern Only or Both. +/// Without a length it does nothing. +pub(crate) fn apply(app: &mut VectorcraftApp, ui: &Ui, st: &Converter) -> Result<(), String> { + let Some(pt) = st.points else { return Ok(()) }; + let reference = app.selection_box().map_or_else(|| transform::reference_index(ui), |b| transform::panel_reference(app, ui, &b).index); + let params = json!({ st.side.key(): pt, "reference": reference, "proportional": transform::proportional(app, ui) }); + let params = transform::with_pattern_switches(app, params); + app.run("object.setBounds", params)?; + Ok(()) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let mut st: Converter = pstate(ui.ctx(), STATE); + st.follow(document_now(app)); + for unit in Unit::EAST_ASIAN { + widgets::label_row(ui, unit.label(), LABEL_W, |ui| { + // A length too large to show in one of the units (near the largest number, in Q and + // Ha) leaves the others as they were, as text that does not read does. + if let Some(pt) = widgets::num_field_live(ui, ("unit-converter", unit.key()), st.points, unit, FIELD_W) + && finite_in_every_unit(pt) + { + st.set(pt); + } + // The button's name and tip carry the row's unit ("Copy Millimeters"). + let tip = format!("{} {}", tl!("Copy"), tl!(unit.label())); + let copy = widgets::icon_button_enabled(ui, "copy", &tip, false, st.points.is_some(), 22.0); + if copy.clicked() + && let Some(text) = st.copied(unit) + { + ui.ctx().copy_text(text); + } + }); + } + if widgets::check(ui, "Copy with Units", st.with_units, true) { + st.with_units = !st.with_units; + } + ui.add_space(6.0); + widgets::subheader(ui, tl!("Selection")); + let selected = app.session.active().is_some_and(|d| !d.selection.is_empty()); + ui.horizontal(|ui| { + for (side, label) in [(Side::Width, "Width"), (Side::Height, "Height")] { + if widgets::radio(ui, label, st.side == side, true) { + st.pick(side); + } + } + }); + ui.horizontal(|ui| { + let read = ui.add_enabled_ui(selected, |ui| widgets::flat_button(ui, tl!("From Selection"), 110.0)).inner; + if read.clicked() + && let Err(e) = from_selection(app, &mut st) + { + app.status(e); + } + let set = ui.add_enabled_ui(selected && st.points.is_some(), |ui| widgets::flat_button(ui, tl!("Apply"), 70.0)).inner; + if set.clicked() + && let Err(e) = apply(app, ui, &st) + { + app.status(e); + } + }); + set_pstate(ui.ctx(), STATE, st); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/units/tests.rs b/crates/ui-egui/src/addons/units/tests.rs new file mode 100644 index 0000000000..63d35f8b8d --- /dev/null +++ b/crates/ui-egui/src/addons/units/tests.rs @@ -0,0 +1,301 @@ +//! Unit Converter's submenu and panel: one field per unit, typing in one updates the others and +//! text that does not read leaves them alone, From Selection reads the selection's size, Apply +//! sets the side picked as one undo step and adds none when nothing changes, and Copy writes the +//! value with or without its unit. + +use egui::{Event, Key, Modifiers, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::Unit; +use vectorcraft_engine::Session; + +use super::{Converter, ID, STATE, Side, apply, document_now, from_selection, show}; +use crate::panels::{pstate, set_pstate}; +use crate::tests_labels::{painted_text, shapes_text}; +use crate::{VectorcraftApp, menus}; + +/// An app with a selected 72 × 36 pt rectangle. +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 72, "height": 36})).unwrap(); + app +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// The selection's width and height. +fn size(app: &mut VectorcraftApp) -> (f64, f64) { + let r = app.run("addon.units.selectionSize", json!({})).unwrap(); + (r["width"]["points"].as_f64().unwrap(), r["height"]["points"].as_f64().unwrap()) +} + +#[test] +fn the_submenu_opens_the_panel() { + let mut app = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Unit Converter"] && e.label == "Unit Converter Panel").expect("listed"); + menus::invoke(&mut app, "window.panel", item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); +} + +#[test] +fn the_panel_has_a_field_for_every_unit_and_its_buttons() { + let mut app = app(); + let text = painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), STATE, Converter { points: Some(720.0 / 25.4), ..Converter::default() }); + show(app, ui); + }); + for u in Unit::EAST_ASIAN { + assert!(text.lines().any(|l| l == u.label()), "{} in {text}", u.label()); + } + for s in ["10 mm", "1 cm", "0.3937 in", "28.346 pt", "40 Q", "40 H"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + for s in ["Copy with Units", "Selection", "Width", "Height", "From Selection", "Apply"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } +} + +#[test] +fn typing_in_a_field_updates_the_others_and_text_that_does_not_read_leaves_them() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + (pstate::(&ctx, STATE), shapes_text(&out)) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the first field, Points, which selects its text so typing replaces it. + frame(&mut app, vec![tab]); + frame(&mut app, vec![]); + let (st, _) = frame(&mut app, vec![Event::Text("1in/2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 36.0)), "{st:?}"); + let (st, text) = frame(&mut app, vec![]); + assert!(near(st.points.unwrap(), 36.0)); + for s in ["0.5 in", "3 p", "12.7 mm", "1.27 cm"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + // Text that does not read keeps the length the other fields show. + let (st, text) = frame(&mut app, vec![Event::Text("x".into())]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); + assert!(text.lines().any(|l| l == "12.7 mm"), "{text}"); + // So does a length too large to show in Q and Ha. + let select_all = Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }; + frame(&mut app, vec![select_all]); + // 1.7e308 pt: finite in points. + let (st, _) = frame(&mut app, vec![Event::Text(format!("17{}", "0".repeat(307)))]); + assert!(near(st.points.unwrap(), 36.0), "{st:?}"); +} + +#[test] +fn picking_a_side_shows_that_side_of_the_size_read() { + let mut st = Converter { size: Some((72.0, 36.0)), ..Converter::default() }; + st.pick(Side::Height); + assert_eq!((st.side, st.points), (Side::Height, Some(36.0))); + st.pick(Side::Width); + assert_eq!(st.points, Some(72.0)); + // A length typed after From Selection replaces the side shown, and picking the other side and + // back keeps it. + st.set(100.0); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + st.pick(Side::Width); + assert_eq!((st.points, st.size), (Some(100.0), Some((100.0, 36.0)))); + // Before From Selection a side keeps the length typed. + let mut st = Converter::default(); + st.set(5.0); + st.pick(Side::Height); + assert_eq!((st.points, st.size), (Some(5.0), None)); +} + +#[test] +fn copy_writes_the_value_with_or_without_its_unit() { + let mut st = Converter { points: Some(72.0), ..Converter::default() }; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1")); + st.with_units = true; + assert_eq!(st.copied(Unit::Inches).as_deref(), Some("1 in")); + assert_eq!(st.copied(Unit::Millimeters), Some(Unit::Millimeters.format(72.0))); + assert_eq!(Converter::default().copied(Unit::Points), None, "nothing to copy before a length"); +} + +/// Apply `st` in a frame whose shared reference point (the Transform panel's) is `reference`. +fn apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) { + try_apply_at(app, st, reference).unwrap(); +} + +/// [`apply_at`], with its result. +fn try_apply_at(app: &mut VectorcraftApp, st: &Converter, reference: usize) -> Result<(), String> { + let ctx = egui::Context::default(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), reference)); + let mut result = Ok(()); + ctx.run_ui(Default::default(), |ui| result = apply(app, ui, st)).textures_delta.clear(); + result +} + +/// The selection's bounding box. +fn bounds(app: &mut VectorcraftApp) -> vectorcraft_geom::Rect { + app.selection_box().unwrap().rect +} + +#[test] +fn from_selection_reads_the_size_and_apply_sets_the_side_picked() { + let mut app = app(); + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + assert_eq!((st.size, st.points), (Some((72.0, 36.0)), Some(72.0))); + st.pick(Side::Height); + assert_eq!(st.points, Some(36.0)); + // Apply: 1 in high, from the centre, as one undo step. + let steps = undo_steps(&app); + st.points = Some(72.0); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 72.0) && near(h, 72.0), "{w} × {h}"); + assert_eq!(undo_steps(&app), steps + 1); + // The same length again changes nothing and adds no step. + apply_at(&mut app, &st, 4); + assert_eq!(undo_steps(&app), steps + 1); + // Without a length Apply does nothing. + apply_at(&mut app, &Converter::default(), 4); + assert_eq!(undo_steps(&app), steps + 1); + // Width, kept at the left edge (reference 3). + let x0 = bounds(&mut app).x0; + let st = Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }; + apply_at(&mut app, &st, 3); + let b = bounds(&mut app); + assert!(near(b.width(), 144.0) && near(b.x0, x0), "{b:?}"); + assert_eq!(undo_steps(&app), steps + 2); +} + +/// Apply follows the Transform panel's W and H fields: Constrain Width and Height Proportions +/// scales the other side too, and Transform Pattern Only leaves the object's size alone. +#[test] +fn apply_follows_the_transform_panels_proportions_and_pattern_choice() { + let mut app = app(); + app.run("prefs.set", json!({"key": "constrainProportions", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(144.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "{w} × {h}"); + app.run("prefs.set", json!({"key": "constrainProportions", "value": false})).unwrap(); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "pattern"})).unwrap(); + // The object has no pattern to transform: whether the command reports that or not, the + // object keeps its size. + let _ = try_apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + let (w, h) = size(&mut app); + assert!(near(w, 144.0) && near(h, 72.0), "the object keeps its size: {w} × {h}"); + app.run("prefs.set", json!({"key": "transformPanelPatterns", "value": "both"})).unwrap(); + apply_at(&mut app, &Converter { points: Some(10.0), side: Side::Width, ..Converter::default() }, 4); + assert!(near(size(&mut app).0, 10.0)); +} + +/// With Use Registration Point for Symbol on and one symbol instance selected, Apply keeps the +/// symbol's registration point (here its top-left corner) in place, as the Transform panel does, +/// instead of the shared reference point (the centre). +#[test] +fn apply_keeps_a_symbol_instances_registration_point() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); + let id = app.run("symbol.new", json!({"name": "Corner", "registration": 0})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("prefs.set", json!({"key": "useRegistrationPointForSymbol", "value": true})).unwrap(); + apply_at(&mut app, &Converter { points: Some(160.0), side: Side::Width, ..Converter::default() }, 4); + assert_eq!(bounds(&mut app), vectorcraft_geom::Rect::new(100.0, 50.0, 260.0, 90.0)); +} + +/// The size From Selection read belongs to the selection it was read from: after the selection +/// changes, picking a side keeps the length shown instead of showing the old object's side, and +/// Apply sets that length. +#[test] +fn a_size_read_from_another_selection_is_dropped() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp| { + ctx.run_ui(Default::default(), |ui| show(app, ui)).textures_delta.clear(); + pstate::(&ctx, STATE) + }; + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + set_pstate(&ctx, STATE, st); + // Drawing the panel again with nothing changed keeps it. + assert_eq!(frame(&mut app).size, Some((72.0, 36.0))); + // Another object selected. + app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 20, "height": 50})).unwrap(); + let mut st = frame(&mut app); + assert_eq!((st.size, st.points), (None, Some(72.0)), "{st:?}"); + st.pick(Side::Height); + assert_eq!(st.points, Some(72.0), "not the first object's height"); + apply_at(&mut app, &st, 4); + let (w, h) = size(&mut app); + assert!(near(w, 20.0) && near(h, 72.0), "{w} × {h}"); + // So does a change to the document. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); + // And a change to how the selection is measured (Use Preview Bounds), which leaves the + // document as it is. + let mut st = Converter::default(); + from_selection(&mut app, &mut st).unwrap(); + st.follow(document_now(&app)); + assert!(st.size.is_some()); + app.run("prefs.set", json!({"key": "usePreviewBounds", "value": true})).unwrap(); + st.follow(document_now(&app)); + assert_eq!(st.size, None); +} + +/// Each row's copy button reads as copying that row's unit, so a screen reader tells the twelve +/// apart, and the fields are named by their rows. +#[test] +fn each_copy_button_and_field_is_named_with_its_unit() { + let mut app = app(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, STATE, Converter { points: Some(72.0), ..Converter::default() }); + ctx.run_ui(Default::default(), |ui| show(&mut app, ui)).textures_delta.clear(); + let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A label node carries its text as its value. + let label_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + let buttons: Vec = + nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Button).filter_map(|(_, n)| n.label().map(str::to_string)).collect(); + for u in Unit::EAST_ASIAN { + let name = format!("Copy {}", u.label()); + assert_eq!(buttons.iter().filter(|b| **b == name).count(), 1, "{name} in {buttons:?}"); + // The row fits the 240 pt body of the default 260 pt floating panel, with 10 pt left for + // its scroll bar. + let button = nodes.iter().find(|(_, n)| n.label() == Some(name.as_str())).and_then(|(_, n)| n.bounds()).unwrap(); + assert!(button.x1 <= 230.0, "{name} ends at {}", button.x1); + // The field of the row is labeled by the row's label. + let field = nodes + .iter() + .find(|(_, n)| n.role() != egui::accesskit::Role::Button && n.labelled_by().iter().any(|l| label_of(*l).as_deref() == Some(u.label()))); + assert!(field.is_some(), "a field labeled {}", u.label()); + } +} + +#[test] +fn from_selection_with_nothing_selected_reports_it_and_keeps_the_length() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let mut st = Converter { points: Some(10.0), ..Converter::default() }; + assert!(from_selection(&mut app, &mut st).is_err()); + assert_eq!((st.points, st.size), (Some(10.0), None)); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 28944173dd..2528cb6731 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6426,6 +6426,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` трябва да е "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` трябва да е [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Преобразувател на мерни единици + Unit Converter Panel Панел „Преобразувател на мерни единици“ + Copy with Units Копиране с мерните единици + From Selection От селекцията + # Color Effects add-on: Select by Color Kind. Select by Color Kind Избиране по вид цвят Objects with Spot Colors Обекти с плакатни цветове diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 01b90e5148..c5dbf362ef 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6767,6 +6767,11 @@ shape Open Otvoren Create Swatch Legend… Kreiraj legendu uzoraka boja… HEX HEX Help Bar Traka pomoći +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pretvarač jedinica + Unit Converter Panel Panel Pretvarač jedinica + Copy with Units Kopiraj s jedinicama + From Selection Iz odabira # Type Tools add-on (Object › Plug-ins › Type Tools). Type Tools Alati za tekst Text Tweaker… Podešavanje teksta… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4ddd1d5605..25a4b4ae51 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6960,6 +6960,12 @@ anchor Points: Punts: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` ha de ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` ha de ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertidor d’unitats + Unit Converter Panel Tauler Convertidor d’unitats + Copy with Units Copia amb les unitats + From Selection De la selecció + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecciona per tipus de color Objects with Spot Colors Objectes amb colors directes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 211982f086..fa3f76a611 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6991,6 +6991,12 @@ anchor Points: Body: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musí být "free", "keepAngles" nebo "symmetric" @msg `{key}` must be [x, y] `{key}` musí být [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Převodník jednotek + Unit Converter Panel Panel Převodník jednotek + Copy with Units Kopírovat s jednotkami + From Selection Z výběru + # Color Effects add-on: Select by Color Kind. Select by Color Kind Vybrat podle druhu barvy Objects with Spot Colors Objekty s přímými barvami diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b3de0ae89a..ca2070c486 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6442,6 +6442,12 @@ anchor Points: Punkter: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` skal være "free", "keepAngles" eller "symmetric" @msg `{key}` must be [x, y] `{key}` skal være [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhedsomregner + Unit Converter Panel Panelet Enhedsomregner + Copy with Units Kopiér med enheder + From Selection Fra markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markér efter farvetype Objects with Spot Colors Objekter med spotfarver diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d0610144ef..6f585c66fe 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6586,6 +6586,12 @@ anchor Points: Punkte: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` muss "free", "keepAngles" oder "symmetric" sein @msg `{key}` must be [x, y] `{key}` muss [x, y] sein +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Einheitenumrechner + Unit Converter Panel Einheitenumrechner-Bedienfeld + Copy with Units Mit Einheiten kopieren + From Selection Aus Auswahl + # Color Effects add-on: Select by Color Kind. Select by Color Kind Nach Farbart auswählen Objects with Spot Colors Objekte mit Volltonfarben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d03f8c6958..f13e494831 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6943,6 +6943,12 @@ anchor Points: Σημεία: @msg `mode` must be "free", "keepAngles" or "symmetric" Το `mode` πρέπει να είναι "free", "keepAngles" ή "symmetric" @msg `{key}` must be [x, y] Το `{key}` πρέπει να είναι [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Μετατροπέας μονάδων + Unit Converter Panel Πλαίσιο Μετατροπέας μονάδων + Copy with Units Αντιγραφή με μονάδες + From Selection Από την επιλογή + # Color Effects add-on: Select by Color Kind. Select by Color Kind Επιλογή κατά είδος χρώματος Objects with Spot Colors Αντικείμενα με χρώματα spot diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3e8bd23752..cab3dd8174 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6935,6 +6935,12 @@ anchor Points: Puntos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` debe ser "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` debe ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Panel Conversor de unidades + Copy with Units Copiar con unidades + From Selection Desde la selección + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleccionar por tipo de color Objects with Spot Colors Objetos con tintas planas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d408220f47..2917f064d7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7021,6 +7021,12 @@ anchor Points: Pisteet: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` on oltava "free", "keepAngles" tai "symmetric" @msg `{key}` must be [x, y] `{key}` on oltava [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Yksikkömuunnin + Unit Converter Panel Yksikkömuunnin-paneeli + Copy with Units Kopioi yksiköineen + From Selection Valinnasta + # Color Effects add-on: Select by Color Kind. Select by Color Kind Valitse värityypin mukaan Objects with Spot Colors Objektit, joissa on spottivärejä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 318bbbeb44..72803f301d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6986,6 +6986,12 @@ anchor Points: Points : @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` doit être "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` doit être [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertisseur d’unités + Unit Converter Panel Panneau Convertisseur d’unités + Copy with Units Copier avec les unités + From Selection Depuis la sélection + # Color Effects add-on: Select by Color Kind. Select by Color Kind Sélectionner par type de couleur Objects with Spot Colors Objets avec tons directs diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 716d851655..63e2119daa 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -752,6 +752,7 @@ Copy into the document's folder દસ્તાવેજના ફોલ્ડરમાં નકલ કરો Copy only fonts you own or are licensed to install. ફક્ત તમારી માલિકીના અથવા ઇન્સ્ટોલ કરવાના લાઇસન્સવાળા ફોન્ટ્સની નકલ કરો. Copy to User Defined વપરાશકર્તા-વ્યાખ્યાયિતમાં નકલ કરો + Copy with Units એકમો સાથે નકલ કરો Copyright કૉપીરાઇટ Copyright Info URL: કૉપીરાઇટ માહિતી URL: Copyright Notice: કૉપીરાઇટ સૂચના: @@ -1468,6 +1469,7 @@ Frequencies and angles are the output device's to apply. ફ્રિક્વન્સી અને એંગલ આઉટપુટ ડિવાઇસ લાગુ કરશે. Frequency ફ્રિક્વન્સી Fresco… ફ્રેસ્કો… + From Selection પસંદગીમાંથી From: થી: Front આગળ Full Document સંપૂર્ણ દસ્તાવેજ @@ -3969,6 +3971,8 @@ Uniform યુનિફોર્મ Uniformly Scaled સમાન રીતે સ્કેલ કરેલ Unite યુનાઇટ + Unit Converter એકમ રૂપાંતરક + Unit Converter Panel એકમ રૂપાંતરક પેનલ Units એકમો Units: એકમો: Units: {units} એકમો: {units} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 78c0a9a7eb..ba33f1ce0a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1067,6 +1067,7 @@ antiAlias Sharp शार्प Copy Selected Style सिलेक्टेड स्टाइल को कॉपी करें Copy to User Defined उपयोगकर्ता परिभाषित करने के लिए कॉपी करें Copy Width Point कॉपी चौड़ाई पॉइंट + Copy with Units इकाइयों के साथ कॉपी करें Copyright कॉपीराइट Copyright and Contact Info कॉपीराइट और संपर्क जानकारी Copyright Info URL: कॉपीराइट जानकारी URL: @@ -2008,6 +2009,7 @@ antiAlias Sharp शार्प Fresco… फ़्रेस्को… from the format's public description फ़ॉर्मैट के सार्वजनिक विवरण से from your earlier imports अपने पहले आयात से + From Selection सिलेक्शन से From: से: Front सामने Frosted फ़्रॉस्टेड @@ -5308,6 +5310,8 @@ antiAlias Sharp शार्प Unique अनोखा Unite मिलाएँ Unite and Simplify एकजुट और सरलीकरण + Unit Converter इकाई कनवर्टर + Unit Converter Panel इकाई कनवर्टर पैनल Units इकाइयाँ Units & Scale इकाइयों और स्केल Units: इकाइयाँ: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a1f6100b2f..215ee1c9c1 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6975,6 +6975,12 @@ anchor Points: Pontok: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`: "free", "keepAngles" vagy "symmetric" kell @msg `{key}` must be [x, y] `{key}`: [x, y] kell +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Mértékegység-átváltó + Unit Converter Panel Mértékegység-átváltó panel + Copy with Units Másolás mértékegységgel + From Selection A kijelölésből + # Color Effects add-on: Select by Color Kind. Select by Color Kind Kijelölés színtípus szerint Objects with Spot Colors Direkt színeket használó objektumok diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c7c6b956db..f518b286b7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6442,6 +6442,12 @@ anchor Points: Titik: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` harus "free", "keepAngles" atau "symmetric" @msg `{key}` must be [x, y] `{key}` harus [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Pengonversi Satuan + Unit Converter Panel Panel Pengonversi Satuan + Copy with Units Salin dengan Satuan + From Selection Dari Seleksi + # Color Effects add-on: Select by Color Kind. Select by Color Kind Pilih menurut Jenis Warna Objects with Spot Colors Objek dengan Warna Spot diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6743704785..c198db8963 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6620,6 +6620,12 @@ anchor Points: Punti: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve essere "free", "keepAngles" o "symmetric" @msg `{key}` must be [x, y] `{key}` deve essere [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Convertitore di unità + Unit Converter Panel Pannello Convertitore di unità + Copy with Units Copia con le unità + From Selection Dalla selezione + # Color Effects add-on: Select by Color Kind. Select by Color Kind Seleziona per tipo di colore Objects with Spot Colors Oggetti con colori spot diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c9cdb8fcbe..2be853ffdb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8490,6 +8490,12 @@ anchor Points: ポイント: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` には "free"、"keepAngles" または "symmetric" を指定してください @msg `{key}` must be [x, y] `{key}` には [x, y] を指定してください +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 単位換算 + Unit Converter Panel 単位換算パネル + Copy with Units 単位付きでコピー + From Selection 選択範囲から + # Color Effects add-on: Select by Color Kind. Select by Color Kind カラーの種類で選択 Objects with Spot Colors 特色を使用したオブジェクト diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 55f726dc38..7087f2841d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7017,6 +7017,12 @@ anchor Points: წერტილები: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` უნდა იყოს "free", "keepAngles" ან "symmetric" @msg `{key}` must be [x, y] `{key}` უნდა იყოს [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter ერთეულების გადამყვანი + Unit Converter Panel ერთეულების გადამყვანის პანელი + Copy with Units ერთეულებით კოპირება + From Selection მონიშნულიდან + # Color Effects add-on: Select by Color Kind. Select by Color Kind ფერის სახეობით არჩევა Objects with Spot Colors ობიექტები სპოტ-ფერებით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index abe2b4bc28..f0196f0316 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6581,6 +6581,12 @@ anchor Points: 포인트: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode`는 "free", "keepAngles" 또는 "symmetric"이어야 합니다 @msg `{key}` must be [x, y] `{key}`은(는) [x, y]여야 합니다 +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 단위 변환기 + Unit Converter Panel 단위 변환기 패널 + Copy with Units 단위 포함 복사 + From Selection 선택 영역에서 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 색상 종류로 선택 Objects with Spot Colors 별색을 사용한 개체 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ed281382a4..29d23b1d3e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8885,6 +8885,12 @@ anchor Points: Punten: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` moet "free", "keepAngles" of "symmetric" zijn @msg `{key}` must be [x, y] `{key}` moet [x, y] zijn +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Eenhedenomrekenaar + Unit Converter Panel Deelvenster Eenhedenomrekenaar + Copy with Units Kopiëren met eenheden + From Selection Uit selectie + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecteren op kleursoort Objects with Spot Colors Objecten met steunkleuren diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 08e96e6a35..d9882c7efb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6847,6 +6847,12 @@ anchor Points: Punkty: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` musi mieć wartość "free", "keepAngles" lub "symmetric" @msg `{key}` must be [x, y] `{key}` musi mieć postać [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Konwerter jednostek + Unit Converter Panel Panel Konwerter jednostek + Copy with Units Kopiuj z jednostkami + From Selection Z zaznaczenia + # Color Effects add-on: Select by Color Kind. Select by Color Kind Zaznacz według rodzaju koloru Objects with Spot Colors Obiekty z kolorami dodatkowymi diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 79c4d9dc8e..1856771d1d 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6907,6 +6907,12 @@ anchor Points: Pontos: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` deve ser "free", "keepAngles" ou "symmetric" @msg `{key}` must be [x, y] `{key}` deve ser [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Conversor de unidades + Unit Converter Panel Painel Conversor de unidades + Copy with Units Copiar com unidades + From Selection Da seleção + # Color Effects add-on: Select by Color Kind. Select by Color Kind Selecionar por tipo de cor Objects with Spot Colors Objetos com cores spot diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 9f608618e7..fdde9d31d0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6968,6 +6968,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` должно быть "free", "keepAngles" или "symmetric" @msg `{key}` must be [x, y] `{key}` должно быть [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер единиц + Unit Converter Panel Панель «Конвертер единиц» + Copy with Units Копировать с единицами + From Selection Из выделения + # Color Effects add-on: Select by Color Kind. Select by Color Kind Выделить по типу цвета Objects with Spot Colors Объекты с плашечными цветами diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6156ca23d5..813134bc5c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7000,6 +7000,12 @@ anchor Points: Punkter: @msg not an RTF file: it doesn't start with {{\\rtf inte en RTF-fil: den börjar inte med {{\\rtf shape Open Öppen +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Enhetsomvandlare + Unit Converter Panel Panelen Enhetsomvandlare + Copy with Units Kopiera med enheter + From Selection Från markering + # Color Effects add-on: Select by Color Kind. Select by Color Kind Markera efter färgtyp Objects with Spot Colors Objekt med dekorfärger diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7120d44707..d77f2d945e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7064,6 +7064,12 @@ anchor Points: Noktalar: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` "free", "keepAngles" veya "symmetric" olmalıdır @msg `{key}` must be [x, y] `{key}` [x, y] olmalıdır +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Birim Dönüştürücü + Unit Converter Panel Birim Dönüştürücü Paneli + Copy with Units Birimlerle Kopyala + From Selection Seçimden + # Color Effects add-on: Select by Color Kind. Select by Color Kind Renk Türüne Göre Seç Objects with Spot Colors Spot Renkli Nesneler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 84f296b0a6..c160fe6bbb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6600,6 +6600,12 @@ anchor Points: Точки: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` має бути "free", "keepAngles" або "symmetric" @msg `{key}` must be [x, y] `{key}` має бути [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Конвертер одиниць + Unit Converter Panel Панель «Конвертер одиниць» + Copy with Units Копіювати з одиницями + From Selection З виділення + # Color Effects add-on: Select by Color Kind. Select by Color Kind Виділити за типом кольору Objects with Spot Colors Об’єкти з плашковими кольорами diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e8b9e5758f..64f5118b70 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6601,6 +6601,12 @@ anchor Points: Điểm: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` phải là "free", "keepAngles" hoặc "symmetric" @msg `{key}` must be [x, y] `{key}` phải là [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter Bộ chuyển đổi đơn vị + Unit Converter Panel Bảng Bộ chuyển đổi đơn vị + Copy with Units Sao chép kèm đơn vị + From Selection Từ vùng chọn + # Color Effects add-on: Select by Color Kind. Select by Color Kind Chọn theo loại màu Objects with Spot Colors Đối tượng có màu pha diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 719968086f..d22e6e9344 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6833,6 +6833,12 @@ anchor Points: 点: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必须是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必须是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 单位换算器 + Unit Converter Panel 单位换算器面板 + Copy with Units 复制时包含单位 + From Selection 从所选对象 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 按颜色类型选择 Objects with Spot Colors 使用专色的对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 121a8b8c02..5d7b0e02e5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6640,6 +6640,12 @@ anchor Points: 點: @msg `mode` must be "free", "keepAngles" or "symmetric" `mode` 必須是 "free"、"keepAngles" 或 "symmetric" @msg `{key}` must be [x, y] `{key}` 必須是 [x, y] +# Unit Converter add-on (Object › Plug-ins › Unit Converter): its panel. + Unit Converter 單位換算器 + Unit Converter Panel 單位換算器面板 + Copy with Units 複製時包含單位 + From Selection 從選取範圍 + # Color Effects add-on: Select by Color Kind. Select by Color Kind 依顏色類型選取 Objects with Spot Colors 使用特別色的物件 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index bbe91da5a6..10f1bf3694 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -193,6 +193,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), + crate::addons::units::ID => crate::addons::units::show(app, ui), id if library_panel::parse(id).is_some() => library_panel::show(app, ui, id), _ => { dim_label(ui, tl!("This panel is on the roadmap (see the parity plan).")); diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index b759a2df7b..8e782df357 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -125,7 +125,13 @@ const PATTERN_MODES: [(&str, &str); 3] = [("object", "Transform Object Only"), ( /// Only (the pattern tiles alone) or Transform Both. Until one is chosen (`default`, or any other /// value) neither is passed: patterns follow General › Transform Pattern Tiles. Errors are /// dropped, as the panels' fields have always done. -pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json::Value) { +pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, params: serde_json::Value) { + let params = with_pattern_switches(app, params); + app.run(cmd, params).ok(); +} + +/// `params` with the `objects` and `patterns` switches [`run_transform`] adds. +pub fn with_pattern_switches(app: &VectorcraftApp, mut params: serde_json::Value) -> serde_json::Value { let switches = match app.session.prefs.transform_panel_patterns.as_str() { "object" => Some((true, false)), "pattern" => Some((false, true)), @@ -136,7 +142,7 @@ pub fn run_transform(app: &mut VectorcraftApp, cmd: &str, mut params: serde_json params["objects"] = json!(objects); params["patterns"] = json!(patterns); } - app.run(cmd, params).ok(); + params } /// The panel menu's checked choice of [`PATTERN_MODES`]: the one chosen, else (`default`) what diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 80a87b4563..bf34a5195f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -230,6 +230,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), + (crate::addons::units::ID, "Unit Converter", "ruler"), ]; /// Groups of icon panels separated by dividers in the collapsed column. diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 89ce8d70d5..5627fe774c 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -22,29 +22,7 @@ pub(crate) fn typed_unit(ctx: &egui::Context, unit: Unit) -> Unit { if bare_points && unit == Unit::Picas { Unit::Points } else { unit } } -/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm` -/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed -/// after the value the field shows) is 100 mm (#5684). A number written with both separators has -/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a -/// number that reads as thousands ([`thousands`]). -pub(super) fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { - if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } -} - -/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three -/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it -/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are -/// decimals). -fn thousands(text: &str) -> bool { - let number = text.trim().trim_start_matches('-'); - let Some((whole, rest)) = number.split_once(',') else { return false }; - let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); - (1..=3).contains(&whole.len()) - && whole.bytes().all(|b| b.is_ascii_digit()) - && !whole.starts_with('0') - && part.len() == 3 - && unit.trim().chars().all(char::is_alphabetic) -} +pub(super) use vectorcraft_doc::decimal_point; /// A recessed numeric field showing `value` (points) in `unit`. Returns the new value (points) /// when the user commits (Enter / focus loss / Shift+Enter, which keeps the focus outside dialogs). diff --git a/docs/mcp.md b/docs/mcp.md index 2e43c14d0e..af50622f56 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11855,6 +11855,45 @@ Path Options' Preview does (#5360). {"name":"run_command","arguments":{"command":"addon.type.releasePath","params":{"mode":"path","keepOriginal":true}}} ``` +## Unit Converter add-on + +Unit Converter is a built-in add-on that shows one length in every unit at once (#5528): its commands are +`addon.units.convert` and `addon.units.selectionSize`, and in the desktop app it lives in Object › Plug-ins › Unit +Converter and in its panel (`window.panel {panel: "unitConverter"}`). Neither command changes the document. + +`addon.units.convert {value, unit?}` reads `value` as a number field reads it: a number, or text with a unit suffix and +`+ - * /` arithmetic (`"10mm"`, `"1in/2"`, `"2p6"`, `"1080/2 px"`, `"3cm*50%"`, `"13q"`), a decimal comma read as a point +(`"0,5 mm"`) and a single number with a thousands comma (`"1,000 mm"`) refused, in at most 1024 bytes with at most 128 `+ - * /` signs. A +number without a suffix is in `unit` (a unit's name, suffix or key: `points`, `picas`, `inches`, `millimeters`, +`centimeters`, `pixels`, `feetInches`, `meters`, `yards`, `feet`, `q`, `ha`; default `points`); a suffix in the text +takes precedence over `unit`. It works without an open document. The command fails when `value` is missing, does not +read, or is not finite in every unit, and when `unit` is not a unit. Result: `{points, units: [{unit, label, number, +text}]}`: the length in points, then one row per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, +px, ft & in, m, yd, ft, Q, Ha) in that order, with the unit's key, its label, the number without its suffix and the +text with it, rounded as the number fields round them (3 decimals in pt, px, picas, Q and Ha, 4 in the others). Pixels +are points. + +`addon.units.selectionSize {}` gives the selection's width and height as the Transform panel shows them: the bounding +box (rotated with rotated objects), the visual bounds with Use Preview Bounds, or the box around the selected anchor +points with Direct Selection. It fails with nothing selected. Result: `{width, height}`, each as +`addon.units.convert` gives a length. + +The panel has one field per unit. A value typed in any field updates the others as it is typed, and text that does not +read leaves them as they were. Each field's copy button puts its value on the clipboard, with the unit when Copy with +Units is on. From Selection reads the selection's size (`addon.units.selectionSize`), and Width or Height picks which +of the two the fields show; the size read is dropped when the document, its selection, Use Preview Bounds or Measure +Type by Glyph Bounds changes, and the fields keep the length they show. Apply sets that side of the selection to the length with `object.setBounds`, as the Transform +panel's W or H field does: from its reference point (a symbol instance's registration point with Use Registration Point +for Symbol on), with the other side scaled too under Constrain Width and Height Proportions, and with the panel menu's +Transform Object Only, Transform Pattern Only or Transform Both. It is one undo step, and none when the size is already +that length. + +```json +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":"10mm"}}} +{"name":"run_command","arguments":{"command":"addon.units.convert","params":{"value":2.5,"unit":"in"}}} +{"name":"run_command","arguments":{"command":"addon.units.selectionSize","params":{}}} +``` + ## Save location errors A save refused by the filesystem with PermissionDenied or ReadOnlyFilesystem returns diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c6375f3aa3..54a6a27828 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2297,6 +2297,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app (it has no command for this), so no area score moves. Object › Plug-ins › Type Tools › Release Type on a Path… splits each selected type on a path into point type holding the same text and the plain path it was set on, or keeps only one of them (#5532). The path keeps its exact shape (open or closed, anchors and handles, the object's transform), layer and place in the stacking order, with no fill and no stroke since type paths carry no paint of their own. The text keeps its runs, character and paragraph attributes and becomes point type on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options don't apply to point type and are dropped. Keep Original leaves the type on a path and adds the released objects above it. Other objects are left alone and a selection with no type on a path makes no undo step; otherwise the run is one undo step, the released objects are selected, and the dialog's Preview works as Type on a Path Options' does (#5360). Tests: `cmd::addons::typetools::tests::release` in `vectorcraft-engine` (each mode, Keep Original, mixed and empty selections, closed, open, curved and flipped paths, transformed and grouped type, multi-style and unicode text with a centred paragraph, empty type, undo and redo, preview, cancel and commit, bad params refused), `release_type_on_a_path_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on › Release Type on a Path. +## Unit Converter add-on (2026-11-14) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Unit Converter opens a panel with one number field per unit of Preferences › Units › East Asian Type (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha), as proposed in #5528. A length typed in any field, with units and arithmetic as every number field reads them, updates the others as it is typed; text that does not read leaves them as they were. From Selection reads the selection's width and height as the Transform panel measures them, Width or Height picks which one the fields show, and Apply sets that side of the selection through `object.setBounds` as the Transform panel's W or H field does (its reference point, Constrain Width and Height Proportions and its Transform Object Only, Pattern Only or Both choice) as one undo step, with no step when the size is already that length. Each field's copy button copies its value, with its unit when Copy with Units is on. Agents use `addon.units.convert` and `addon.units.selectionSize`, which change nothing in the document (`docs/mcp.md`). Tests: `cmd::addons::units::tests` in `vectorcraft-engine` (every unit, number-field syntax, preview bounds and selected anchors, bad params and unknown keys refused), `addons::units::tests` in `vectorcraft-ui-egui` (typing, From Selection and a changed selection, Apply with the Transform panel's reference point, proportions, pattern choice and a symbol's registration point, copy, screen-reader names) and `command_sweep`. + ## Cutting Tools add-on: Stencil Bridges (2026-11-12) A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Stencil Bridges… cuts strips of a set width (0.01 to 1000 pt, 2 by default) out of the selected art so that a stencil cut from it keeps its islands, such as the inside of an O or a hole in a shape, attached to the sheet ([stencil islands and bridges](https://en.wikipedia.org/wiki/Stencil)). Every island is joined to the sheet, directly or through another island, by the shortest crossings that fit, then gets more bridges spread around it up to the count asked for (1 to 16); bridges run vertically, horizontally or along the shortest crossing among 12 directions 15° apart. The art is measured by the area its outlines enclose (hidden objects left out), type by its glyph outlines without converting the type, and becomes one compound path with the gaps cut; the selected objects that make up the art go to a new hidden layer, Stencil Original, or are replaced, and selected objects with no outlines stay where they are. Art with no islands is left as it is with a message and no undo step, islands the cut result still encloses are counted and reported, and the run is one undo step. Tests: `addons::stencil::tests` in `vectorcraft-pathops` (an O, two holes, nested islands, curved outlines, width, direction, the shortest crossing at an angle, more bridges per island and their spacing, narrow islands, slivers, outlines that touch at a corner, the curve tolerance, open outlines, limits and the work budget), `cmd::addons::cutting::stencil::tests` in `vectorcraft-engine` (the hidden layer and undo, replacing, width with units, type, hidden group members, objects with no outlines, the result's paint, kind and place in the stacking order, no islands, narrow islands, bad params refused), `stencil_bridges_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Stencil Bridges. From 1ae70095ccc33735bf52c198abe68d3340c56f47 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:47:48 -0800 Subject: [PATCH 037/138] Scripts: the grants-file lock waits a bounded time Taking the lock on Script Grants.lock blocked until the holder let go, so another process that stalled while holding it stopped listing, loading, keeping and revoking grants for good. The lock is now tried 20 times, 50 ms apart, and then fails with TimedOut: a change is not made and a read gives no grants rather than reading without the lock. --- crates/engine/src/script/files.rs | 50 ++++++++++++++++++++++++---- crates/engine/src/tests/script_io.rs | 36 ++++++++++++++++++++ 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 19c1a37409..0e863fa03d 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -900,10 +900,10 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { } /// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant -/// that is not well formed is left out. It is read under [`lock_store`]'s lock when that can be -/// taken, so it is read between two changes. +/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read +/// between two changes, and none are read when the lock cannot be taken. fn read_store(store: &Path) -> Vec { - let _lock = lock_store(store).ok(); + let Ok(_lock) = lock_store(store) else { return Vec::new() }; load_store(store, false).unwrap_or_default() } @@ -983,9 +983,20 @@ fn write_store(store: &Path, grants: Vec) -> std::io::Result< }) } +/// How many times [`lock_store`] tries to take the grants file's lock, [`LOCK_PAUSE`] apart, before +/// it gives up. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const LOCK_TRIES: u32 = 20; + +/// The wait between two tries of [`lock_store`]. +#[cfg(not(target_arch = "wasm32"))] +const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50); + /// The lock file beside the grants file at `store` (`Script Grants.lock`), locked until it is -/// dropped and waiting while another process holds it, so that processes that read and change the -/// grants file take turns. A change is not made when the lock cannot be taken. +/// dropped, so that processes that read and change the grants file take turns. While another +/// process or handle holds it, the lock is tried [`LOCK_TRIES`] times, [`LOCK_PAUSE`] apart, and +/// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the +/// lock cannot be taken. #[cfg(not(target_arch = "wasm32"))] fn lock_store(store: &Path) -> std::io::Result { let lock = store.with_extension("lock"); @@ -993,13 +1004,40 @@ fn lock_store(store: &Path) -> std::io::Result { .parent() .map_or(Ok(()), std::fs::create_dir_all) .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(&lock)); - let file = opened.and_then(|f| f.lock().map(|()| f)); + let file = opened.and_then(take_lock); if let Err(e) = &file { log::warn!("can't lock {}: {e}", lock.display()); } file } +/// `file`, locked within [`lock_store`]'s tries. +#[cfg(not(target_arch = "wasm32"))] +fn take_lock(file: std::fs::File) -> std::io::Result { + let mut tries = 1; + loop { + match file.try_lock() { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::Error(e)) => return Err(e), + Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => { + return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock")); + } + Err(std::fs::TryLockError::WouldBlock) => tries += 1, + } + #[cfg(test)] + if WHILE_GRANTS_LOCKED.with_borrow_mut(|w| w.as_mut().map(|waiting| waiting()).is_some()) { + continue; + } + std::thread::sleep(LOCK_PAUSE); + } +} + +#[cfg(test)] +thread_local! { + /// Tests: runs on this thread in place of each wait of [`lock_store`] for a lock that is held. + pub(crate) static WHILE_GRANTS_LOCKED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] fn lock_store(_: &Path) -> std::io::Result { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 1943a11bab..7b5db047ef 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -613,6 +613,42 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Reading and changing the grants file wait for a lock another handle holds only for a bounded +/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock +/// released while it waits is taken. +#[test] +fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { + use crate::script::files::{LOCK_TRIES, WHILE_GRANTS_LOCKED, revoke_grants, stored_grants}; + let base = folder("grants-lock-held"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + let held = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(base.join("settings/Script Grants.lock")).unwrap(); + held.lock().unwrap(); + let waits = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = waits.clone(); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); + assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + assert_eq!(waits.get(), LOCK_TRIES - 1); + waits.set(0); + let refused = revoke_grants(&data, None, None); + assert_eq!(refused.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut)); + assert_eq!(waits.get(), LOCK_TRIES - 1, "it waits between tries and gives up after the last"); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), text); + let mut released = Some(held); + let counted = waits.clone(); + waits.set(0); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || { + counted.set(counted.get() + 1); + drop(released.take()); + }))); + assert_eq!(revoke_grants(&data, None, None).unwrap(), 1, "a lock released while it waits is taken"); + assert_eq!(waits.get(), 1); + WHILE_GRANTS_LOCKED.set(None); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From 82620a1b27aaed84b3f01fcb9c341274eb995034 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:58:51 -0800 Subject: [PATCH 038/138] Scripts: copy and length reach files open for reading A file opened with open('r') kept its old bytes after copy wrote over it or length changed it, while an object open for writing took the new bytes. Both now update every object that holds the file. An object that holds a renamed file is found at the new path, and an object whose file was removed is not taken for a file made later at its path. --- crates/engine/src/script/files.rs | 34 +++++++++++++++++++--------- crates/engine/src/tests/script_io.rs | 29 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 0e863fa03d..559b660d08 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1448,6 +1448,9 @@ struct Open { /// The run may no longer read the file the object holds: `read`, `readln`, `readch` and `seek` /// give [`ACCESS_DENIED`], and `eof` is true. unreadable: bool, + /// The file the object holds was removed, so a file made later at its path is not the one it + /// holds. + removed: bool, } impl Open { @@ -1477,9 +1480,19 @@ impl Open { dirty: false, withdrawn: false, unreadable: false, + removed: false, }) } + /// Does the object hold the bytes of the file at the real path `real`: the file it writes to, or, + /// when it writes to none, the file it was opened on while that file was not removed? + fn holds(&self, real: &Path) -> bool { + match self.target.as_deref() { + Some(t) => t == real, + None => !self.removed && self.read_from.as_deref() == Some(real), + } + } + /// Writes `text` at the position, over what is there and past the end, when it takes at most /// `left` bytes; → the bytes written. fn write(&mut self, text: &str, left: usize) -> Result { @@ -1797,7 +1810,7 @@ fn copy(host: &Host, a: &[Data]) -> Result { }; // The target's open objects each take a copy of the bytes, which count as written too, as does // the copy itself when it is written. - let holders = disk.open.values().filter(|o| o.target.as_deref() == Some(target.as_path())).count(); + let holders = disk.open.values().filter(|o| o.holds(&target)).count(); disk.charge_write(copied.len().saturating_mul(holders.saturating_add(usize::from(!itself))))?; // The copy takes the source's permissions, as `std::fs::copy` gives them. let permissions = std::fs::metadata(&source).map(|m| m.permissions()); @@ -1806,9 +1819,10 @@ fn copy(host: &Host, a: &[Data]) -> Result { if !itself && (r.is_ok() || target.exists()) { disk.wrote(&target); } - // Open objects of the target hold the copy, so closing them does not write their older bytes. + // Open objects of the target hold the copy, so those opened for reading read it and closing the + // others does not write their older bytes. if r.is_ok() { - for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.bytes.clone_from(&copied); file.pos = file.pos.min(copied.len()); file.dirty = false; @@ -1843,10 +1857,12 @@ fn remove(host: &Host, a: &[Data]) -> Result { }; if r.is_ok() { // Other open objects of the file drop their changes and take no more writes, so neither - // their close nor the run's end makes the file again. - for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + // their close nor the run's end makes the file again, and no object holds a file made later + // at its path. + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.dirty = false; file.target = None; + file.removed = true; } disk.wrote(&target); } @@ -1952,11 +1968,7 @@ fn set_length(host: &Host, a: &[Data]) -> Result { Ok(m) => { // Each open object of the file holds its own bytes, so what each one grows by counts too. let len = usize::try_from(n).unwrap_or(usize::MAX); - let held = disk - .open - .values() - .filter(|o| o.target.as_deref() == Some(target.as_path())) - .fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); + let held = disk.open.values().filter(|o| o.holds(&target)).fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); disk.charge_write(usize::try_from(n.saturating_sub(m.len())).unwrap_or(usize::MAX).saturating_add(held))?; // The file's open objects write what they hold first, and then hold the new length. let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); @@ -1967,7 +1979,7 @@ fn set_length(host: &Host, a: &[Data]) -> Result { }; if r.is_ok() { let len = usize::try_from(n).unwrap_or(usize::MAX); - for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.bytes.resize(len, 0); file.pos = file.pos.min(len); } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7b5db047ef..62f031528b 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -889,6 +889,35 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// An object that has a file open for reading holds what `copy` writes over the file and the length +/// `length` sets, as an object open for writing does, also after the file is renamed, and not after +/// it is removed. +#[test] +fn script_file_open_for_reading_holds_a_copy_and_a_new_length() { + let base = folder("copyreader"); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('copied'); s.close();\n\ + var t = new File(d + '/t.txt'); t.open('w'); t.write('old'); t.close(); t.open('r');\n\ + var out = [s.copy(t.fsName), t.read()]; t.close();\n\ + var u = new File(d + '/u.txt'); u.open('w'); u.write('abcdef'); u.close(); u.open('r');\n\ + new File(u.fsName).length = 2; out.push(u.read()); u.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, "copied", "ab"]])); + // A renamed file is held at its new path; a removed one is not held by a file made at its path. + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('copied'); s.close();\n\ + var v = new File(d + '/v.txt'); v.open('w'); v.write('old'); v.close(); v.open('r');\n\ + var w = new File(d + '/v.txt'); var out = [w.rename('w.txt'), s.copy(d + '/v.txt'), v.read()];\n\ + v.seek(0); out.push(s.copy(w.fsName), v.read()); v.close();\n\ + var x = new File(d + '/x.txt'); x.open('w'); x.write('kept'); x.close(); x.open('r');\n\ + out.push(new File(x.fsName).remove(), s.copy(d + '/x.txt'), x.read()); x.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, "old", true, "copied", true, true, "kept"]])); + let _ = std::fs::remove_dir_all(base); +} + /// A file whose `close` could not write it stays open, so a later `close` writes it. #[test] fn script_file_close_that_fails_can_be_tried_again() { From 9971b39c6dc37fa2e7122502420ee15cbe6b6ede Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:50:47 -0800 Subject: [PATCH 039/138] i18n: Danish rows for script file messages Adds Danish rows for the script File and Folder messages, now that Danish is a complete-message language, and removes the two Danish rows for messages the scripts no longer give. --- crates/ui-egui/src/i18n/da.tsv | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 80fb5d9ab8..b3c1a1a86e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -75,14 +75,33 @@ @msg Script file could not be read Scriptfilen kunne ikke læses @msg Script folder has more than 2,048 entries Scriptmappen har mere end 2.048 elementer @msg Script file open mode must be r, w, e or a Scriptfilens åbningstilstand skal være r, w, e eller a -@msg Script file writing is not available Skrivning af scriptfiler er ikke tilgængelig -@msg Script file dialogs are not available Scriptfildialoger er ikke tilgængelige @msg Script files cannot be opened in another application Scriptfiler kan ikke åbnes i et andet program @msg Script file access is unavailable on the web Scriptets filadgang er ikke tilgængelig på nettet @msg Script has 256 files open Scriptet har 256 filer åbne @msg Script file path exceeds 32,767 characters Scriptfilens sti er længere end 32.767 tegn @msg Script folder mask takes too many steps to match Scriptmappens maske kræver for mange trin at matche @msg the script opened more file data than one run may open (32 MiB) scriptet åbnede flere fildata, end én kørsel må åbne (32 MiB) +@msg Script file access denied: {path} Scriptets filadgang blev nægtet: {path} +@msg Script file access to the app's own folders is not allowed Scripts må ikke få adgang til programmets egne mapper +@msg Script file cannot encode the text Scriptfilen kan ikke kode teksten +@msg Script file could not be written Scriptfilen kunne ikke skrives +@msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person +@msg Script file is not open for writing Scriptfilen er ikke åben for skrivning +@msg Script file name is already in use Scriptfilens navn er allerede i brug +@msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe +@msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil +@msg Script file permission could not be saved Scriptets filtilladelse kunne ikke gemmes +@msg Script folder is not empty Scriptmappen er ikke tom +@msg Script files cannot make aliases Scriptfiler kan ikke oprette aliasser +@msg Script file hidden setting cannot be changed Scriptfilens indstilling for skjult kan ikke ændres +@msg {name}: a file 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 fildialog kan ikke åbnes i et callback fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg the script wrote more file data than one run may write (32 MiB) scriptet skrev flere fildata, end én kørsel må skrive (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop +@msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis +@msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang +@msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang +@msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt @msg File.seek: takes a position and a mode File.seek: tager en position og en tilstand @msg vc.run: give a command id, as a string vc.run: angiv et kommando-id som en streng @msg vc.run: takes a command id and an object of parameters vc.run: tager et kommando-id og et objekt med parametre From 30bd983302dcdba7b02bd527a9a62f854b864360 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:53:57 -0800 Subject: [PATCH 040/138] i18n: Danish rows for SVG filter refusals --- crates/ui-egui/src/i18n/da.tsv | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b99ae26197..ac1ae4528f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -290,6 +290,25 @@ @msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en gruppes udfyldning eller streg tegner intet @msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en gruppes udfyldning eller streg tegner intet at eksportere @msg The 3D object is too complex to export 3D-objektet er for komplekst til at blive eksporteret +@msg the element needs an id, the filter's name -elementet skal have et id, filterets navn +@msg an SVG filter's id is at most {MAX_NAME} characters et SVG-filters id er på højst {MAX_NAME} tegn +@msg <{_1}> isn't an element of an SVG filter <{_1}> er ikke et element i et SVG-filter +@msg an SVG filter has no event attributes such as {_1} et SVG-filter har ingen hændelsesattributter som {_1} +@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs et SVG-filters billeder er data:-URL’er i PNG, JPEG, GIF eller WebP +@msg the SVG filter isn't valid XML: {e} SVG-filteret er ikke gyldig XML: {e} +@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} numOctaves for feTurbulence er højst {MAX_OCTAVES} +@msg {what} is at most {max} {what} er højst {max} +@msg feConvolveMatrix's order order for feConvolveMatrix +@msg feMorphology's radius radius for feMorphology +@msg a blur's stdDeviation stdDeviation for en sløring +@msg the SVG filter has no primitives SVG-filteret har ingen filterprimitiver +@msg an SVG filter has at most {MAX_PRIMITIVES} primitives et SVG-filter har højst {MAX_PRIMITIVES} filterprimitiver +@msg the SVG filter is too large once its attributes are written out SVG-filteret er for stort, når dets attributter er skrevet ud +@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all et SVG-filters billeder har højst {MAX_IMAGE_PIXELS} pixels i alt +@msg the SVG filter can't be drawn: check its primitives and their inputs SVG-filteret kan ikke tegnes: kontrollér dets filterprimitiver og deres input +@msg an SVG filter's elements nest at most {MAX_DEPTH} deep et SVG-filters elementer er indlejret højst {MAX_DEPTH} niveauer dybt +@msg an SVG filter is at most {_1} KB et SVG-filter er på højst {_1} KB +@msg give one element angiv ét -element @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Ekstrudér og facet, Omdrej, Pust op eller Rotér) @msg its 3D effect builds no solid dens 3D-effekt danner intet legeme @msg bevel must be none or one of {_1} bevel skal være none eller en af {_1} From 37441a44c20ee2424a3b496943ae60b983bbfcda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:55:05 -0800 Subject: [PATCH 041/138] i18n: Danish row for the action step error --- crates/ui-egui/src/i18n/da.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ca27bdd2f9..e7b78135de 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5066,6 +5066,7 @@ imageTrace Outline Kontur @msg bad trailer ugyldig trailer @msg balance must be between 0 and 100 balance skal være mellem 0 og 100 @msg batch step {_1} (`{id}`) failed: {e} batchtrin {_1} (`{id}`) mislykkedes: {e} +@msg action step {_1} (`{id}`) failed: {reason} handlingstrin {_1} (`{id}`) mislykkedes: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness skal være dark|mediumDark|mediumLight|light @msg can't encode the document: {0} kan ikke kode dokumentet: {0} @msg can't parse shortcut `{c}` kan ikke parse genvejen `{c}` From b173bd7b4048679a3fed38a0ecf103754342f29f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:45:16 -0800 Subject: [PATCH 042/138] Scripts: a folder renamed under another case of its name moves its open files `rename` matched open File objects by the path as given, while the objects hold the names the file system keeps. Where case does not matter, a folder named in another case was renamed but its open files kept the old path, so their changes could not be written and they stayed under the old path's rules for reading. The objects are now matched by the kept name, and a rename whose kept name cannot be learned is refused. --- crates/engine/src/script/files.rs | 14 +++++++++++++- crates/engine/src/tests/script_io.rs | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 559b660d08..7f4052dfb8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1895,13 +1895,25 @@ fn rename(host: &Host, a: &[Data]) -> Result { { return Ok(error(NAME_TAKEN)); } + // Open objects hold real paths with the names the file system keeps, and `from` keeps the last + // name as given, which where case does not matter can differ in case: they are matched by the + // kept name. A link is renamed itself, and no object holds a path through it. When the kept + // name cannot be learned, nothing is renamed, so no object goes on under the old path's rules. + let kept = if was.file_type().is_symlink() { + from.clone() + } else { + match std::fs::canonicalize(&from) { + Ok(kept) => kept, + Err(_) => return Ok(error(WRITE_FAILED)), + } + }; if std::fs::rename(&from, &to).is_err() { return Ok(error(WRITE_FAILED)); } // Open objects of the file, or of files in the folder, write to the new path, and the rules for // reading apply to them there. let moved = |p: &mut Option| { - if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&kept).ok()) { *p = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } }; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 62f031528b..9fc69e080f 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1192,6 +1192,28 @@ fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() let _ = std::fs::remove_dir_all(base); } +/// Where case does not matter, a folder renamed under its name in another case still moves the open +/// objects of the files in it: changes are written under the new name, not lost at the old one. +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn script_file_rename_of_a_folder_named_in_another_case_moves_its_open_files() { + let base = folder("renamecase"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName; new Folder(d + '/sub').create();\n\ + var f = new File(d + '/sub/f.txt'); f.open('w'); f.write('kept');\n\ + var out = [new Folder(d + '/SUB').rename('moved'), f.close(), f.error]; vc.log(out); vc.log(d);", + ) + .unwrap(); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert_eq!(r["log"][0], json!([true, true, ""])); + assert_eq!(std::fs::read(d.join("moved/f.txt")).unwrap(), b"kept"); + assert!(!d.join("sub").exists()); + let _ = std::fs::remove_dir_all(base); +} + /// Where case matters, a rename to a name that differs in case alone does not replace the other file. #[cfg(target_os = "linux")] #[test] From fd2baa04225c214e911dc26f2e3e0c76615a1da9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:51:22 -0800 Subject: [PATCH 043/138] Tests: the data folder write test expects Windows line ends and paths on Windows `writeln` uses CRLF by default on Windows, and the script reports paths without the `\?\` prefix that canonicalize adds there. The test expected LF and compared with the prefixed path, so it failed on Windows. It now expects the platform's default line end and compares plain paths. --- crates/engine/src/tests/script_io.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 9fc69e080f..6637d3fe8d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -500,16 +500,18 @@ fn script_files_write_in_the_temporary_and_data_folders() { vc.log(out); vc.log(u.fsName); vc.log(Folder.temp.fsName);", ) .unwrap(); - assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, "a1trueb\nc\r\n", true, true, true, 4, true, true])); + // The first `writeln` uses the default line end, which is the platform's. + let text = if cfg!(windows) { "a1trueb\r\nc\r\n" } else { "a1trueb\nc\r\n" }; + assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, text, true, true, true, 4, true, true])); let notes = PathBuf::from(r["log"][1].as_str().unwrap()); let temp = PathBuf::from(r["log"][2].as_str().unwrap()); - assert_eq!(std::fs::read(¬es).unwrap(), b"a1trueb\nc\r\n"); - assert!(notes.starts_with(std::fs::canonicalize(base.join("settings/Script Data")).unwrap()), "{notes:?}"); + assert_eq!(std::fs::read(¬es).unwrap(), text.as_bytes()); + assert!(notes.starts_with(crate::cmd::findfiles::plain(std::fs::canonicalize(base.join("settings/Script Data")).unwrap())), "{notes:?}"); assert!(!temp.exists(), "the run's temporary folder is deleted when it ends"); let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); assert!(written.contains(¬es.to_string_lossy().as_ref()), "{written:?}"); let again = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/notes.txt'); u.open('r'); vc.log(u.read());").unwrap(); - assert_eq!(again["log"], json!(["a1trueb\nc\r\n"]), "a script's data folder is kept between runs"); + assert_eq!(again["log"], json!([text]), "a script's data folder is kept between runs"); let _ = std::fs::remove_dir_all(base); } From e4955fb933141c2a40c93ccbd52b1393d723ee7a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:32:57 -0800 Subject: [PATCH 044/138] Unit Converter: a thousands comma in any number of a sum is refused A value such as 1,000 mm+1 mm read the comma as a decimal point and gave 2 mm, because only a value that was one number was checked for a thousands comma. Each number of a sum is now checked on its own, so 1,000 mm+1 mm, +1,000 and 2*1,000 are refused in the number fields and in addon.units.convert, and 100.5 mm-0,5 still reads as 100 mm. --- crates/doc/src/units.rs | 16 +++++++++++----- crates/engine/src/cmd/addons/units/tests.rs | 7 +++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 052830ef0f..2ae33d0783 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -317,12 +317,18 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } -/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three -/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it -/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are -/// decimals). +/// Does `text` hold a number written with a thousands comma, as `1,000` or `12,500 mm`: one to +/// three digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a +/// decimal it would be a thousand times too small, so the field refuses it instead (`0,125` and +/// `1,25` are decimals). Each number of a sum is checked on its own, so `1,000 mm+1 mm` and +/// `+1,000` are refused too. fn thousands(text: &str) -> bool { - let number = text.trim().trim_start_matches('-'); + text.split(['+', '-', '*', '/']).any(thousands_number) +} + +/// Is `number`, one number of a field value, written with a thousands comma ([`thousands`])? +fn thousands_number(number: &str) -> bool { + let number = number.trim(); let Some((whole, rest)) = number.split_once(',') else { return false }; let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); (1..=3).contains(&whole.len()) diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 2b572c3d11..12e93a8a02 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -70,6 +70,8 @@ fn values_read_as_number_fields_read_them() { // A decimal comma reads as a point, as in the number fields. assert!(near(pt(&mut s, json!({"value": "0,5 in"})), 36.0)); assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); + // Each number of a sum reads its own separator. + assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); } @@ -143,6 +145,11 @@ fn bad_values_and_units_are_refused() { // A thousands comma is refused, as the number fields refuse it. json!({"value": "1,000 mm"}), json!({"value": "1,000.5"}), + // So is a thousands comma in any number of a sum. + json!({"value": "1,000 mm+1 mm"}), + json!({"value": "1 mm+1,000 mm"}), + json!({"value": "+1,000"}), + json!({"value": "2*1,000"}), // A long expression is refused instead of exhausting the stack. json!({"value": format!("1{}", "+1".repeat(200_000))}), json!({"value": format!("1{}", "+1".repeat(129))}), From 8620f0611cfb02ea1e5ef7a7522c4dcf939ce8fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:37:25 -0800 Subject: [PATCH 045/138] Scripts: a file whose write fails after it was emptied is named as written Writing an open file's bytes empties the file first. When the write then failed, for example on a full disk, the file had lost its old bytes but was left out of the files the run names as written. It is now named as soon as it has been opened for the write. --- crates/engine/src/script/files.rs | 16 ++++++++++++---- crates/engine/src/tests/script_io.rs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 7f4052dfb8..05f148e714 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -762,11 +762,17 @@ impl Disk { if moved || std::fs::symlink_metadata(&real).is_ok_and(|m| m.file_type().is_symlink()) { return Err(ACCESS_DENIED); } - // The file stays changed until its bytes are written, so the run's end tries it again. - std::fs::write(&real, &file.bytes).map_err(|_| WRITE_FAILED)?; - file.dirty = false; + // The file stays changed until its bytes are written, so the run's end tries it again. Once + // it is opened its old bytes are gone, so a write that then fails names it in the report too. + let mut out = std::fs::File::create(&real).map_err(|_| WRITE_FAILED)?; + let written = std::io::Write::write_all(&mut out, &file.bytes).is_ok(); + #[cfg(test)] + let written = written && !FLUSH_WRITE_FAILS.with(std::cell::Cell::get); + if written { + file.dirty = false; + } self.wrote(&real); - Ok(()) + if written { Ok(()) } else { Err(WRITE_FAILED) } } /// Writes every open file that has changed: at the end of the run. → the files that could not @@ -2357,6 +2363,8 @@ pub(crate) type CopyHook = Box; #[cfg(test)] thread_local! { pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. + pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; } #[cfg(test)] diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 6637d3fe8d..eca6dd5638 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -515,6 +515,23 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// A file whose bytes fail to be written after it was opened for them has lost its old bytes, so the +/// failed run names it among the files that stay written. +#[test] +fn script_file_whose_write_fails_partway_is_named_as_written() { + let base = folder("flushfails"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var f = new File(Folder.userData.fsName + '/f.txt'); f.open('w'); f.write('old'); f.close(); vc.log(f.fsName);") + .unwrap(); + let path = r["log"][0].as_str().unwrap().to_string(); + crate::script::files::FLUSH_WRITE_FAILS.with(|f| f.set(true)); + let r = run_in(&mut s, &base, "var f = new File(Folder.userData.fsName + '/f.txt'); f.open('e'); f.write('new'); f.close();"); + crate::script::files::FLUSH_WRITE_FAILS.with(|f| f.set(false)); + let e = format!("{}", r.unwrap_err()); + assert!(e.split("these files stay written:").nth(1).is_some_and(|w| w.contains(&path)), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` reads its source under the rules for reading: a source that a link to a file outside the /// script's places replaced after it was looked up is refused, and nothing is copied. #[cfg(unix)] From b7d85212961739db08326e6dd69a94ddf660aaf4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:32:49 -0800 Subject: [PATCH 046/138] Window: Arrange Documents tiles the documents side by side, stacked or 2-Up to 6-Up Tile laid the open documents out in one grid only, and the application bar had no Arrange Documents button. Window > Arrange now also has Tile All Vertically (side by side in one row), Tile All Horizontally (stacked in one column) and 2-Up, 3-Up, 4-Up and 6-Up layouts, which show that many documents and leave the others under their tabs. Those layouts show the first documents in tab order, and the current document takes the last pane when it is not among them. An Arrange Documents button on the application bar, beside the workspace switcher, lists Consolidate All Windows and the Tile layouts. The item for the layout the panes show is checked. window.arrange.tile takes `layout` (grid, vertical, horizontal, 2up, 3up, 4up or 6up; grid when omitted), refuses any other value, and returns it with {tiled, panes}. ui.inspect reports tileLayout. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/panes.rs | 149 ++++++++++-- crates/ui-egui/src/canvas/panes/tests.rs | 282 ++++++++++++++++++++++- crates/ui-egui/src/chrome.rs | 47 +++- crates/ui-egui/src/control.rs | 7 +- crates/ui-egui/src/doc_windows/tests.rs | 4 +- crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/gu.tsv | 7 + crates/ui-egui/src/i18n/hi.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/ka.tsv | 7 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tests.rs | 11 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/menus/run.rs | 2 +- crates/ui-egui/src/menus/state.rs | 2 + crates/ui-egui/src/menus/tree.rs | 35 ++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/state.rs | 5 + docs/mcp.md | 22 +- docs/target-app-parity.md | 1 + 44 files changed, 716 insertions(+), 54 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1bc2d14442..0429a7af31 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -768,7 +768,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5c30f96246..1cc1abd5ca 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -63,7 +63,7 @@ use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; #[cfg(test)] use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; -pub use panes::Panes; +pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, pane, tile, tiled_area}; use raster::{changed_pixels, pixel_region, upload}; pub(crate) use raster::{color_image, color_image_owned, render_job}; diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 0a26f26843..6b8eea9440 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,5 +1,6 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document -//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its +//! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the +//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its //! document from a render of its own, with its artboards, guides and selected objects, and a press //! in it makes its document the current one. Each view Window › New Window opened has a pane of //! its own ([`crate::doc_windows`]). @@ -38,6 +39,9 @@ pub struct Panes { pending: HashMap, /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, + /// The slots of `last`'s windows, in the same order: which windows they were, as document + /// indices shift when a document closes. + last_slots: Vec>, /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, @@ -49,6 +53,7 @@ impl Panes { self.shown.clear(); self.pending.clear(); self.last.clear(); + self.last_slots.clear(); self.fits.clear(); } @@ -158,37 +163,123 @@ fn render_pane( img } -/// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n` -/// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover -/// `area`; the spare cells of the last row stay empty. -pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { - if n == 0 { - return vec![]; +/// How Tile lays out the panes (`window.arrange.tile`'s `layout`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Layout { + /// A grid: as many columns as the square root of the number of panes rounded up. + #[default] + Grid, + /// Side by side in one row, each pane as tall as the document area. + Vertical, + /// Stacked in one column, each pane as wide as the document area. + Horizontal, + /// At most this many panes (2, 3, 4 or 6); the other windows stay under their tabs. + Up(usize), +} + +impl Layout { + /// Each layout with its name in `layout`, in the order the menus list them. + pub(crate) const ALL: [(&'static str, Layout); 7] = [ + ("grid", Layout::Grid), + ("vertical", Layout::Vertical), + ("horizontal", Layout::Horizontal), + ("2up", Layout::Up(2)), + ("3up", Layout::Up(3)), + ("4up", Layout::Up(4)), + ("6up", Layout::Up(6)), + ]; + + /// The layout's name in `layout`. + pub(crate) fn name(self) -> &'static str { + Self::ALL.iter().find(|(_, l)| *l == self).map_or("grid", |(n, _)| n) } + + /// The layout `p`'s `layout` names, the grid without one. Any other value is an error. + pub(crate) fn from_params(p: &serde_json::Value) -> Result { + let key = "layout"; + match p.get(key) { + None => Ok(Layout::Grid), + Some(v) => v + .as_str() + .and_then(|s| Self::ALL.iter().find(|(n, _)| *n == s)) + .map(|(_, l)| *l) + .ok_or_else(|| format!("`{key}` must be one of {}", Self::ALL.map(|(n, _)| n).join(", "))), + } + } + + /// How many of `n` windows the layout gives a pane. + fn panes(self, n: usize) -> usize { + match self { + Layout::Up(k) => n.min(k), + _ => n, + } + } + + /// How many columns the layout puts `n` panes in. + fn columns(self, n: usize) -> usize { + match self { + Layout::Grid => grid_columns(n), + Layout::Vertical => n, + Layout::Horizontal => 1, + Layout::Up(k) if k <= 3 => n, + Layout::Up(k) => grid_columns(k).min(n), + } + } +} + +/// The square root of `n` rounded up. +fn grid_columns(n: usize) -> usize { let mut cols = 1; while cols * cols < n { cols += 1; } + cols +} + +/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns +/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to +/// edge and cover `area`; the spare cells of the last row stay empty. +pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec { + if n == 0 { + return vec![]; + } + let cols = layout.columns(n).clamp(1, n); let rows = n.div_ceil(cols); let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 }; let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 }; (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own, -/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it -/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it. -pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { +/// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of +/// the first ones as it shows, with the current window `active` in the last pane when it is not +/// among them. +pub(crate) fn shown_windows(layout: Layout, docked: &[Win], active: Option) -> Vec { + let k = layout.panes(docked.len()); + let mut shown = docked[..k].to_vec(); + if let (Some(a), Some(last)) = (active.filter(|a| !shown.contains(a) && docked.contains(a)), shown.last_mut()) { + *last = a; + } + shown +} + +/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own +/// as `layout` places them (the grid without one), each fitted to its pane. With fewer than two +/// windows open (when the menu item is grayed out) it leaves the view, `tiled` and the layout as +/// they are. The windows floating come back under the tabs for it. A `layout` that is not one of +/// [`Layout::ALL`]'s names is an error. +pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result { + let layout = Layout::from_params(p)?; app.sync_views(); let n = crate::doc_windows::windows(app).len(); if n < 2 { - return Ok(json!({"tiled": app.ui.tiled, "panes": n})); + return Ok(json!({"tiled": app.ui.tiled, "panes": n, "layout": app.ui.tile_layout.name()})); } crate::doc_windows::dock_all(app); app.ui.tiled = true; + app.ui.tile_layout = layout; app.ui.home = None; crate::doc_windows::unfit_all(app); - Ok(json!({"tiled": app.ui.tiled, "panes": n})) + Ok(json!({"tiled": app.ui.tiled, "panes": layout.panes(n), "layout": layout.name()})) } /// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the @@ -216,27 +307,41 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.clear(); } app.canvas.panes.last.clear(); + app.canvas.panes.last_slots.clear(); return false; } // The current window's pane is the canvas, unless it is a floating one. let active = crate::doc_windows::current(app).filter(|a| docked.contains(a)); + // The 2-up to 6-up layouts leave the windows past their panes under the tabs. + let layout = app.ui.tile_layout; + let shown = shown_windows(layout, &docked, active); app.sync_views(); - let live: Vec = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect(); + // The renders of the panes and the floating windows stay; a window under its tab has none. + let live: Vec = + crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect(); app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - // A window opened, closed, floated or docked changes the grid, and so does coming back to the - // panes from one window: each window fits its new pane. - if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) { - for w in &docked { - if let Some(v) = crate::doc_windows::view_mut(app, *w) { - v.fitted = false; - } + // A window opened, closed, floated or docked changes the panes, and so does coming back to the + // panes from one window: each window fits its new pane. With as many panes as before, only a + // window that moved to another pane fits it, as when a tab brings its window into the last pane + // of a 2-up to 6-up layout: the others keep their zoom and scroll. Windows are compared by + // their slots, since a closed document shifts the indices of the documents after it. + let before = std::mem::take(&mut app.canvas.panes.last_slots); + let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); + let same_panes = before.len() == now.len(); + for (i, (w, s)) in shown.iter().zip(&now).enumerate() { + if same_panes && s.is_some() && before.get(i) == Some(s) { + continue; + } + if let Some(v) = crate::doc_windows::view_mut(app, *w) { + v.fitted = false; } } + app.canvas.panes.last_slots = now; let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect(); let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); let unfitted = refit_resized(app, &areas); let mut activate = None; diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 005b930d01..2ad0af3dc1 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -43,6 +43,11 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event { egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } +/// Tile's grid of `n` panes in `area`. +fn cells(n: usize, area: egui::Rect) -> Vec { + layout_cells(Layout::Grid, n, area) +} + /// The documents' indices in the panes the last frame drew, and the panes. fn panes(app: &VectorcraftApp) -> (Vec, Vec) { app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip() @@ -84,6 +89,279 @@ fn cells_tile_the_area_edge_to_edge() { } } +/// The distinct left and top edges of `c`: how many columns and rows its panes take. +fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) { + let lefts: BTreeSet = c.iter().map(|r| r.left().to_bits()).collect(); + let tops: BTreeSet = c.iter().map(|r| r.top().to_bits()).collect(); + (lefts.len(), tops.len()) +} + +#[test] +fn each_tile_layout_places_its_panes_edge_to_edge() { + let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0)); + let cases = [ + (Layout::Vertical, 3, (3, 1)), + (Layout::Vertical, 7, (7, 1)), + (Layout::Horizontal, 3, (1, 3)), + (Layout::Up(2), 2, (2, 1)), + (Layout::Up(3), 3, (3, 1)), + (Layout::Up(3), 2, (2, 1)), + (Layout::Up(4), 4, (2, 2)), + (Layout::Up(4), 3, (2, 2)), + (Layout::Up(6), 6, (3, 2)), + (Layout::Up(6), 4, (3, 2)), + (Layout::Up(6), 2, (2, 1)), + ]; + for (layout, n, shape) in cases { + let c = layout_cells(layout, n, area); + assert_eq!(c.len(), n); + assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows"); + assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner"); + let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max); + let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); + assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges"); + for (i, r) in c.iter().enumerate() { + assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}"); + for o in &c[i + 1..] { + assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}"); + } + } + } + assert!(layout_cells(Layout::Up(2), 0, area).is_empty()); +} + +#[test] +fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}"); + let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}"); + // Each document fits its new pane. + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let canvas = app.canvas_rect.unwrap(); + for (i, r) in docs.iter().zip(&rects) { + let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 }; + let v = app.views[*i]; + assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}"); + } + assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal")); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid"); +} + +#[test] +fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { + let mut app = app_with(5); + let ctx = egui::Context::default(); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "2up"})); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 4], "the current document takes the last pane"); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order"); + let second = (app.session.documents()[1].uid, 1); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane"); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane"); + assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render"); + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9); + assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas"); + // A document brought into the last pane leaves the first pane's zoom as it is. + app.views[0].zoom *= 2.0; + let zoomed = app.views[0].zoom; + app.run("document.activate", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 2]); + assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom"); + let last = app.canvas_rect.unwrap(); + assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane"); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3], (2, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap()["panes"], json!(5), "6-Up with five documents shows them all"); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "3up"})).unwrap()["panes"], json!(3)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2], (3, 1))); + app.run("document.activate", json!({"index": 4})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 4]); +} + +/// A document closed before the panes shifts the indices of the ones after it: the document that +/// moves into another pane fits it. +#[test] +fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { + let mut app = app_with(4); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 3]); + let moving = app.session.documents()[1].uid; + // The second document's view, under its tab, is zoomed away from its fit. + app.views[1].zoom *= 3.0; + app.run("file.close", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last"); + assert_eq!(app.session.documents()[0].uid, moving); + let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + let v = app.views[0]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); +} + +#[test] +fn tile_refuses_a_layout_it_does_not_have() { + let mut app = app_with(3); + for bad in [json!("5up"), json!("Vertical"), json!(3), json!(null), json!({})] { + let err = app.run("window.arrange.tile", json!({"layout": bad})).unwrap_err(); + assert_eq!(err, "`layout` must be one of grid, vertical, horizontal, 2up, 3up, 4up, 6up", "{bad}"); + assert!(!app.ui.tiled && app.ui.tile_layout == Layout::Grid, "{bad}: the view stays as it is"); + } + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert!(app.run("window.arrange.tile", json!({"layout": "diagonal"})).is_err()); + assert_eq!(app.ui.tile_layout, Layout::Vertical, "a refused layout leaves the tiled one"); + // With one document the layout is still checked, and nothing changes. + let mut one = app_with(1); + assert!(one.run("window.arrange.tile", json!({"layout": "7up"})).is_err()); + assert_eq!(one.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); +} + +#[test] +fn the_tile_items_check_the_layout_the_panes_show() { + let mut app = app_with(3); + let checked = |app: &VectorcraftApp, layout: Option<&str>| { + let p = layout.map_or(serde_json::Value::Null, |l| json!({"layout": l})); + crate::menus::checked(app, "window.arrange.tile", &p) + }; + assert_eq!(checked(&app, None), Some(false), "not tiled"); + app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap(); + assert_eq!(checked(&app, Some("4up")), Some(true)); + assert_eq!(checked(&app, None), Some(false)); + assert_eq!(checked(&app, Some("2up")), Some(false)); + app.run("window.arrange.tile", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(true), "Tile is the grid"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(false)); + // Window › Arrange lists every layout, after Cascade and before Float in Window. + let window = crate::menus::menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, items)| items).unwrap(); + let arrange = window + .into_iter() + .find_map(|i| match i { + crate::menus::Item::Sub("Arrange", items) => Some(items), + _ => None, + }) + .unwrap(); + let labels: Vec<&str> = arrange + .iter() + .filter_map(|i| match i { + crate::menus::Item::Cmd(l, ..) => Some(*l), + _ => None, + }) + .collect(); + assert_eq!( + labels, + [ + "Cascade", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + "Float in Window", + "Float All in Windows", + "Consolidate All Windows" + ] + ); + // Each item's params run, as the menu sends them. + for item in &arrange { + if let crate::menus::Item::Cmd(_, "window.arrange.tile", p) = item { + let p = if p.is_null() { json!({}) } else { p.clone() }; + assert!(app.run("window.arrange.tile", p.clone()).is_ok(), "{p}"); + } + } +} + +/// One frame of the application bar with screen-reader nodes on → the nodes. +fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() +} + +/// The center of the application bar's node whose label, without its leading spaces, is `name` +/// (or starts with it and a shortcut in parentheses). +fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option { + let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('(')); + let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?; + Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) +} + +/// Click the application bar's node labeled `name`. +fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn")); + app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + app_bar_frame(app, ctx, vec![button(at, false)]); +} + +#[test] +fn the_arrange_documents_button_tiles_and_consolidates() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + app_bar_frame(&mut app, &ctx, vec![]); + let nodes = app_bar_frame(&mut app, &ctx, vec![]); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands and tools")); + let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search icon shows")); + assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search icon: {arrange:?}, {search:?}"); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + let menu = app_bar_frame(&mut app, &ctx, vec![]); + for item in [ + "Consolidate All Windows", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + ] { + assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}"); + } + click_app_bar(&mut app, &ctx, "Tile All Vertically"); + assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + click_app_bar(&mut app, &ctx, "Consolidate All Windows"); + assert!(!app.ui.tiled); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); @@ -91,7 +369,7 @@ fn tile_shows_a_pane_for_each_document_fitted_to_it() { frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty(), "documents open under their tabs"); let tabbed = app.canvas_rect.unwrap(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 1, 2]); @@ -206,7 +484,7 @@ fn arrange_items_follow_the_open_documents() { fn tile_with_one_document_leaves_the_next_one_under_its_tab() { let mut app = app_with(1); let ctx = egui::Context::default(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); assert!(!app.ui.tiled); assert!(!enabled(&app, "window.arrange.consolidateAllWindows")); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index fc0234885b..96b4d12965 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -85,7 +85,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // The right-side group fills the space after the menus from the right; when it runs // short, Discord goes first (it is also under Help), then Explore tutorials (also // Window › Learn), then the search icon (the palette stays under its shortcut), then - // the workspace switcher narrows. + // Arrange Documents (also Window › Arrange), then the workspace switcher narrows. let full = ui.max_rect(); let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() }; let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom())); @@ -105,13 +105,16 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text); let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0); let gap = ui.spacing().item_spacing.x; - // The search icon, as in PhotoCraft: shown while a minimal switcher fits beside it. + // Arrange Documents, beside the switcher, then the search icon, as in PhotoCraft: each + // shown while a minimal switcher fits beside it. let icon = 28.0; - let search = switcher && room >= 64.0 + 8.0 + gap + icon; - let ws_w = ws_w.min(room - 8.0 - gap - if search { icon } else { 0.0 }).max(64.0); + let arrange = switcher && room >= 64.0 + 8.0 + gap + icon; + let search = arrange && room >= 64.0 + 8.0 + 2.0 * (gap + icon); + let icons = f32::from(u8::from(arrange) + u8::from(search)); + let ws_w = ws_w.min(room - 8.0 - icons * (gap + icon)).max(64.0); // Explore tutorials, beside the search icon, opens the Learn panel. - let learn = search && room >= ws_w + 8.0 + 2.0 * (gap + icon); - let discord = learn && room >= ws_w + 8.0 + 2.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); + let learn = search && room >= ws_w + 8.0 + 3.0 * (gap + icon); + let discord = learn && room >= ws_w + 8.0 + 3.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; // Workspace switcher: shows the current workspace, opens Window → Workspace. @@ -130,6 +133,11 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.add_space(8.0); } + // Arrange Documents: Consolidate All Windows and the Tile layouts. + if arrange { + let resp = widgets::icon_button(ui, "layout-grid", tl!("Arrange Documents"), app.ui.tiled, icon); + egui::Popup::menu(&resp).show(|ui| arrange_documents_popup(app, ui)); + } // Search → command palette (its shortcut opens it too). if search { let tip = match menus::shortcut_of("help.commandPalette") { @@ -168,6 +176,33 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The Arrange Documents menu ([`menus::arrange_documents_items`]): each item as the Window menu +/// shows it, grayed out while its command can't run, the Tile layout the panes show checked. +fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) { + ui.set_min_width(200.0); + let mut clicked = None; + for it in menus::arrange_documents_items() { + match it { + menus::Item::Sep => { + ui.separator(); + } + menus::Item::Cmd(label, id, p) => { + let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue }; + let label = crate::i18n::t_id(id, label); + let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") }; + if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() { + clicked = Some((id, if p.is_null() { json!({}) } else { p })); + ui.close(); + } + } + _ => {} + } + } + if let Some((id, p)) = clicked { + menus::invoke(app, id, p); + } +} + /// Whether the window shows the system's title bar instead of the app drawing its own /// ([`VectorcraftApp::desktop_frame`]): Windows with Preferences › User Interface › System Title /// Bar, and Linux whenever the desktop draws the frame, with or without the preference. The diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 26f67a0365..461b352c4e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -273,11 +273,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), - // Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew: - // each one's document index, view number (Window › New Window) and rect. Canvas - // coordinates map to the current window's pane, inside its rulers and scroll bars + // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the + // last frame drew: each one's document index, view number (Window › New Window) and rect. + // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars // (`canvasRect`). "tiled": app.ui.tiled, + "tileLayout": app.ui.tile_layout.name(), "panes": app.canvas.panes.last.iter().map(|(w, c)| json!({ "document": w.0, "view": w.1, diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 64a693a09b..91a0ef23e4 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -259,7 +259,7 @@ fn tile_brings_floating_documents_back_into_the_grid() { frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1, 2]); @@ -844,7 +844,7 @@ fn arrange_treats_each_view_as_a_window() { assert!(!enabled(&app, "window.arrange.tile") && !enabled(&app, "window.arrange.cascade"), "one window"); app.run("window.newWindow", json!({})).unwrap(); assert!(enabled(&app, "window.arrange.tile") && enabled(&app, "window.arrange.cascade"), "two views of one document"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "grid"})); app.run("window.arrange.cascade", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); let uid = app.session.documents()[0].uid; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d0a770b2b1..ffeacfc3f5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3643,6 +3643,13 @@ digits Malayalam Малаялам Thumbnail View Изглед с миниатюри Thumbnails: Миниатюри: Tile Мозайка + Tile All Vertically Всички в мозайка вертикално + Tile All Horizontally Всички в мозайка хоризонтално + 2-Up Layout Подредба по 2 + 3-Up Layout Подредба по 3 + 4-Up Layout Подредба по 4 + 6-Up Layout Подредба по 6 + Arrange Documents Подреждане на документите Tile Edge Color Цвят на ръба на плочката Tile Edge Color… Цвят на ръба на плочката… Tile Full Pages Покриване на цели страници diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5fca937f98..916a3e6b5f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -689,6 +689,13 @@ Previous Document Prethodni dokument Cascade Kaskadno Tile Popločaj + Tile All Vertically Popločaj sve okomito + Tile All Horizontally Popločaj sve vodoravno + 2-Up Layout Raspored po 2 + 3-Up Layout Raspored po 3 + 4-Up Layout Raspored po 4 + 6-Up Layout Raspored po 6 + Arrange Documents Rasporedi dokumente Float in Window Odvoji u prozor Float All in Windows Odvoji sve u prozore Consolidate All Windows Objedini sve prozore diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b6fdc2a6a6..7fe0977ead 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4740,6 +4740,13 @@ digits Malayalam Malaiàlam TIFF (8-bit Color) TIFF (color de 8 bits) TIFF (Black & White) TIFF (blanc i negre) Tile Mosaic + Tile All Vertically Mosaic vertical de tot + Tile All Horizontally Mosaic horitzontal de tot + 2-Up Layout Disposició de 2 + 3-Up Layout Disposició de 3 + 4-Up Layout Disposició de 4 + 6-Up Layout Disposició de 6 + Arrange Documents Organitza els documents Tile Edge Color Color de la vora del mosaic Tile Edge Color… Color de la vora del mosaic… Tile Full Pages Mosaic de pàgines senceres diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 47ca092cc0..d9fa87f2bf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -702,6 +702,13 @@ Previous Document Předchozí dokument Cascade Do kaskády Tile Vedle sebe + Tile All Vertically Vše vedle sebe svisle + Tile All Horizontally Vše vedle sebe vodorovně + 2-Up Layout Rozvržení po 2 + 3-Up Layout Rozvržení po 3 + 4-Up Layout Rozvržení po 4 + 6-Up Layout Rozvržení po 6 + Arrange Documents Uspořádat dokumenty Float in Window Uvolnit do samostatného okna Float All in Windows Uvolnit vše do samostatných oken Consolidate All Windows Sloučit všechna okna diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ca27bdd2f9..57322a818e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1257,6 +1257,13 @@ Previous Document Forrige dokument Cascade Kaskade Tile Fliselæg + Tile All Vertically Fliselæg alle lodret + Tile All Horizontally Fliselæg alle vandret + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Arrangér dokumenter Float in Window Flyd i vindue Float All in Windows Flyd alle i vinduer Consolidate All Windows Saml alle vinduer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index df4d5df82e..3da18ee5ba 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3686,6 +3686,13 @@ effect Points Punkte Thumbnail View Miniaturansicht Thumbnails: Miniaturen: Tile Nebeneinander + Tile All Vertically Alle vertikal nebeneinander + Tile All Horizontally Alle horizontal nebeneinander + 2-Up Layout Layout mit 2 + 3-Up Layout Layout mit 3 + 4-Up Layout Layout mit 4 + 6-Up Layout Layout mit 6 + Arrange Documents Dokumente anordnen Tile Edge Color Farbe der Kachelkante Tile Edge Color… Farbe der Kachelkante… Tile Full Pages Ganze Seiten aufteilen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9f3ee177e5..739d63f664 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2171,6 +2171,13 @@ font-technology Variable Μεταβλητές Templates Πρότυπα Threshold Κατώφλι Tile Παράθεση + Tile All Vertically Παράθεση όλων κατακόρυφα + Tile All Horizontally Παράθεση όλων οριζόντια + 2-Up Layout Διάταξη ανά 2 + 3-Up Layout Διάταξη ανά 3 + 4-Up Layout Διάταξη ανά 4 + 6-Up Layout Διάταξη ανά 6 + Arrange Documents Διάταξη εγγράφων Tint Χρωματική απόχρωση Fill Tint Χρωματική απόχρωση γεμίσματος Stroke Tint Χρωματική απόχρωση περιγράμματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 555e51b8c7..8244d1fee3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3734,6 +3734,13 @@ digits Malayalam Malayálam Thumbnail View Vista de miniaturas Thumbnails: Miniaturas: Tile Mosaico + Tile All Vertically Mosaico vertical de todo + Tile All Horizontally Mosaico horizontal de todo + 2-Up Layout Disposición de 2 + 3-Up Layout Disposición de 3 + 4-Up Layout Disposición de 4 + 6-Up Layout Disposición de 6 + Arrange Documents Organizar documentos Tile Edge Color Color del borde del mosaico Tile Edge Color… Color del borde del mosaico… Tile Full Pages Mosaico de páginas completas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 363042b43d..85043309b2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -693,6 +693,13 @@ Previous Document Edellinen asiakirja Cascade Porrasta Tile Vierekkäin + Tile All Vertically Kaikki vierekkäin pystysuunnassa + Tile All Horizontally Kaikki vierekkäin vaakasuunnassa + 2-Up Layout 2 ikkunan asettelu + 3-Up Layout 3 ikkunan asettelu + 4-Up Layout 4 ikkunan asettelu + 6-Up Layout 6 ikkunan asettelu + Arrange Documents Järjestä asiakirjat Float in Window Kelluta ikkunassa Float All in Windows Kelluta kaikki ikkunoissa Consolidate All Windows Yhdistä kaikki ikkunat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 494a2d944a..6ea29e0c88 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3726,6 +3726,13 @@ digits Malayalam Malayalam Thumbnail View Vignettes Thumbnails: Vignettes : Tile Mosaïque + Tile All Vertically Tout en mosaïque verticale + Tile All Horizontally Tout en mosaïque horizontale + 2-Up Layout Disposition par 2 + 3-Up Layout Disposition par 3 + 4-Up Layout Disposition par 4 + 6-Up Layout Disposition par 6 + Arrange Documents Disposer les documents Tile Edge Color Couleur du bord du carreau Tile Edge Color… Couleur du bord du carreau… Tile Full Pages Mosaïque de pages entières diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 7382b4fe9e..f7d8b1c2a9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3837,6 +3837,13 @@ Three Point Perspective Preset 5 ત્રણ બિંદુ પર્સ્પેક્ટિવ પ્રીસેટ 5 Thumbnails: થંબનેલ: Tile ટાઇલ + Tile All Vertically બધું ઊભી રીતે ટાઇલ કરો + Tile All Horizontally બધું આડી રીતે ટાઇલ કરો + 2-Up Layout 2 નું લેઆઉટ + 3-Up Layout 3 નું લેઆઉટ + 4-Up Layout 4 નું લેઆઉટ + 6-Up Layout 6 નું લેઆઉટ + Arrange Documents દસ્તાવેજો ગોઠવો Tile Edge Color ટાઇલ કિનારીનો રંગ Tile Edge Color… ટાઇલ કિનારીનો રંગ… Tile Range: ટાઇલ શ્રેણી: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index edfbe0818f..a1bbffcb84 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5130,6 +5130,13 @@ antiAlias Sharp शार्प TIFF (8-bit Color) TIFF (8-बिट रंग) TIFF (Black & White) TIFF (ब्लैक एंड व्हाइट) Tile टाइल + Tile All Vertically सभी को लंबवत टाइल करें + Tile All Horizontally सभी को क्षैतिज टाइल करें + 2-Up Layout 2 का लेआउट + 3-Up Layout 3 का लेआउट + 4-Up Layout 4 का लेआउट + 6-Up Layout 6 का लेआउट + Arrange Documents दस्तावेज़ व्यवस्थित करें tile {number} टाइल {number} Tile Edge Color टाइल एज रंग Tile Edge Color… टाइल एज रंग… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 27dda10840..b57ce2d524 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4420,6 +4420,13 @@ mark-style Japanese Japán TIFF (8-bit Color) TIFF (8 bites színes) TIFF (Black & White) TIFF (fekete-fehér) Tile Mozaikelrendezés + Tile All Vertically Összes mozaikelrendezése függőlegesen + Tile All Horizontally Összes mozaikelrendezése vízszintesen + 2-Up Layout 2-es elrendezés + 3-Up Layout 3-as elrendezés + 4-Up Layout 4-es elrendezés + 6-Up Layout 6-os elrendezés + Arrange Documents Dokumentumok elrendezése Tile Edge Color Csempeszél színe Tile Edge Color… Csempeszél színe… Tile Full Pages Teljes oldalak csempézése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f870492477..d323f3fb3d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -648,6 +648,13 @@ Previous Document Dokumen sebelumnya Cascade Bertingkat Tile Ubin + Tile All Vertically Ubin semua secara vertikal + Tile All Horizontally Ubin semua secara horizontal + 2-Up Layout Tata letak 2 + 3-Up Layout Tata letak 3 + 4-Up Layout Tata letak 4 + 6-Up Layout Tata letak 6 + Arrange Documents Susun dokumen Float in Window Mengambang di jendela Float All in Windows Mengambangkan semua di jendela Consolidate All Windows Konsolidasikan semua jendela diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7ef7dedc00..be1847efa5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3780,6 +3780,13 @@ digits Malayalam Malayalam Thumbnail View Vista miniature Thumbnails: Miniature: Tile Affianca + Tile All Vertically Affianca tutto verticalmente + Tile All Horizontally Affianca tutto orizzontalmente + 2-Up Layout Layout a 2 + 3-Up Layout Layout a 3 + 4-Up Layout Layout a 4 + 6-Up Layout Layout a 6 + Arrange Documents Disponi documenti Tile Edge Color Colore bordo tassello Tile Edge Color… Colore bordo tassello… Tile Full Pages Affianca pagine intere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c18d4c55ca..aabea31a78 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -725,6 +725,13 @@ digits Malayalam マラヤーラム数字 Previous Document 前のドキュメント Cascade 重ねて表示 Tile 並べて表示 + Tile All Vertically すべてを左右に並べて表示 + Tile All Horizontally すべてを上下に並べて表示 + 2-Up Layout 2 分割レイアウト + 3-Up Layout 3 分割レイアウト + 4-Up Layout 4 分割レイアウト + 6-Up Layout 6 分割レイアウト + Arrange Documents ドキュメントの配置 Float in Window ウィンドウを分離 Float All in Windows すべてをウィンドウに分離 Consolidate All Windows すべてのウィンドウを統合 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5ab6945aec..33cafdc24e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -622,6 +622,13 @@ Previous Document წინა დოკუმენტი Cascade კასკადად Tile ფილებად + Tile All Vertically ყველა ფილებად ვერტიკალურად + Tile All Horizontally ყველა ფილებად ჰორიზონტალურად + 2-Up Layout 2-იანი განლაგება + 3-Up Layout 3-იანი განლაგება + 4-Up Layout 4-იანი განლაგება + 6-Up Layout 6-იანი განლაგება + Arrange Documents დოკუმენტების დალაგება Float in Window ცალკე ფანჯარაში გამოტანა Float All in Windows ყველას ცალკე ფანჯრებში გამოტანა Consolidate All Windows ყველა ფანჯრის გაერთიანება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9ed9cd6a98..bbfc3bfed6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -718,6 +718,13 @@ digits Malayalam 말라얄람어 Previous Document 이전 문서 Cascade 계단식 배열 Tile 바둑판식 배열 + Tile All Vertically 모두 세로로 바둑판식 배열 + Tile All Horizontally 모두 가로로 바둑판식 배열 + 2-Up Layout 2분할 레이아웃 + 3-Up Layout 3분할 레이아웃 + 4-Up Layout 4분할 레이아웃 + 6-Up Layout 6분할 레이아웃 + Arrange Documents 문서 정렬 Float in Window 창에 플로팅 Float All in Windows 모두 창에 플로팅 Consolidate All Windows 모든 창 통합 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 711ce4c8a8..002aabacc0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1166,6 +1166,13 @@ Previous Document Vorig document Cascade Trapsgewijs schikken Tile Naast elkaar schikken + Tile All Vertically Alles verticaal naast elkaar schikken + Tile All Horizontally Alles horizontaal naast elkaar schikken + 2-Up Layout Indeling met 2 + 3-Up Layout Indeling met 3 + 4-Up Layout Indeling met 4 + 6-Up Layout Indeling met 6 + Arrange Documents Documenten schikken Float in Window In venster zweven Float All in Windows Alles in vensters zweven Consolidate All Windows Alle vensters samenvoegen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7e29ed89c5..cde65748c8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -659,6 +659,13 @@ Previous Document Poprzedni dokument Cascade Kaskadowo Tile Sąsiadująco + Tile All Vertically Wszystkie sąsiadująco w pionie + Tile All Horizontally Wszystkie sąsiadująco w poziomie + 2-Up Layout Układ po 2 + 3-Up Layout Układ po 3 + 4-Up Layout Układ po 4 + 6-Up Layout Układ po 6 + Arrange Documents Rozmieść dokumenty Float in Window Pływające w oknie Float All in Windows Wszystkie pływające w oknach Consolidate All Windows Scal wszystkie okna diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b9d233f1c9..8867015300 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3088,6 +3088,13 @@ digits Malayalam Malaiala Threshold Limite Thumbnail View Exibição em Miniatura Tile Bloco + Tile All Vertically Todos em Bloco na Vertical + Tile All Horizontally Todos em Bloco na Horizontal + 2-Up Layout Layout de 2 + 3-Up Layout Layout de 3 + 4-Up Layout Layout de 4 + 6-Up Layout Layout de 6 + Arrange Documents Organizar Documentos Tile Edge Color Cor da Borda do Bloco Tile Edge Color… Cor da Borda do Bloco… Tile Range: Intervalo de Blocos: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 5845c34c1d..3940cb892d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3766,6 +3766,13 @@ digits Malayalam Малаялам Thumbnail View Миниатюры Thumbnails: Миниатюры: Tile Плитка + Tile All Vertically Все плиткой по вертикали + Tile All Horizontally Все плиткой по горизонтали + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядочить документы Tile Edge Color Цвет края плитки Tile Edge Color… Цвет края плитки… Tile Full Pages Плитка целых страниц diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9e37b924b0..b070c937a1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3656,6 +3656,13 @@ digits Malayalam Malayalam Thumbnail View Miniatyrvy Thumbnails: Miniatyrer: Tile Sida vid sida + Tile All Vertically Alla sida vid sida lodrätt + Tile All Horizontally Alla sida vid sida vågrätt + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Ordna dokument Tile Edge Color Rutkantsfärg Tile Edge Color… Rutkantsfärg… Tile Full Pages Dela upp i hela sidor diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b23fc994a9..7f86184a60 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -421,6 +421,17 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { assert!(bad.is_empty(), "{}", bad.join("\n")); } +/// Window › Arrange's Tile layouts and the application bar's Arrange Documents button. +#[test] +fn tile_layout_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Tile All Vertically", "Tile All Horizontally", "2-Up Layout", "3-Up Layout", "4-Up Layout", "6-Up Layout", "Arrange Documents"] + { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Preference choices and the marquee's E hint share the same translated labels. #[test] fn marquee_selection_labels_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e5278e58c6..9096a2d401 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3519,6 +3519,13 @@ digits Malayalam Malayalam Thumbnail View Küçük Resim Görünümü Thumbnails: Küçük resimler: Tile Fayans + Tile All Vertically Tümünü Dikey Fayans + Tile All Horizontally Tümünü Yatay Fayans + 2-Up Layout 2'li Düzen + 3-Up Layout 3'lü Düzen + 4-Up Layout 4'lü Düzen + 6-Up Layout 6'lı Düzen + Arrange Documents Belgeleri Düzenle Tile Edge Color Döşeme Kenar Rengi Tile Edge Color… Döşeme Kenar Rengi… Tile Full Pages Tam Sayfaları Döşe diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 160d9a2c09..c01d0a2141 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3773,6 +3773,13 @@ effect Points Точки Thumbnail View Мініатюри Thumbnails: Мініатюри: Tile Плитка + Tile All Vertically Усі плиткою вертикально + Tile All Horizontally Усі плиткою горизонтально + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядкувати документи Tile Edge Color Колір краю плитки Tile Edge Color… Колір краю плитки… Tile Full Pages Плитка цілих сторінок diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 45312793f3..66942a71d3 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4130,6 +4130,13 @@ mark-style Japanese Kiểu Nhật Thumbnail View Dạng xem hình thu nhỏ Thumbnails: Hình thu nhỏ: Tile Ô + Tile All Vertically Xếp tất cả theo chiều dọc + Tile All Horizontally Xếp tất cả theo chiều ngang + 2-Up Layout Bố cục 2 + 3-Up Layout Bố cục 3 + 4-Up Layout Bố cục 4 + 6-Up Layout Bố cục 6 + Arrange Documents Sắp xếp tài liệu Tile Edge Color Màu cạnh ô Tile Edge Color… Màu cạnh ô… Tile Full Pages Ô toàn trang diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0b3c38c9ca..a9f4e1d7e0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3594,6 +3594,13 @@ digits Malayalam 马拉雅拉姆数字 Threshold 阈值 Thumbnail View 缩略图视图 Tile 平铺 + Tile All Vertically 全部垂直平铺 + Tile All Horizontally 全部水平平铺 + 2-Up Layout 双联布局 + 3-Up Layout 三联布局 + 4-Up Layout 四联布局 + 6-Up Layout 六联布局 + Arrange Documents 排列文档 Tile Edge Color 拼贴边缘颜色 Tile Edge Color… 拼贴边缘颜色… Tile Full Pages 并排完整页面 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4c8b7f2d3e..d63d2a05fc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4853,6 +4853,13 @@ digits Malayalam 馬來亞拉姆數字 Thumbnail View 縮圖檢視 Thumbnails: 縮圖: Tile 並排顯示 + Tile All Vertically 全部垂直並排顯示 + Tile All Horizontally 全部水平並排顯示 + 2-Up Layout 雙聯版面 + 3-Up Layout 三聯版面 + 4-Up Layout 四聯版面 + 6-Up Layout 六聯版面 + Arrange Documents 排列文件 Tile Edge Color 拼貼邊緣顏色 Tile Edge Color… 拼貼邊緣顏色… Tile Full Pages 並排完整頁面 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4e2d80bb45..8cb75fdae9 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -80,6 +80,7 @@ pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; use slots::RECENT_FONT_IDS; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; +pub(crate) use tree::arrange_documents_items; pub use tree::{menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7b7f7a6b21..4be65589c9 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -671,7 +671,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::doc_windows::new_window(app), "window.arrange.cascade" => crate::doc_windows::cascade(app), - "window.arrange.tile" => crate::canvas::tile(app), + "window.arrange.tile" => crate::canvas::tile(app, p), "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app, p), "window.arrange.floatAllInWindows" => crate::doc_windows::float_all(app), "window.arrange.consolidateAllWindows" if p.get("index").is_some_and(|i| !i.is_null()) => crate::doc_windows::dock(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 0d5775ffe9..5f76ce6efd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -98,6 +98,8 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { } "window.collapseDock" => crate::panel_docking::dock_collapsed(&app.ui), "window.workspace" => p.get("name").and_then(Value::as_str) == Some(app.ui.workspace.as_str()), + // The Tile layout the panes show. + "window.arrange.tile" => app.ui.tiled && crate::canvas::TileLayout::from_params(p) == Ok(app.ui.tile_layout), "window.brightness" => p.get("brightness").and_then(Value::as_str).and_then(Brightness::parse) == Some(app.ui.brightness), "view.slices.lock" => app.session.slices_locked(), "object.slice.clipToArtboard" => app.session.active().is_some_and(|d| d.doc.slices_clip_to_artboard), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 4b86b4152d..2f93db6520 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -631,16 +631,16 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ("Window", { let mut window_items = vec![ c("New Window", "window.newWindow"), - sub( - "Arrange", - vec![ - c("Cascade", "window.arrange.cascade"), - c("Tile", "window.arrange.tile"), + sub("Arrange", { + let mut arrange = vec![c("Cascade", "window.arrange.cascade")]; + arrange.extend(tile_items()); + arrange.extend([ c("Float in Window", "window.arrange.floatInWindow"), c("Float All in Windows", "window.arrange.floatAllInWindows"), c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), - ], - ), + ]); + arrange + }), sub("Workspace", crate::workspaces::menu_items()), Sep, c("Control", "window.control"), @@ -755,6 +755,27 @@ pub(super) fn transform_items() -> Vec { ] } +/// Window → Arrange's Tile layouts, one `window.arrange.tile` `layout` each (also under the +/// application bar's Arrange Documents button). +fn tile_items() -> Vec { + vec![ + c("Tile", "window.arrange.tile"), + cp("Tile All Vertically", "window.arrange.tile", json!({"layout": "vertical"})), + cp("Tile All Horizontally", "window.arrange.tile", json!({"layout": "horizontal"})), + cp("2-Up Layout", "window.arrange.tile", json!({"layout": "2up"})), + cp("3-Up Layout", "window.arrange.tile", json!({"layout": "3up"})), + cp("4-Up Layout", "window.arrange.tile", json!({"layout": "4up"})), + cp("6-Up Layout", "window.arrange.tile", json!({"layout": "6up"})), + ] +} + +/// The application bar's Arrange Documents menu: Consolidate All Windows, then the Tile layouts. +pub(crate) fn arrange_documents_items() -> Vec { + let mut items = vec![c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), Sep]; + items.extend(tile_items()); + items +} + /// Object → Arrange (also in the canvas context menu). pub(super) fn arrange_items() -> Vec { vec![ diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 21b8795662..e54b366be3 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -769,7 +769,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 80a87b4563..97ffd12af0 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -598,6 +598,10 @@ pub struct UiState { /// Consolidate All Windows. Not saved: the reference app does not save windows with a document. #[serde(skip)] pub tiled: bool, + /// How Tile lays the panes out: in a grid, side by side, stacked, or 2-up to 6-up. Not saved, + /// as `tiled` is not. + #[serde(skip)] + pub tile_layout: crate::canvas::TileLayout, /// Window › Arrange › Float in Window, Float All in Windows and Cascade: the documents in /// floating windows of their own, out of the tab strip, until Consolidate All Windows. Not /// saved, as `tiled` is not. @@ -1176,6 +1180,7 @@ impl Default for UiState { palette_query: String::new(), screen_mode: 0, tiled: false, + tile_layout: crate::canvas::TileLayout::Grid, floating: Vec::new(), tab_document: None, draw_mode: 0, diff --git a/docs/mcp.md b/docs/mcp.md index fc03d070b6..550e2249dd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6606,14 +6606,20 @@ current, or the one before it when it was the last tab. In the desktop app a mod to ask whether to save it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to -its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. -The current document's pane is the canvas, and a press in another pane makes its document the current one. -`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab -again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` and `panes` (each pane's -`document` index, `rect` and whether it is `active`); canvas coordinates map to the current document's pane -(`canvasRect`). -its pane; it returns `{tiled, panes}`. The current document's pane is the canvas, and a press in another pane makes its -document the current one. `window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document +its pane; with fewer than two documents open it leaves the view, `tiled` and the layout as they are. It returns +`{tiled, panes, layout}`. `window.arrange.tile {layout}` picks another layout, as the other Tile items of Window › +Arrange and of the application bar's Arrange Documents button do: `grid` (the default), `vertical` (Tile All +Vertically: side by side in one row), `horizontal` (Tile All Horizontally: stacked in one column), and `2up`, `3up`, +`4up` and `6up`, which show at most that many documents (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by +two) and leave the others under their tabs. Those layouts show the first documents in tab order, and the current +document takes the last pane when it is not among them, so a click on another tab brings that document into the last +pane. Any other `layout` is an error, and the view stays as it is. The set of layouts and how each one places the panes +are VectorCraft's own. The current document's pane is the canvas, and a press in another pane makes its document the +current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows, also first in Arrange +Documents) shows one document under its tab again and returns `{tiled: false}`. The arrangement is not saved. +`ui.inspect` reports `tiled`, `tileLayout` and `panes` (each pane's `document` index, `rect` and whether it is +`active`); canvas coordinates map to the current document's pane (`canvasRect`). +`window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document out of the tab strip into a floating window of its own, `window.arrange.floatAllInWindows` (Float All in Windows) does so for every tabbed document, and `window.arrange.cascade` (Cascade) floats every document and stacks the windows 30 pt apart from the upper left of the document area; each returns `{floating}`, the floating documents' indices. On the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a1f7c81b8..51d04da8c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -724,6 +724,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. +- **Arrange Documents (G7):** the application bar's Arrange Documents button arranges the open documents in grid and tile layouts ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). Its menu, and Window › Arrange, have Consolidate All Windows, Tile (the grid), Tile All Vertically (side by side), Tile All Horizontally (stacked) and the 2-Up, 3-Up, 4-Up and 6-Up layouts, which show that many documents and leave the others under their tabs, the current one in the last pane (`window.arrange.tile {layout}`). The set of layouts and how each places the panes are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. From 418b54403d4888a6a28c27f36d2515993bbfdc71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:25:22 -0800 Subject: [PATCH 047/138] Type: stop a text edit when typing in progress can't be kept When the typing Real-time Drawing off leaves unapplied can't be kept, the Character, Paragraph and Tabs panel edits, Kerning, the Variable Font sliders, Justification, Bullets and Numbering, Tate-chu-yoko, Warichu and Underline now stop with the error instead of acting on a selection read in the text without the typing. Underline reports a failed format instead of the new state. --- .../ui-egui/src/dialogs/bullets_numbering.rs | 2 +- crates/ui-egui/src/dialogs/justification.rs | 2 +- crates/ui-egui/src/panels/character.rs | 35 ++++++++++++------- crates/ui-egui/src/panels/paragraph.rs | 2 +- crates/ui-egui/src/panels/tabs.rs | 3 +- 5 files changed, 28 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 5dd09dd8f3..f42ff03a21 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -85,7 +85,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); - if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app) { + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); } let mut values = Map::new(); diff --git a/crates/ui-egui/src/dialogs/justification.rs b/crates/ui-egui/src/dialogs/justification.rs index 607debd5ec..c10e5b00bc 100644 --- a/crates/ui-egui/src/dialogs/justification.rs +++ b/crates/ui-egui/src/dialogs/justification.rs @@ -92,7 +92,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { // While typing, the dialog acts on the paragraphs of the text being edited. let mut targets = json!({}); let mut story = None; - if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app) { + if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? { targets = json!({"ids": [id.0], "start": a, "end": b}); // After Select All in threaded text: every paragraph of every frame ([`params`]). story = crate::panels::character::text_story(app).map(|_| id.0); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 7d7e7eee40..f3430f1e13 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -263,7 +263,7 @@ pub(crate) fn format(app: &mut VectorcraftApp, p: Value) { /// has selected (the whole text when nothing is selected) while it edits text, else /// `text.setFormat` on the selected stories ([`selected_stories`]). pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result { - let Some((id, a, b)) = text_editing_kept(app) else { + let Some((id, a, b)) = text_editing_kept(app)? else { target_selected_stories(app, &mut p); return app.run("text.setFormat", p); }; @@ -320,7 +320,8 @@ fn char_cmd(app: &mut VectorcraftApp, cmd: &str, mut p: Value) { /// and Optical set no space (#5111); nowhere to set at an empty line's start. Else it is a /// character attribute like the others: the selected range, or all the text. fn set_kerning(app: &mut VectorcraftApp, value: Value) { - let Some((id, a, b)) = text_editing_kept(app) else { + let Ok(editing) = text_editing_kept(app) else { return }; + let Some((id, a, b)) = editing else { format(app, json!({"kerning": value})); return; }; @@ -517,14 +518,14 @@ pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result Result { text_style(app).ok_or("select some type first")?; let on = shared(app, |s| s.underline) != Some(true); - format(app, json!({"underline": on})); + run_format(app, json!({"underline": on}))?; Ok(json!(on)) } /// `text.setRangeStyle` with `p` on the range the Type tool has selected (the whole text when /// nothing is selected). Does nothing unless the Type tool edits text. pub(crate) fn range_style(app: &mut VectorcraftApp, p: Value) { - let Some((id, a, b)) = text_editing_kept(app) else { return }; + let Ok(Some((id, a, b))) = text_editing_kept(app) else { return }; if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { story_style(app, first, p).ok(); return; @@ -553,10 +554,12 @@ pub(crate) fn text_editing(app: &VectorcraftApp) -> Option<(NodeId, usize, usize } /// [`text_editing`] after [`end_typing`], for an edit of the text: the selection is read in the -/// text with the typing applied, which Real-time Drawing off leaves unapplied until then. -pub(crate) fn text_editing_kept(app: &mut VectorcraftApp) -> Option<(NodeId, usize, usize)> { - end_typing(app); - text_editing(app) +/// text with the typing applied, which Real-time Drawing off leaves unapplied until then. When the +/// typing can't be kept, the error (also shown in the status bar), so the edit stops instead of +/// acting on a selection in the text without the typing. +pub(crate) fn text_editing_kept(app: &mut VectorcraftApp) -> Result, String> { + try_end_typing(app)?; + Ok(text_editing(app)) } /// The frames of the threaded story whose whole text the Type tool has selected after Select All, @@ -635,15 +638,21 @@ fn story_style(app: &mut VectorcraftApp, first: NodeId, mut p: Value) -> Result< /// typing Real-time Drawing off left unapplied is applied first; when it can't be kept, the error /// shows and the session goes on. pub(crate) fn end_typing(app: &mut VectorcraftApp) { + try_end_typing(app).ok(); +} + +/// [`end_typing`] that also returns the error when the typing can't be kept. +fn try_end_typing(app: &mut VectorcraftApp) -> Result<(), String> { if app.session.tool_options().get("typing").and_then(Value::as_bool) == Some(true) { if let Err(e) = app.keep_typing() { - app.status(e); - return; + app.status(e.clone()); + return Err(e); } app.session.set_tool_option("commitTyping", &json!(true)); app.session.commit_interaction().ok(); app.sync_views(); } + Ok(()) } static CTX: OnceLock = OnceLock::new(); @@ -1236,7 +1245,9 @@ pub(crate) fn axis_sliders(app: &mut VectorcraftApp, ui: &mut Ui, face: &vectorc /// Set Variable Font settings `axes` on the text the panel acts on, live while a slider drags. fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { match text_editing_kept(app) { - Some((id, a, b)) => { + // The typing can't be kept (the error shows): nothing is set. + Err(_) => {} + Ok(Some((id, a, b))) => { let mut q = json!({"id": id.0, "fontAxes": axes}); // After Select All in threaded text: every frame of the story. if let Some(first) = text_story(app).and_then(|story| story.first().copied()) { @@ -1248,7 +1259,7 @@ fn axes_cmd(app: &mut VectorcraftApp, axes: Value, phase: widgets::Live) { } super::live_run(app, "Character", "text.setRangeStyle", q, phase); } - None => { + Ok(None) => { let mut p = json!({ "fontAxes": axes }); target_selected_stories(app, &mut p); super::live_run(app, "Character", "text.setFormat", p, phase); diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 838bcebd13..b004c67f6c 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -80,7 +80,7 @@ fn para_cmd(app: &mut VectorcraftApp, cmd: &str, p: Value) { /// the Selection tool these are the paragraphs of every frame of the selected stories /// ([`super::character::selected_stories`]). pub(crate) fn run_on_paragraphs(app: &mut VectorcraftApp, cmd: &str, mut p: Value) -> Result { - if let Some((id, a, b)) = super::character::text_editing_kept(app) { + if let Some((id, a, b)) = super::character::text_editing_kept(app)? { match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => p["ids"] = json!(story.iter().map(|f| f.0).collect::>()), diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 187ce21c42..b5dfb017a1 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -423,7 +423,8 @@ fn stops_json(stops: &[TabStop]) -> Value { /// frame of the selected stories ([`super::character::selected_stories`]). Returns false when it /// fails. fn apply(app: &mut VectorcraftApp, stops: &[TabStop]) -> bool { - if let Some((id, a, b)) = super::character::text_editing_kept(app) { + let Ok(editing) = super::character::text_editing_kept(app) else { return false }; + if let Some((id, a, b)) = editing { let p = match super::character::text_story(app) { // After Select All in threaded text: every paragraph of every frame. Some(story) => json!({"stops": stops_json(stops), "ids": story.iter().map(|f| f.0).collect::>()}), From 40e1a80d5cdfce1feb7a1c1a8d8c8ed49b40180f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:26:11 -0800 Subject: [PATCH 048/138] Window: a document that keeps its pane keeps its zoom when another closes Panes refit a view when its slot or its place in the layout changes, not when the number of panes changes. Closing the sixth document in 6-Up leaves the other five in their panes with their zoom and scroll; side by side and stacked, every pane changes size and each document fits its new pane. --- crates/ui-egui/src/canvas/panes.rs | 16 +++++++----- crates/ui-egui/src/canvas/panes/tests.rs | 33 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 6b8eea9440..703c6b46bd 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -322,16 +322,18 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - // A window opened, closed, floated or docked changes the panes, and so does coming back to the - // panes from one window: each window fits its new pane. With as many panes as before, only a - // window that moved to another pane fits it, as when a tab brings its window into the last pane - // of a 2-up to 6-up layout: the others keep their zoom and scroll. Windows are compared by - // their slots, since a closed document shifts the indices of the documents after it. + // A window that moved to another pane fits it, and so does a window whose pane changed place or + // size because a window opened, closed, floated or docked, or because the panes came back from + // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its + // window into the last pane of a 2-up to 6-up layout, or when 6-Up loses its sixth document. + // Windows are compared by their slots, since a closed document shifts the indices of the + // documents after it, and panes by their place in the layout. let before = std::mem::take(&mut app.canvas.panes.last_slots); let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); - let same_panes = before.len() == now.len(); + let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0)); + let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit)); for (i, (w, s)) in shown.iter().zip(&now).enumerate() { - if same_panes && s.is_some() && before.get(i) == Some(s) { + if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) { continue; } if let Some(v) = crate::doc_windows::view_mut(app, *w) { diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 2ad0af3dc1..1fcbd7cc61 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -232,6 +232,39 @@ fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); } +/// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the +/// others in their panes with the zoom they had. Side by side, closing one widens every pane, and +/// each document fits its new pane. +#[test] +fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() { + let mut app = app_with(6); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 2, 3, 4, 5]); + app.views[1].zoom *= 2.0; + let zoomed = app.views[1].zoom; + app.run("file.close", json!({"index": 5})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.views[1].zoom, zoomed, "the document that kept its pane keeps its zoom"); + + let mut app = app_with(3); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.views[1].zoom *= 2.0; + app.run("file.close", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1]); + let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1; + let v = app.views[1]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}"); +} + #[test] fn tile_refuses_a_layout_it_does_not_have() { let mut app = app_with(3); From 02351b0105c30c98d9e6e1122b49abd9769cfb12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:45:34 -0800 Subject: [PATCH 049/138] Window: a narrow application bar drops Arrange Documents before the search icon The search icon takes the first icon slot beside the workspace switcher, as before Arrange Documents was added; Arrange Documents shows only when a second slot fits. --- crates/ui-egui/src/canvas/panes/tests.rs | 26 +++++++++++++++++++++++- crates/ui-egui/src/chrome.rs | 14 ++++++------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 1fcbd7cc61..e3da1a6a60 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -341,7 +341,12 @@ fn the_tile_items_check_the_layout_the_panes_show() { /// One frame of the application bar with screen-reader nodes on → the nodes. fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { - let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 800.0)); + app_bar_frame_in(app, ctx, events, 1400.0) +} + +/// [`app_bar_frame`] on a window `width` points wide. +fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, width: f32) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0)); let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); out.textures_delta.clear(); out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() @@ -395,6 +400,25 @@ fn the_arrange_documents_button_tiles_and_consolidates() { assert!(!app.ui.tiled); } +/// As the application bar narrows, Arrange Documents goes before the search icon. +#[test] +fn a_narrow_application_bar_keeps_search_before_arrange_documents() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut search_alone = false; + for width in (200..=1400).rev().step_by(4) { + app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands and tools").is_some()); + assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search icon"); + search_alone |= search && !arrange; + } + assert!(search_alone, "some width shows the search icon without Arrange Documents"); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 96b4d12965..989cebadc0 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -84,8 +84,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let menus_end = if app.services.native_menu.is_some() { ui.cursor().min.x } else { menus::menu_bar(app, ui) }; // The right-side group fills the space after the menus from the right; when it runs // short, Discord goes first (it is also under Help), then Explore tutorials (also - // Window › Learn), then the search icon (the palette stays under its shortcut), then - // Arrange Documents (also Window › Arrange), then the workspace switcher narrows. + // Window › Learn), then Arrange Documents (also Window › Arrange), then the search icon + // (the palette stays under its shortcut), then the workspace switcher narrows. let full = ui.max_rect(); let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() }; let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom())); @@ -105,15 +105,15 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text); let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0); let gap = ui.spacing().item_spacing.x; - // Arrange Documents, beside the switcher, then the search icon, as in PhotoCraft: each - // shown while a minimal switcher fits beside it. + // The search icon, as in PhotoCraft, then Arrange Documents between it and the switcher: + // each shown while a minimal switcher fits beside it. let icon = 28.0; - let arrange = switcher && room >= 64.0 + 8.0 + gap + icon; - let search = arrange && room >= 64.0 + 8.0 + 2.0 * (gap + icon); + let search = switcher && room >= 64.0 + 8.0 + gap + icon; + let arrange = search && room >= 64.0 + 8.0 + 2.0 * (gap + icon); let icons = f32::from(u8::from(arrange) + u8::from(search)); let ws_w = ws_w.min(room - 8.0 - icons * (gap + icon)).max(64.0); // Explore tutorials, beside the search icon, opens the Learn panel. - let learn = search && room >= ws_w + 8.0 + 3.0 * (gap + icon); + let learn = arrange && room >= ws_w + 8.0 + 3.0 * (gap + icon); let discord = learn && room >= ws_w + 8.0 + 3.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; From d6761e23baf2e7b94077089661d062878929d134 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:51:04 -0800 Subject: [PATCH 050/138] Unit Converter: a comma in a sum reads as a decimal comma again The number fields read a comma in a sum as a decimal comma, so 1,500+2 is 3.5 (widgets::decimal_point_tests::a_decimal_comma_reads_as_a_point), and only a value that is one number with a thousands comma, such as 1,000 mm, is refused. Checking each number of a sum for a thousands comma broke that test. The check is back to the single number, and addon.units.convert reads 1,500+2 the same way the number fields do. --- crates/doc/src/units.rs | 16 +++++----------- crates/engine/src/cmd/addons/units/tests.rs | 7 ++----- 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 2ae33d0783..052830ef0f 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -317,18 +317,12 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } -/// Does `text` hold a number written with a thousands comma, as `1,000` or `12,500 mm`: one to -/// three digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a -/// decimal it would be a thousand times too small, so the field refuses it instead (`0,125` and -/// `1,25` are decimals). Each number of a sum is checked on its own, so `1,000 mm+1 mm` and -/// `+1,000` are refused too. +/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three +/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it +/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are +/// decimals). fn thousands(text: &str) -> bool { - text.split(['+', '-', '*', '/']).any(thousands_number) -} - -/// Is `number`, one number of a field value, written with a thousands comma ([`thousands`])? -fn thousands_number(number: &str) -> bool { - let number = number.trim(); + let number = text.trim().trim_start_matches('-'); let Some((whole, rest)) = number.split_once(',') else { return false }; let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); (1..=3).contains(&whole.len()) diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 12e93a8a02..8ab0bd8984 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -72,6 +72,8 @@ fn values_read_as_number_fields_read_them() { assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0)); // Each number of a sum reads its own separator. assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4)); + // A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5. + assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); } @@ -145,11 +147,6 @@ fn bad_values_and_units_are_refused() { // A thousands comma is refused, as the number fields refuse it. json!({"value": "1,000 mm"}), json!({"value": "1,000.5"}), - // So is a thousands comma in any number of a sum. - json!({"value": "1,000 mm+1 mm"}), - json!({"value": "1 mm+1,000 mm"}), - json!({"value": "+1,000"}), - json!({"value": "2*1,000"}), // A long expression is refused instead of exhausting the stack. json!({"value": format!("1{}", "+1".repeat(200_000))}), json!({"value": format!("1{}", "+1".repeat(129))}), From 71686757ec7acd01178957258989b5010c9ee9f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:09:03 -0800 Subject: [PATCH 051/138] Unit Converter: a null unit is an error addon.units.convert read {"value": 12, "unit": null} as 12 points. Only an omitted unit is points now; a null unit is refused as an unknown unit. --- crates/engine/src/cmd/addons/units.rs | 4 ++-- crates/engine/src/cmd/addons/units/tests.rs | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs index 5d362a0acb..b5d844709a 100644 --- a/crates/engine/src/cmd/addons/units.rs +++ b/crates/engine/src/cmd/addons/units.rs @@ -57,9 +57,9 @@ pub fn in_every_unit(pt: f64) -> Value { json!({ "points": pt, "units": units }) } -/// The unit `p` gives for a number without a suffix (points when left out). +/// The unit `p` gives for a number without a suffix (points when left out; null is an error). fn unit_param(p: &Value) -> Result { - let Some(given) = p.get("unit").filter(|u| !u.is_null()) else { return Ok(Unit::Points) }; + let Some(given) = p.get("unit") else { return Ok(Unit::Points) }; let named = given.as_str().filter(|name| name.len() <= MAX_TEXT_LEN).and_then(Unit::named_east_asian); named.ok_or_else(|| { let u = match given { diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 8ab0bd8984..1216a1ca0b 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -155,6 +155,8 @@ fn bad_values_and_units_are_refused() { json!({"value": 1, "unit": "furlongs"}), json!({"value": 1, "unit": 5}), json!({"value": 1, "unit": ["mm"]}), + // Only an omitted `unit` is points. + json!({"value": 1, "unit": null}), ] { match s.execute("addon.units.convert", &p) { Err(EngineError::BadParams { cmd, .. }) => assert_eq!(cmd, "addon.units.convert", "{p}"), From 27fa52b97f2c1a68c4025dfb06858c77ff799dfc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 20:33:57 -0800 Subject: [PATCH 052/138] Unit Converter: a number typed in the Picas row is in picas With Preferences > Units > Numbers Without Units Are Points on (the default), 2 typed in the panel's Picas row read as 2 pt and showed 0.167 p. Each row now reads a number without a unit in its own unit, so 2 in the Picas row is 2 picas, as addon.units.convert reads it with unit picas. Length fields in other panels still follow the preference. --- crates/ui-egui/src/addons/units.rs | 5 +++++ crates/ui-egui/src/addons/units/tests.rs | 28 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/crates/ui-egui/src/addons/units.rs b/crates/ui-egui/src/addons/units.rs index 2e2801a2ca..8822b70167 100644 --- a/crates/ui-egui/src/addons/units.rs +++ b/crates/ui-egui/src/addons/units.rs @@ -141,6 +141,10 @@ pub(crate) fn apply(app: &mut VectorcraftApp, ui: &Ui, st: &Converter) -> Result pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut st: Converter = pstate(ui.ctx(), STATE); st.follow(document_now(app)); + // A number typed without a unit is in its row's unit, so 2 in the Picas row is 2 picas, also + // with Preferences › Units › Numbers Without Units Are Points on; other panels' fields keep it. + let bare_points = widgets::typed_unit(ui.ctx(), Unit::Picas) == Unit::Points; + widgets::set_bare_numbers_are_points(ui.ctx(), false); for unit in Unit::EAST_ASIAN { widgets::label_row(ui, unit.label(), LABEL_W, |ui| { // A length too large to show in one of the units (near the largest number, in Q and @@ -160,6 +164,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }); } + widgets::set_bare_numbers_are_points(ui.ctx(), bare_points); if widgets::check(ui, "Copy with Units", st.with_units, true) { st.with_units = !st.with_units; } diff --git a/crates/ui-egui/src/addons/units/tests.rs b/crates/ui-egui/src/addons/units/tests.rs index 63d35f8b8d..3959157032 100644 --- a/crates/ui-egui/src/addons/units/tests.rs +++ b/crates/ui-egui/src/addons/units/tests.rs @@ -100,6 +100,34 @@ fn typing_in_a_field_updates_the_others_and_text_that_does_not_read_leaves_them( assert!(near(st.points.unwrap(), 36.0), "{st:?}"); } +#[test] +fn a_number_typed_without_a_unit_in_the_picas_row_is_in_picas() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // Numbers Without Units Are Points is on (its default), and stays on for other fields. + crate::widgets::set_bare_numbers_are_points(&ctx, true); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.05; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { events, time: Some(time), screen_rect, focused: true, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + pstate::(&ctx, STATE) + }; + let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + // Tab reaches the Points field, then the Picas field (the copy buttons are off with no length). + for _ in 0..2 { + frame(&mut app, vec![tab.clone()]); + frame(&mut app, vec![]); + } + let st = frame(&mut app, vec![Event::Text("2".into())]); + assert!(st.points.is_some_and(|pt| near(pt, 24.0)), "{st:?}"); + assert_eq!(crate::widgets::typed_unit(&ctx, Unit::Picas), Unit::Points, "other fields still read points"); +} + #[test] fn picking_a_side_shows_that_side_of_the_size_read() { let mut st = Converter { size: Some((72.0, 36.0)), ..Converter::default() }; From 18297cc66225e5288a4792668d8f1c46ef00d214 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 21:52:07 -0800 Subject: [PATCH 053/138] Unit Converter: a signed or inch- or foot-suffixed thousands comma is refused +1,000 read as 1 pt and 1,000" as 1 inch, though a single number with a thousands comma is refused. The check now allows a leading + as well as -, and accepts " and ' as the unit after the number, so +1,000, 1,000" and 1,000' are refused in addon.units.convert and in the number fields. --- crates/doc/src/units.rs | 13 +++++++------ crates/engine/src/cmd/addons/units/tests.rs | 3 +++ crates/ui-egui/src/widgets.rs | 2 +- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 052830ef0f..9552493399 100644 --- a/crates/doc/src/units.rs +++ b/crates/doc/src/units.rs @@ -317,19 +317,20 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> { if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() } } -/// Is `text` a number written with a thousands comma, as `1,000` or `12,500 mm`: one to three -/// digits (not a lone 0), a comma, exactly three digits, then at most a unit? Read as a decimal it -/// would be a thousand times too small, so the field refuses it instead (`0,125` and `1,25` are -/// decimals). +/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or +/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at +/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it +/// instead (`0,125` and `1,25` are decimals). fn thousands(text: &str) -> bool { - let number = text.trim().trim_start_matches('-'); + let number = text.trim(); + let number = number.strip_prefix(['+', '-']).unwrap_or(number); let Some((whole, rest)) = number.split_once(',') else { return false }; let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len())); (1..=3).contains(&whole.len()) && whole.bytes().all(|b| b.is_ascii_digit()) && !whole.starts_with('0') && part.len() == 3 - && unit.trim().chars().all(char::is_alphabetic) + && unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'') } /// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index 1216a1ca0b..f914c53092 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -147,6 +147,9 @@ fn bad_values_and_units_are_refused() { // A thousands comma is refused, as the number fields refuse it. json!({"value": "1,000 mm"}), json!({"value": "1,000.5"}), + json!({"value": "+1,000"}), + json!({"value": "1,000\""}), + json!({"value": "1,000'"}), // A long expression is refused instead of exhausting the stack. json!({"value": format!("1{}", "+1".repeat(200_000))}), json!({"value": format!("1{}", "+1".repeat(129))}), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 36145224d5..85f2ca714a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -577,7 +577,7 @@ mod decimal_point_tests { } assert_eq!(mm("1,000.5"), None, "a point and a comma"); assert_eq!(mm("1,2,3"), None, "two commas"); - for thousand in ["1,000", "12,500 mm", "-1,000", "999,999mm"] { + for thousand in ["1,000", "12,500 mm", "-1,000", "+1,000", "999,999mm", "1,000\"", "1,000'"] { assert_eq!(mm(thousand), None, "{thousand} reads as thousands: refused, not a thousand times too small"); } for (text, want) in [("0,125", 0.125), ("1,25", 1.25), ("1,0000", 1.0), ("1,500+2", 3.5)] { From 8f5aed7ea47de494153cd13c4203d43fdf9709bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 22:07:06 -0800 Subject: [PATCH 054/138] Variables: Import Data Sets reads % columns of graph data files dataset.import refused every header cell that starts with % unless it was a variable's exact name, so the five-column example on the data source set-up page did not import. A %Name header now defines the graph variable Name, or names it when the document has it, and each cell of the column is the path of a graph data file. The file is read as the Graph Data window's Import Data reads one, and the data becomes the data set's graph value, which applies as graph.setData applies it. A relative path is taken from the new base parameter, else from the folder of the CSV file at path. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and % columns that hold more than 256 MB in all refuse the import with the line and the column, and the document is left as it was. Each file is read once per import. Import Data's text decoding, cell splitting and sheet-to-data steps move from the Graph Data dialog to the engine (graph/data.rs), so both imports read a file the same way. dataset.export's warning now lists a % header over values as refused and a %-prefixed variable of another kind as read back with another kind. --- crates/engine/src/cmd.rs | 4 + crates/engine/src/cmd/graph.rs | 3 +- crates/engine/src/cmd/graph/data.rs | 96 ++++++++++++++++ crates/engine/src/cmd/variablecmds.rs | 5 +- crates/engine/src/cmd/variablecmds/csv.rs | 121 +++++++++++++++++--- crates/engine/src/tests/variables.rs | 130 ++++++++++++++++++++-- crates/ui-egui/src/dialogs/graph_data.rs | 73 ++---------- crates/ui-egui/src/i18n/cs.tsv | 7 +- crates/ui-egui/src/i18n/de.tsv | 7 +- crates/ui-egui/src/i18n/fr.tsv | 7 +- crates/ui-egui/src/i18n/hi.tsv | 7 +- crates/ui-egui/src/i18n/hu.tsv | 7 +- crates/ui-egui/src/i18n/it.tsv | 7 +- crates/ui-egui/src/i18n/ja.tsv | 7 +- crates/ui-egui/src/i18n/ko.tsv | 7 +- crates/ui-egui/src/i18n/nl.tsv | 7 +- crates/ui-egui/src/i18n/pl.tsv | 7 +- crates/ui-egui/src/i18n/pt-br.tsv | 7 +- crates/ui-egui/src/i18n/sv.tsv | 7 +- crates/ui-egui/src/i18n/tr.tsv | 7 +- crates/ui-egui/src/i18n/uk.tsv | 7 +- crates/ui-egui/src/i18n/zh-hans.tsv | 7 +- crates/ui-egui/src/i18n/zh-hant.tsv | 7 +- crates/ui-egui/src/panels/variables.rs | 2 + docs/mcp.md | 35 ++++-- docs/target-app-parity.md | 1 + 26 files changed, 463 insertions(+), 119 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 99b8e1ecdd..72ca754ccd 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -896,6 +896,10 @@ pub use brushsym::reset_transformation_changes; /// Data window reads files by it too). pub use variablecmds::utf16_order_without_mark; +/// How the Graph Data window's Import Data and Import Data Sets' `%` columns read a graph data +/// file: its size limit, its text, its cells and the data `graph.setData` takes from them. +pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; + /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 06557e6f59..a504aa4df3 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -37,7 +37,8 @@ use axis::{nice_axis, tick_values}; #[cfg(test)] use columns::{fill_totals, total_text}; pub use commands::specs; -pub(crate) use data::{apply_csv, parse_csv}; +pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; pub(crate) use edit::{graphs_holding, keep_placed}; diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index 68a83fd80a..b231ee2051 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -91,6 +91,102 @@ pub(super) fn to_csv(g: &GraphSpec) -> String { g.to_csv() } +// ---------- graph data files ---------- + +/// The largest graph data file that Graph Data's Import Data and Import Data Sets' `%` columns +/// read, 1 MB (1,048,576 bytes). +pub const MAX_GRAPH_DATA_FILE: usize = 1 << 20; + +/// A graph data sheet's size: a row of labels over a graph's categories, a column of labels +/// before its series; a cell's longest text. +const SHEET_ROWS: usize = vectorcraft_doc::MAX_GRAPH_CATEGORIES + 1; +const SHEET_COLS: usize = vectorcraft_doc::MAX_GRAPH_SERIES + 1; +const SHEET_CELL: usize = 256; + +/// A graph data file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode +/// Text"), else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives +/// them a byte order ([`crate::cmd::utf16_order_without_mark`]), else UTF-8 with or without one. +/// UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an unpaired +/// surrogate reads as U+FFFD. +pub fn graph_data_text(bytes: &[u8]) -> String { + let utf16 = |rest: &[u8], le: bool| { + let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); + String::from_utf16_lossy(&units) + }; + match bytes { + [0xFF, 0xFE, rest @ ..] => utf16(rest, true), + [0xFE, 0xFF, rest @ ..] => utf16(rest, false), + [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), + _ => match bytes.contains(&0).then(|| crate::cmd::utf16_order_without_mark(bytes)).flatten() { + Some(le) => utf16(bytes, le), + None => String::from_utf8_lossy(bytes).into_owned(), + }, + } +} + +/// A graph data sheet cell's text: one line (tabs and line breaks become spaces), at most 256 +/// characters. +pub fn graph_cell_text(s: &str) -> String { + s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(SHEET_CELL).collect() +} + +/// Text from a file or the clipboard as graph data sheet cells: tab-separated when any line holds +/// a tab, else comma-separated (decided once, so a label with a comma in a tab-separated file +/// stays whole), at most a graph's rows and columns. +pub fn graph_grid_from_text(text: &str) -> Vec> { + let sep = if text.contains('\t') { '\t' } else { ',' }; + text.lines().take(SHEET_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(SHEET_COLS).map(|c| graph_cell_text(c.trim())).collect()).collect() +} + +/// A graph data sheet as `graph.setData` takes it: the first row holds the series labels, the +/// first column the category labels (none when all are blank), and the other cells the values (a +/// blank cell, or text that isn't a number, has none), without the empty rows and columns past +/// the data. +pub fn graph_data_from_grid(grid: &[Vec]) -> Value { + let cell = |r: usize, c: usize| grid.get(r).and_then(|row| row.get(c)).cloned().unwrap_or_default(); + let filled = |s: &String| !s.trim().is_empty(); + // At most a graph's rows and columns, as a file gives (`graph_grid_from_text`): a grid sent by + // automation is any size, and the values are their product. + let grid = &grid[..grid.len().min(SHEET_ROWS)]; + let rows = grid.iter().rposition(|r| r.iter().take(SHEET_COLS).any(filled)).map_or(1, |i| i + 1).max(1); + let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(SHEET_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); + let label = |s: &str| { + let s = s.trim(); + // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. + s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() + }; + // Series labels up to the last one given (none when all are blank). + let mut series: Vec = (1..cols).map(|c| label(&cell(0, c))).collect(); + while series.last().is_some_and(String::is_empty) { + series.pop(); + } + let mut categories: Vec = (1..rows).map(|r| label(&cell(r, 0))).collect(); + if categories.iter().all(String::is_empty) { + categories.clear(); + } + let values: Vec> = (1..rows) + .map(|r| { + (1..cols) + .map(|c| { + let t = cell(r, c); + t.trim().parse::().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) + }) + .collect() + }) + .collect(); + json!({ "series": series, "categories": categories, "rows": values }) +} + +/// The graph value (the CSV form [`apply_csv`] reads) of a graph data file's bytes, read as Graph +/// Data's Import Data reads the file into its sheet and Apply sends the sheet: so applying the +/// value gives a graph the data that Import Data and Apply give it. +pub(crate) fn graph_csv_from_file(bytes: &[u8]) -> Result { + let data = graph_data_from_grid(&graph_grid_from_text(&graph_data_text(bytes))); + let mut spec = GraphSpec::default(); + apply_data(&mut spec, &data, "dataset.import")?; + Ok(spec.to_csv()) +} + /// Apply CSV graph data to the graph root `id` and rebuild its art (Variables data merge), as `graph.setData` with /// `csv` does. Data the graph already holds leaves the graph as it is. pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> { diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index a73c16448b..9650a423a9 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -8,7 +8,8 @@ //! variable name per column, which export writes with `#` before a visibility variable and `@` //! before an image variable); import replaces the datasets, names the rows Data Set 1, 2…, //! also reads tab-separated files, and reads header cells that define new variables (`#` for -//! visibility, `@` for image, no prefix for text). `variable.loadLibrary` replaces the variables and data sets with the +//! visibility, `@` for image, `%` for graph, whose cells name graph data files, no prefix for +//! text). `variable.loadLibrary` replaces the variables and data sets with the //! variables and data sets of a variable library, the XML file of the reference app's Save //! Variable Library, and `variable.saveLibrary` writes the variables and data sets as one. //! Agents reach every command through `run_command`, like all engine commands. @@ -868,7 +869,7 @@ pub fn specs() -> Vec { "Import Data Sets…", ["Window", "Variables"], None, - "{path? | data? | dataBase64? | csv?} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, and a header without a prefix defines a text variable. A prefixed header whose name is a variable of another kind, and a `%` header that isn't a variable's exact name (graph data files), are refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}", + "{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}", has_doc, dataset_import ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index be9db3b841..0d3d1057c9 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -3,6 +3,7 @@ use super::{ json, read_file_head, str_param, variables_unlocked, write_file, }; use crate::cmd::place::text::windows_1252; +use crate::cmd::{MAX_GRAPH_DATA_FILE, text_param}; /// Cap on a graph variable's CSV (MCP and files are untrusted). pub(super) const MAX_GRAPH_CSV: usize = 256 * 1024; @@ -268,10 +269,11 @@ fn export_header(v: &Variable) -> String { /// What [`dataset_import`] does with each variable's column of the CSV that [`datasets_to_csv`] /// writes, in a document without the variables: the first list names the variables whose header -/// or values it refuses, so it doesn't import the file (a `%` header, a `#` header whose values -/// aren't true or false, a header that names a variable an earlier column named), and the second -/// the variables it reads as another variable (a text variable whose name starts with `#` or `@`, -/// and a graph variable, which no header cell defines). +/// or values it refuses, so it doesn't import the file (a `%` header over values, which it reads as +/// paths of graph data files, a `#` header whose values aren't true or false, a header that names +/// a variable an earlier column named), and the second the variables it reads as another variable +/// (a variable whose name starts with `#`, `@` or `%` and isn't of that prefix's kind, and a graph +/// variable, which the export writes without `%`). fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { const C: &str = "dataset.import"; let none = BTreeMap::new(); @@ -287,9 +289,11 @@ fn kinds_a_new_document_loses(vars: &Variables) -> (Vec<&str>, Vec<&str>) { refused.push(v.name.as_str()); continue; }; + // A `%` header's cells are paths of graph data files, which the values the export writes aren't. + let files = kind == VariableKind::Graph && name != cell; let cells_read = vars.datasets.iter().filter_map(|d| d.values.get(&v.name)).all(|val| { let cell = value_to_cell(val); - cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() + if files { cell.trim().is_empty() } else { cell_to_value(kind, &cell, cell.is_empty(), &name, 2, C).is_ok() } }); if !cells_read { refused.push(v.name.as_str()); @@ -340,7 +344,9 @@ fn datasets_to_csv(vars: &Variables, cmd: &str) -> Result { /// that earlier columns define) names that variable. Otherwise `#` before the name makes it a /// visibility variable, `@` makes it an image variable, and a cell without a prefix names a text /// variable. A prefixed name that is already a variable must be one of the prefix's kind; a new -/// name is added to `defined`. A `%` cell that names no variable (graph data files) is refused. +/// name is added to `defined`. `%` before a name makes it a graph variable whose column holds the +/// paths of graph data files ([`graph_file_value`]); [`dataset_import`] tells such a column apart +/// by a returned name that is not the cell. fn header_variable( cell: &str, column: usize, @@ -356,8 +362,8 @@ fn header_variable( (rest.trim(), VariableKind::Visibility) } else if let Some(rest) = cell.strip_prefix('@') { (rest.trim(), VariableKind::Image) - } else if cell.starts_with('%') { - return Err(bad(cmd, format!("column {column}: `{cell}` is a `%` column of graph data files, which are not read"))); + } else if let Some(rest) = cell.strip_prefix('%') { + (rest.trim(), VariableKind::Graph) } else { (cell, VariableKind::Text) }; @@ -375,13 +381,90 @@ fn header_variable( } } +/// The most bytes the `%` columns of one import read from graph data files and keep as graph +/// values, counted together: each file's bytes once (it is read once, however many cells name it), +/// and the graph value of every cell, which each data set holds a copy of. +const MAX_GRAPH_FILES_TOTAL: usize = 256 * 1_048_576; + +/// The graph data files the `%` columns of one import have read, by path, and the bytes counted +/// against [`MAX_GRAPH_FILES_TOTAL`] so far. +#[derive(Default)] +struct GraphFiles { + read: BTreeMap, + total: usize, +} + +/// The graph value of a `%` column's cell `path` on file line `line`, in 1-based `column`, for the +/// graph variable `var`: the graph data file at `path` (taken from the folder `base` when +/// relative), read as Graph Data's Import Data reads one ([`crate::cmd::graph::graph_csv_from_file`]), +/// or no value for an empty cell. A relative path without `base`, a file that can't be read or is +/// larger than 1 MB, a file that gives a graph value longer than [`MAX_GRAPH_CSV`] bytes and more +/// than [`MAX_GRAPH_FILES_TOTAL`] bytes in all are refused, with the line and the column. +fn graph_file_value(files: &mut GraphFiles, path: &str, base: Option<&str>, var: &str, (line, column): (usize, usize)) -> Result> { + const C: &str = "dataset.import"; + let path = path.trim(); + if path.is_empty() { + return Ok(None); + } + let full = match base { + _ if std::path::Path::new(path).is_absolute() => path.to_string(), + Some(base) => std::path::Path::new(base).join(path).to_string_lossy().into_owned(), + None => { + return Err(bad( + C, + format!( + "line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path" + ), + )); + } + }; + let csv = match files.read.get(&full) { + Some(csv) => csv.clone(), + None => { + // One byte past the limit is enough to refuse the file. + let bytes = read_file_head(&full, MAX_GRAPH_DATA_FILE + 1) + .map_err(|e| bad(C, format!("line {line}, column {column}: the graph data file for `{var}` can't be read: {e}")))?; + if bytes.len() > MAX_GRAPH_DATA_FILE { + return Err(bad( + C, + format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes"), + )); + } + let csv = crate::cmd::graph::graph_csv_from_file(&bytes)?; + if csv.len() > MAX_GRAPH_CSV { + return Err(bad( + C, + format!( + "line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes" + ), + )); + } + files.total += bytes.len(); + files.read.insert(full, csv.clone()); + csv + } + }; + files.total += csv.len(); + if files.total > MAX_GRAPH_FILES_TOTAL { + return Err(bad(C, format!("line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all"))); + } + Ok(Some(DataValue::Graph(csv))) +} + /// Import datasets from CSV. Every header cell names a variable, as [`header_variable`] reads it, /// and the variables the document doesn't define yet are defined, unbound. Two headers that name -/// one variable are refused. The rows replace every dataset of the document and are named "Data -/// Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings +/// one variable are refused. The cells of a `%` column are paths of graph data files +/// ([`graph_file_value`]); a relative one is taken from the folder `base` gives, else from the +/// folder of the file `path` names. The rows replace every dataset of the document and are named +/// "Data Set 1", "Data Set 2" and so on, in file order. The document's variables and their bindings /// stay. One undo step, and none when the variables and datasets stay as they were. pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.import"; + let base = match text_param(p, "base", C)? { + Some("") => return Err(bad(C, "`base` is empty")), + Some(base) => Some(absolute_path(base)), + None => str_param(p, "path").and_then(|path| std::path::Path::new(&absolute_path(path)).parent().map(|d| d.to_string_lossy().into_owned())), + }; let (bytes, given_as_text) = datasets_csv_bytes(p, C)?; // `data` and `csv` are already text, NUL characters included (`dataset.export` writes them). let text = if given_as_text { String::from_utf8(bytes).map_err(|_| bad(C, "CSV is not UTF-8"))? } else { datasets_csv_text(&bytes, C)? }; @@ -390,7 +473,8 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "CSV is empty")); }; let kinds: BTreeMap = s.doc()?.doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind)).collect(); - let mut columns: Vec<(usize, String, VariableKind)> = Vec::new(); + // Each column: its index, its variable and kind, and whether its cells are graph data files. + let mut columns: Vec<(usize, String, VariableKind, bool)> = Vec::new(); let mut defined: Vec = Vec::new(); for (i, h) in header.iter().enumerate() { let cell = h.trim(); @@ -398,11 +482,12 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("empty header in column {}", i + 1))); } let (name, kind) = header_variable(cell, i + 1, &kinds, &mut defined, C)?; - if let Some(&(first, ..)) = columns.iter().find(|(_, n, _)| *n == name) { + if let Some(&(first, ..)) = columns.iter().find(|(_, n, ..)| *n == name) { let (first, column) = (first + 1, i + 1); return Err(bad(C, format!("columns {first} and {column} both name the variable `{name}`"))); } - columns.push((i, name, kind)); + let files = kind == VariableKind::Graph && name != cell; + columns.push((i, name, kind, files)); } // Lock Variables refuses New Variable, so the import is refused when a header would define one. if !defined.is_empty() { @@ -412,13 +497,19 @@ pub(super) fn dataset_import(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "CSV has a header but no data rows")); } let mut parsed: Vec = Vec::new(); + let mut files = GraphFiles::default(); for (n, &(line, ref row, ref quoted)) in rows.iter().skip(1).enumerate() { let name = format!("Data Set {}", n + 1); let mut values = BTreeMap::new(); - for &(col, ref var, kind) in &columns { + for &(col, ref var, kind, from_files) in &columns { let cell = row.get(col).map(String::as_str).unwrap_or(""); let was_quoted = quoted.get(col).copied().unwrap_or(false); - if let Some(v) = cell_to_value(kind, cell, was_quoted, var, line, C)? { + let value = if from_files { + graph_file_value(&mut files, cell, base.as_deref(), var, (line, col + 1))? + } else { + cell_to_value(kind, cell, was_quoted, var, line, C)? + }; + if let Some(v) = value { values.insert(var.clone(), v); } } diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index bb5b73b2f2..553ce3c4f4 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -1958,8 +1958,8 @@ fn datasets_csv_export_imports_back_to_the_same_data_sets() { } /// The export's `warning` names the variables whose column a document without the variables -/// refuses, so it doesn't import the file: a `%` header, a `#` header whose values aren't true or -/// false, and a header that names a variable an earlier column defined with another kind. A +/// refuses, so it doesn't import the file: a `%` header over values, a `#` header whose values +/// aren't true or false, and a header that names a variable an earlier column defined with another kind. A /// header that names such a variable with its kind is read with that kind, and is listed as one /// read back with another kind. #[test] @@ -1977,7 +1977,9 @@ fn datasets_csv_export_warns_of_headers_a_new_document_refuses() { let refuses = |names: &str| format!("a new document refuses this file because of these variables: {names}"); let loses = |names: &str| format!("a new document won't read these variables back with their kind: {names}"); - assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (refuses("`%Rate`"), true)); + // A `%` header's cells are read as paths of graph data files. + assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({"%Rate": "5"})), (refuses("`%Rate`"), true)); + assert_eq!(export(&[("%Rate", "text"), ("Chart", "graph")], json!({})), (loses("`%Rate`, `Chart`"), false)); assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "hello"})), (refuses("`#Tag`"), true)); assert_eq!(export(&[("#Tag", "text")], json!({"#Tag": "yes"})), (loses("`#Tag`"), false)); assert_eq!(export(&[("#Seen", "text"), ("Seen", "image")], json!({})), (refuses("`Seen`"), true)); @@ -2005,18 +2007,122 @@ fn datasets_csv_export_refuses_a_header_that_names_another_variable() { } } -/// A `%` header cell that isn't a variable's name (graph data files) is refused with its column, -/// and the import defines nothing. +/// The data `graph.setData` reports for the graph `g`: series, categories and rows. +fn graph_data(s: &mut Session, g: NodeId) -> Value { + let v = s.execute("graph.setData", &json!({"id": g.0})).unwrap(); + json!({"series": v["series"], "categories": v["categories"], "rows": v["rows"]}) +} + +/// A `%` header defines a graph variable, and each of its cells is the path of a graph data file, +/// as the set-up page's five-column example has them. A relative path is taken from the CSV file's +/// folder. Selecting a data set gives the bound graph the data that Graph Data's Import Data and +/// Apply give it for the same file: tab- or comma-separated, the first row the series labels and the +/// first column the category labels, in UTF-16 too. An empty cell is no value. #[test] -fn datasets_csv_refuses_graph_data_file_columns() { +fn datasets_csv_reads_graph_data_files_in_percent_columns() { + let dir = Folder::new("vars-csv-graph-files"); + let tabs: &[u8] = b"\t2024\t2025\nQ1\t3\t4\nQ2\t5\t6\n"; + let commas: &[u8] = b",North\nJan,7\nFeb,8\n"; + let utf16: Vec = [0xFF, 0xFE].into_iter().chain(",A\r\nX,9\r\n".encode_utf16().flat_map(u16::to_le_bytes)).collect(); + write(&dir.file("graphs/bill.txt"), tabs); + write(&dir.file("dat.csv"), commas); + write(&dir.file("ruiz.txt"), &utf16); + let absolute = dir.file("dat.csv"); + let csv = format!( + "Name,Age,@Photos,%Graphs,#Visibility\nBill,36,b.jpg,graphs/bill.txt,true\nDat,53,d.jpg,{absolute},true\nMaria,26,r.jpg,ruiz.txt,false\nNone,1,n.jpg,,true\n" + ); + let path = dir.file("data.csv"); + write(&path, csv.as_bytes()); + let mut s = session(); - let error = |s: &mut Session, csv: &str| s.execute("dataset.import", &json!({"csv": csv})).unwrap_err().to_string(); - let named = error(&mut s, "Name,Title,%Sales\nA,x,sales.txt"); - assert!(named.contains("column 3:") && named.contains("`%Sales`"), "{named}"); - let unnamed = error(&mut s, "%Sales\tTitle\nsales.txt\tx"); - assert!(unnamed.contains("column 1:") && unnamed.contains("`%Sales`"), "{unnamed}"); + let graph = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"})).unwrap(); + let g = NodeId(graph["id"].as_u64().unwrap()); + let imp = s.execute("dataset.import", &json!({"path": path})).unwrap(); + assert_eq!(imp["defined"], json!(["Name", "Age", "Photos", "Graphs", "Visibility"])); + assert_eq!(imp["imported"], 4); + let listed = s.execute("variable.list", &json!({})).unwrap(); + assert_eq!(listed["variables"][3], json!({"name": "Graphs", "kind": "graph", "bindings": 0})); + s.execute("variable.bind", &json!({"variable": "Graphs", "ids": [g.0]})).unwrap(); + + // What Import Data and Apply give the graph for each file. + let sheet = |bytes: &[u8]| { + let data = crate::cmd::graph_data_from_grid(&crate::cmd::graph_grid_from_text(&crate::cmd::graph_data_text(bytes))); + let mut probe = session(); + let p = json!({"type": "column", "x": 10, "y": 10, "width": 100, "height": 80, "csv": ",B\nY,1"}); + let id = NodeId(probe.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap()); + let mut set = data.clone(); + set["id"] = json!(id.0); + probe.execute("graph.setData", &set).unwrap(); + graph_data(&mut probe, id) + }; + for (set, bytes) in ["Data Set 1", "Data Set 2", "Data Set 3"].into_iter().zip([tabs, commas, utf16.as_slice()]) { + s.execute("dataset.select", &json!({"name": set})).unwrap(); + assert_eq!(graph_data(&mut s, g), sheet(bytes), "{set}"); + } + assert_eq!(graph_data(&mut s, g), json!({"series": ["A"], "categories": ["X"], "rows": [[9.0]]})); let vars = &s.doc().unwrap().doc.variables; - assert!(vars.variables.is_empty() && vars.datasets.is_empty()); + assert_eq!(vars.datasets[3].values.get("Graphs"), None, "an empty cell is no value"); + + // A `%` header names a graph variable the document has, and `base` sets the folder of + // relative paths when the CSV comes as text. + let mut t = session(); + t.execute("variable.define", &json!({"name": "Sales", "kind": "graph"})).unwrap(); + let base = dir.0.to_string_lossy().into_owned(); + let imp = t.execute("dataset.import", &json!({"csv": "% Sales\ndat.csv", "base": base})).unwrap(); + assert_eq!(imp["defined"], json!([])); + let value = t.doc().unwrap().doc.variables.datasets[0].values.get("Sales").cloned(); + assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains("North") && c.contains("Feb")), "{value:?}"); +} + +/// A `%` column's file that is missing, a folder, larger than 1 MB, or gives a graph value longer +/// than 256 KB, a relative path with no +/// folder to take it from, a `base` that isn't a folder path, and a `%` header whose name is a +/// variable of another kind refuse the import with the line and column, and leave the variables and +/// data sets as they were. A file of exactly 1 MB is read, and a file named by many cells is read +/// once. +#[test] +fn datasets_csv_refuses_unreadable_graph_data_files() { + let dir = Folder::new("vars-csv-graph-refused"); + write(&dir.file("ok.txt"), b"\tA\nX\t1\n"); + write(&dir.file("big.txt"), &vec![b'1'; crate::cmd::MAX_GRAPH_DATA_FILE + 1]); + let at_limit = [b"\tA\nX\t2\n".as_slice(), &vec![b' '; crate::cmd::MAX_GRAPH_DATA_FILE - 7]].concat(); + write(&dir.file("limit.txt"), &at_limit); + std::fs::create_dir_all(dir.file("folder.txt")).unwrap(); + // 10,000 categories with long labels: under 1 MB, but a graph value over 256 KB. + let long: String = (0..10_000).map(|i| format!("category label number {i:05}\t{i}\n")).collect(); + write(&dir.file("long.txt"), format!("\tA\n{long}").as_bytes()); + let base = dir.0.to_string_lossy().into_owned(); + + let mut s = session(); + s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap(); + s.execute("dataset.import", &json!({"csv": "Title\nkept"})).unwrap(); + let before = s.doc().unwrap().doc.variables.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let cases = [ + (json!({"csv": "Name,%Chart\na,ok.txt\nb,missing.txt", "base": base}), "line 3, column 2: the graph data file for `Chart` can't be read"), + (json!({"csv": "Name,%Chart\na,folder.txt", "base": base}), "line 2, column 2: the graph data file for `Chart` can't be read"), + (json!({"csv": "%Chart\nbig.txt", "base": base}), "line 2, column 1: the graph data file `big.txt` for `Chart` is larger than 1048576 bytes"), + ( + json!({"csv": "Name,%Chart\na,long.txt", "base": base}), + "line 2, column 2: the graph data file `long.txt` for `Chart` gives a graph value longer than 262144 bytes", + ), + (json!({"csv": "%Chart\nok.txt"}), "line 2, column 1: the graph data file `ok.txt` for `Chart` is a relative path"), + (json!({"csv": "%Chart\nok.txt", "base": ""}), "`base` is empty"), + (json!({"csv": "%Chart\nok.txt", "base": 3}), "`base` must be a string"), + (json!({"csv": "%Title\nok.txt", "base": base}), "column 1: `%Title` names `Title`, which is a text variable"), + ]; + for (p, want) in cases { + let e = s.execute("dataset.import", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + assert_eq!(s.doc().unwrap().doc.variables, before, "{p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{p}"); + } + + let rows: String = (0..300).map(|_| "limit.txt\n").collect(); + let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{rows}"), "base": base})).unwrap(); + assert_eq!(imp["imported"], 300, "a 1 MB file named by 300 cells counts once against the import's limit"); + let value = s.doc().unwrap().doc.variables.datasets[299].values.get("Chart").cloned(); + assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('2')), "{value:?}"); } /// Two header cells that name one variable, by the same name or by a name and its prefix, are diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index ecfb0c303e..bed1117748 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -26,14 +26,13 @@ use crate::{VectorcraftApp, widgets}; pub const KIND: &str = "graphData"; /// The sheet's size: a row of labels over a graph's categories, a column of labels before its -/// series; the least it shows; a cell's longest text. +/// series; the least it shows. const MAX_ROWS: usize = MAX_GRAPH_CATEGORIES + 1; const MAX_COLS: usize = MAX_GRAPH_SERIES + 1; const MIN_ROWS: usize = 8; const MIN_COLS: usize = 6; -const MAX_CELL: usize = 256; /// The largest file Import Data reads, 1 MB (1,048,576 bytes), the same as Import Data Sets'. -const MAX_IMPORT_BYTES: usize = 1 << 20; +const MAX_IMPORT_BYTES: usize = vectorcraft_engine::cmd::MAX_GRAPH_DATA_FILE; /// The Cell Style limits (Adjust column width and decimal digits). const MAX_DECIMALS: u64 = 10; const MAX_WIDTH: u64 = 20; @@ -103,75 +102,25 @@ pub(crate) fn grid_from_data(v: &Value) -> Grid { grid } -/// The sheet as `graph.setData` takes it: series labels, category labels (none when all are blank) -/// and the values (a blank cell, or text that isn't a number, has none), without the empty rows and -/// columns past the data. +/// The sheet as `graph.setData` takes it ([`vectorcraft_engine::cmd::graph_data_from_grid`]), +/// which Import Data Sets' `%` columns also use. pub(crate) fn data_from_grid(grid: &Grid) -> Value { - let filled = |s: &String| !s.trim().is_empty(); - // At most a graph's rows and columns, as a file gives (`grid_from_text`): a grid sent by - // automation is any size, and the values are their product. - let grid = &grid[..grid.len().min(MAX_ROWS)]; - let rows = grid.iter().rposition(|r| r.iter().take(MAX_COLS).any(filled)).map_or(1, |i| i + 1).max(1); - let cols = grid.iter().take(rows).filter_map(|r| r.iter().take(MAX_COLS).rposition(filled)).max().map_or(1, |i| i + 1).max(1); - let label = |s: &str| { - let s = s.trim(); - // A label typed in straight quotes (as the CSV form takes a number as a label) is the text inside. - s.strip_prefix('"').and_then(|t| t.strip_suffix('"')).unwrap_or(s).to_string() - }; - // Series labels up to the last one given (none when all are blank). - let mut series: Vec = (1..cols).map(|c| label(&cell(grid, 0, c))).collect(); - while series.last().is_some_and(String::is_empty) { - series.pop(); - } - let mut categories: Vec = (1..rows).map(|r| label(&cell(grid, r, 0))).collect(); - if categories.iter().all(String::is_empty) { - categories.clear(); - } - let values: Vec> = (1..rows) - .map(|r| { - (1..cols) - .map(|c| { - let t = cell(grid, r, c); - t.trim().parse::().ok().filter(|v| v.is_finite() && !t.trim().starts_with('"')).map_or(Value::Null, |v| json!(v)) - }) - .collect() - }) - .collect(); - json!({ "series": series, "categories": categories, "rows": values }) + vectorcraft_engine::cmd::graph_data_from_grid(grid) } -/// Text from a file or the clipboard as cells: tab-separated when any line holds a tab, else -/// comma-separated (decided once, so a label with a comma in a tab-separated file stays whole), at -/// most a graph's rows and columns. +/// Text from a file or the clipboard as cells ([`vectorcraft_engine::cmd::graph_grid_from_text`]). pub(crate) fn grid_from_text(text: &str) -> Grid { - let sep = if text.contains('\t') { '\t' } else { ',' }; - text.lines().take(MAX_ROWS).map(|l| l.trim_end_matches('\r').split(sep).take(MAX_COLS).map(|c| clean(c.trim())).collect()).collect() + vectorcraft_engine::cmd::graph_grid_from_text(text) } -/// A text file's bytes as text: UTF-16 with its byte-order mark (spreadsheets' "Unicode Text"), -/// else UTF-16 without one when the bytes hold NUL bytes and Import Data Sets' rule gives them a -/// byte order ([`vectorcraft_engine::cmd::utf16_order_without_mark`]), else UTF-8 with or without -/// one. UTF-16 is read as it is after a byte-order mark: an odd last byte is left out, and an -/// unpaired surrogate reads as U+FFFD. +/// A text file's bytes as text ([`vectorcraft_engine::cmd::graph_data_text`]). pub(crate) fn decode(bytes: &[u8]) -> String { - let utf16 = |rest: &[u8], le: bool| { - let units: Vec = rest.as_chunks::<2>().0.iter().map(|p| if le { u16::from_le_bytes(*p) } else { u16::from_be_bytes(*p) }).collect(); - String::from_utf16_lossy(&units) - }; - match bytes { - [0xFF, 0xFE, rest @ ..] => utf16(rest, true), - [0xFE, 0xFF, rest @ ..] => utf16(rest, false), - [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8_lossy(rest).into_owned(), - _ => match bytes.contains(&0).then(|| vectorcraft_engine::cmd::utf16_order_without_mark(bytes)).flatten() { - Some(le) => utf16(bytes, le), - None => String::from_utf8_lossy(bytes).into_owned(), - }, - } + vectorcraft_engine::cmd::graph_data_text(bytes) } -/// A cell's text: one line (tabs and line breaks become spaces), at most MAX_CELL characters. +/// A cell's text ([`vectorcraft_engine::cmd::graph_cell_text`]). fn clean(s: &str) -> String { - s.chars().map(|c| if matches!(c, '\t' | '\r' | '\n') { ' ' } else { c }).take(MAX_CELL).collect() + vectorcraft_engine::cmd::graph_cell_text(s) } fn cell(grid: &[Vec], r: usize, c: usize) -> String { diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 161e235c56..516757d163 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8271,7 +8271,12 @@ breakText Glyphs Glyfy @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel musí být {own} (režim dokumentu), grayscale nebo bitmap @msg colour groups can't go into colour groups skupiny barev nelze vkládat do skupin barev @msg colour, mode and spot apply to solid-colour swatches only colour, mode a spot platí jen pro položky vzorníku s plnou barvou -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sloupec {column}: `{cell}` je sloupec `%` pro soubory dat grafu, které se nečtou +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je zadán relativní cestou: zadejte `base` nebo absolutní cestu +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} řádek {line}, sloupec {column}: soubor dat grafu pro `{var}` nelze přečíst: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je větší než {MAX_GRAPH_DATA_FILE} bajtů +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` dává hodnotu grafu delší než {MAX_GRAPH_CSV} bajtů +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all řádek {line}, sloupec {column}: soubory dat grafu obsahují celkem více než {MAX_GRAPH_FILES_TOTAL} bajtů +@msg `base` is empty `base` je prázdné @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sloupec {column}: `{cell}` uvádí `{name}`, což je proměnná typu {_1} @msg column {column}: `{cell}` names no variable sloupec {column}: `{cell}` neuvádí žádnou proměnnou @msg column {column}: the variable name is longer than {MAX_NAME} characters sloupec {column}: název proměnné je delší než {MAX_NAME} znaků diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a5f32a5d9..007a7f7a10 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7956,7 +7956,12 @@ breakText Glyphs Glyphen @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel muss {own} (der Modus des Dokuments), grayscale oder bitmap sein @msg colour groups can't go into colour groups Farbgruppen können nicht in Farbgruppen eingefügt werden @msg colour, mode and spot apply to solid-colour swatches only colour, mode und spot gelten nur für Vollfarbfelder -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read Spalte {column}: `{cell}` ist eine `%`-Spalte von Diagrammdatendateien, die nicht gelesen werden +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist ein relativer Pfad: Geben Sie `base` oder einen absoluten Pfad an +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} Zeile {line}, Spalte {column}: die Diagrammdatendatei für `{var}` kann nicht gelesen werden: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist größer als {MAX_GRAPH_DATA_FILE} Byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ergibt einen Diagrammwert, der länger als {MAX_GRAPH_CSV} Byte ist +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all Zeile {line}, Spalte {column}: die Diagrammdatendateien enthalten insgesamt mehr als {MAX_GRAPH_FILES_TOTAL} Byte +@msg `base` is empty `base` ist leer @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable Spalte {column}: `{cell}` nennt `{name}`, eine Variable vom Typ {_1} @msg column {column}: `{cell}` names no variable Spalte {column}: `{cell}` nennt keine Variable @msg column {column}: the variable name is longer than {MAX_NAME} characters Spalte {column}: Der Variablenname ist länger als {MAX_NAME} Zeichen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2762d2a954..e42715fb58 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8132,7 +8132,12 @@ breakText Glyphs Glyphes @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel doit valoir {own} (le mode du document), grayscale ou bitmap @msg colour groups can't go into colour groups un groupe de couleurs ne peut pas aller dans un groupe de couleurs @msg colour, mode and spot apply to solid-colour swatches only couleur, mode et ton direct s’appliquent uniquement aux nuances de couleur unie -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read colonne {column} : `{cell}` est une colonne `%` des fichiers de données de graphe, qui ne sont pas lus +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` est un chemin relatif : indiquez `base` ou un chemin absolu +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} ligne {line}, colonne {column} : impossible de lire le fichier de données de graphe pour `{var}` : {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` dépasse {MAX_GRAPH_DATA_FILE} octets +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` donne une valeur de graphe de plus de {MAX_GRAPH_CSV} octets +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all ligne {line}, colonne {column} : les fichiers de données de graphe contiennent plus de {MAX_GRAPH_FILES_TOTAL} octets au total +@msg `base` is empty `base` est vide @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable colonne {column} : `{cell}` désigne `{name}`, qui est une variable {_1} @msg column {column}: `{cell}` names no variable colonne {column} : `{cell}` ne désigne aucune variable @msg column {column}: the variable name is longer than {MAX_NAME} characters colonne {column} : le nom de variable dépasse {MAX_NAME} caractères diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 548f961f51..670c356710 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6587,7 +6587,12 @@ antiAlias Sharp शार्प @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: अधिकतम {MAX_TABLE} रंग @msg colour groups can't go into colour groups रंग समूह रंग समूहों में नहीं जा सकते हैं @msg colour, mode and spot apply to solid-colour swatches only रंग, मोड और स्पॉट केवल ठोस रंग वाले स्वॉच पर लागू होते हैं -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read कॉलम {column}: `{cell}` ग्राफ़ डेटा फ़ाइल का `%` कॉलम है, जिसे पढ़ा नहीं जाता +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` एक सापेक्ष पाथ है: `base` या एक पूर्ण पाथ दें +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल पढ़ी नहीं जा सकती: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` {MAX_GRAPH_DATA_FILE} बाइट्स से बड़ी है +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` से मिलने वाला ग्राफ़ मूल्य {MAX_GRAPH_CSV} बाइट्स से अधिक है +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all लाइन {line}, कॉलम {column}: ग्राफ़ डेटा फ़ाइलों में कुल मिलाकर {MAX_GRAPH_FILES_TOTAL} बाइट्स से अधिक हैं +@msg `base` is empty `base` खाली है @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable कॉलम {column}: `{cell}` में `{name}` नाम का {_1} वेरिएबल है @msg column {column}: `{cell}` names no variable कॉलम {column}: `{cell}` किसी वेरिएबल का नाम नहीं है @msg column {column}: the variable name is longer than {MAX_NAME} characters कॉलम {column}: वेरिएबल का नाम {MAX_NAME} कैरेक्टर से लंबा है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 200b45d1b1..6873c4ffb2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8141,7 +8141,12 @@ breakText Glyphs Glifák @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel: {own} (a dokumentum módja), grayscale vagy bitmap kell @msg colour groups can't go into colour groups színcsoport nem kerülhet színcsoportba @msg colour, mode and spot apply to solid-colour swatches only colour, mode és spot: csak egyszínű színmintákra vonatkozik -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read {column}. oszlop: `{cell}` a diagramadat-fájlok `%` oszlopa, ezek beolvasása nem történik meg +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja relatív elérési út: adja meg a `base` értéket vagy egy abszolút elérési utat +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}. sor, {column}. oszlop: a(z) `{var}` diagramadat-fájlja nem olvasható: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja nagyobb {MAX_GRAPH_DATA_FILE} bájtnál +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja {MAX_GRAPH_CSV} bájtnál hosszabb diagramértéket ad +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}. sor, {column}. oszlop: a diagramadat-fájlok összesen több mint {MAX_GRAPH_FILES_TOTAL} bájtot tartalmaznak +@msg `base` is empty a `base` üres @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable {column}. oszlop: `{cell}` ezt nevezi meg: `{name}`, amely {_1} típusú változó @msg column {column}: `{cell}` names no variable {column}. oszlop: `{cell}` nem nevez meg változót @msg column {column}: the variable name is longer than {MAX_NAME} characters {column}. oszlop: a változó neve hosszabb {MAX_NAME} karakternél diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 90ec79404c..0f92f38878 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8004,7 +8004,12 @@ breakText Glyphs Glifi @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel deve essere {own} (il metodo del documento), grayscale o bitmap @msg colour groups can't go into colour groups i gruppi di colori non possono entrare in altri gruppi di colori @msg colour, mode and spot apply to solid-colour swatches only colore, metodo e spot si applicano solo ai campioni di colore pieno -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read colonna {column}: `{cell}` è una colonna `%` dei file di dati dei grafici, che non vengono letti +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` è un percorso relativo: indica `base` o un percorso assoluto +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} riga {line}, colonna {column}: impossibile leggere il file di dati del grafico per `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` supera i {MAX_GRAPH_DATA_FILE} byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` dà un valore di grafico che supera i {MAX_GRAPH_CSV} byte +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all riga {line}, colonna {column}: i file di dati dei grafici contengono in tutto più di {MAX_GRAPH_FILES_TOTAL} byte +@msg `base` is empty `base` è vuoto @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable colonna {column}: `{cell}` indica `{name}`, che è una variabile {_1} @msg column {column}: `{cell}` names no variable colonna {column}: `{cell}` non indica alcuna variabile @msg column {column}: the variable name is longer than {MAX_NAME} characters colonna {column}: il nome della variabile supera {MAX_NAME} caratteri diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d98acfa22d..8bf1a33a52 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7205,7 +7205,12 @@ axis Y Axis Y 軸 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel には {own} (ドキュメントのモード)、grayscale、bitmap のいずれかを指定してください @msg colour groups can't go into colour groups カラーグループをカラーグループに入れることはできません @msg colour, mode and spot apply to solid-colour swatches only colour、mode、spot を適用できるのは単色のスウォッチだけです -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 列 {column}: `{cell}` はグラフデータファイルの `%` 列で、読み込まれません +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` は相対パスです: `base` か絶対パスを指定してください +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line} 行目、列 {column}: `{var}` のグラフデータファイルを読み込めません: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` が {MAX_GRAPH_DATA_FILE} バイトを超えています +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` から得られるグラフの値が {MAX_GRAPH_CSV} バイトを超えています +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line} 行目、列 {column}: グラフデータファイルが合計で {MAX_GRAPH_FILES_TOTAL} バイトを超えています +@msg `base` is empty `base` が空です @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 列 {column}: `{cell}` が指定している `{name}` は {_1} 変数です @msg column {column}: `{cell}` names no variable 列 {column}: `{cell}` に該当する変数はありません @msg column {column}: the variable name is longer than {MAX_NAME} characters 列 {column}: 変数名が {MAX_NAME} 文字を超えています diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bb8676df71..4fcdff6e06 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7867,7 +7867,12 @@ breakText Glyphs 글리프 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel은 {own}(문서의 모드), grayscale 또는 bitmap이어야 합니다 @msg colour groups can't go into colour groups 색상 그룹은 색상 그룹 안에 넣을 수 없습니다 @msg colour, mode and spot apply to solid-colour swatches only colour, mode, spot은 단색 견본에만 적용됩니다 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read {column}열: `{cell}`은(는) 그래프 데이터 파일의 `%` 열이며, 이 열은 읽지 않습니다 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`은(는) 상대 경로입니다. `base` 또는 절대 경로를 지정하세요 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}행, {column}열: `{var}`의 그래프 데이터 파일을 읽을 수 없습니다: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`이(가) {MAX_GRAPH_DATA_FILE}바이트보다 큽니다 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`에서 나온 그래프 값이 {MAX_GRAPH_CSV}바이트보다 깁니다 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}행, {column}열: 그래프 데이터 파일이 모두 합쳐 {MAX_GRAPH_FILES_TOTAL}바이트를 넘습니다 +@msg `base` is empty `base`가 비어 있습니다 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable {column}열: `{cell}`이(가) 가리키는 `{name}`은(는) {_1} 변수입니다 @msg column {column}: `{cell}` names no variable {column}열: `{cell}`이(가) 가리키는 변수가 없습니다 @msg column {column}: the variable name is longer than {MAX_NAME} characters {column}열: 변수 이름이 {MAX_NAME}자보다 깁니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a597a03fd0..8d1ff71086 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6206,7 +6206,12 @@ imageTrace Outline Contour @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel moet {own} (de modus van het document), grayscale of bitmap zijn @msg colour groups can't go into colour groups kleurgroepen kunnen niet in kleurgroepen worden geplaatst @msg colour, mode and spot apply to solid-colour swatches only colour, mode en spot gelden alleen voor stalen met een effen kleur -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolom {column}: `{cell}` is een `%`-kolom van grafiekgegevensbestanden, die niet worden gelezen +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is een relatief pad: geef `base` of een absoluut pad op +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} regel {line}, kolom {column}: het grafiekgegevensbestand voor `{var}` kan niet worden gelezen: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is groter dan {MAX_GRAPH_DATA_FILE} bytes +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` geeft een grafiekwaarde langer dan {MAX_GRAPH_CSV} bytes +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all regel {line}, kolom {column}: de grafiekgegevensbestanden bevatten samen meer dan {MAX_GRAPH_FILES_TOTAL} bytes +@msg `base` is empty `base` is leeg @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolom {column}: `{cell}` noemt `{name}`, en dat is een variabele van het type {_1} @msg column {column}: `{cell}` names no variable kolom {column}: `{cell}` noemt geen variabele @msg column {column}: the variable name is longer than {MAX_NAME} characters kolom {column}: de naam van de variabele is langer dan {MAX_NAME} tekens diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 99ee2080b8..b13aa895f1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8243,7 +8243,12 @@ breakText Glyphs Glify @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel musi mieć wartość {own} (tryb dokumentu), grayscale lub bitmap @msg colour groups can't go into colour groups grup kolorów nie można umieszczać w grupach kolorów @msg colour, mode and spot apply to solid-colour swatches only color, mode i spot dotyczą tylko próbek kolorów jednolitych -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolumna {column}: `{cell}` to kolumna `%` plików danych wykresu, które nie są odczytywane +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` ma ścieżkę względną: podaj `base` albo ścieżkę bezwzględną +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} wiersz {line}, kolumna {column}: nie można odczytać pliku danych wykresu dla `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` jest większy niż {MAX_GRAPH_DATA_FILE} bajtów +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` daje wartość wykresu dłuższą niż {MAX_GRAPH_CSV} bajtów +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all wiersz {line}, kolumna {column}: pliki danych wykresu zawierają łącznie ponad {MAX_GRAPH_FILES_TOTAL} bajtów +@msg `base` is empty `base` jest puste @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolumna {column}: `{cell}` wskazuje `{name}`, czyli zmienną typu {_1} @msg column {column}: `{cell}` names no variable kolumna {column}: `{cell}` nie wskazuje żadnej zmiennej @msg column {column}: the variable name is longer than {MAX_NAME} characters kolumna {column}: nazwa zmiennej ma więcej niż {MAX_NAME} znaków diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 677c8e460f..abaeda7401 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8335,7 +8335,12 @@ swatch Yellow Green Verde-amarelado @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel deve ser {own} (o modo do documento), grayscale ou bitmap @msg colour groups can't go into colour groups grupos de cores não podem ficar dentro de grupos de cores @msg colour, mode and spot apply to solid-colour swatches only colour, mode e spot se aplicam somente a amostras de cor sólida -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read coluna {column}: `{cell}` é uma coluna `%` de arquivos de dados de gráfico, que não são lidos +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` é um caminho relativo: informe `base` ou um caminho absoluto +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} linha {line}, coluna {column}: não é possível ler o arquivo de dados de gráfico de `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` tem mais de {MAX_GRAPH_DATA_FILE} bytes +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` gera um valor de gráfico com mais de {MAX_GRAPH_CSV} bytes +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all linha {line}, coluna {column}: os arquivos de dados de gráfico têm mais de {MAX_GRAPH_FILES_TOTAL} bytes no total +@msg `base` is empty `base` está vazio @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable coluna {column}: `{cell}` indica `{name}`, que é uma variável de {_1} @msg column {column}: `{cell}` names no variable coluna {column}: `{cell}` não indica nenhuma variável @msg column {column}: the variable name is longer than {MAX_NAME} characters coluna {column}: o nome da variável tem mais de {MAX_NAME} caracteres diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cc854aa362..7c9466d97e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7903,7 +7903,12 @@ digits Hindi Hindi @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel måste vara {own} (dokumentets läge), grayscale eller bitmap @msg colour groups can't go into colour groups färggrupper kan inte läggas i färggrupper @msg colour, mode and spot apply to solid-colour swatches only färg, läge och dekor gäller endast enfärgade färgrutor -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read kolumn {column}: `{cell}` är en `%`-kolumn i diagramdatafiler, som inte läses +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är en relativ sökväg: ange `base` eller en absolut sökväg +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} rad {line}, kolumn {column}: diagramdatafilen för `{var}` kan inte läsas: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är större än {MAX_GRAPH_DATA_FILE} byte +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` ger ett diagramvärde som är längre än {MAX_GRAPH_CSV} byte +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all rad {line}, kolumn {column}: diagramdatafilerna innehåller sammanlagt mer än {MAX_GRAPH_FILES_TOTAL} byte +@msg `base` is empty `base` är tom @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable kolumn {column}: `{cell}` anger `{name}`, som är en {_1}-variabel @msg column {column}: `{cell}` names no variable kolumn {column}: `{cell}` anger ingen variabel @msg column {column}: the variable name is longer than {MAX_NAME} characters kolumn {column}: variabelnamnet är längre än {MAX_NAME} tecken diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2888a30f0..86111722ee 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7590,7 +7590,12 @@ axis Y Axis Y ekseni @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel {own} (belgenin modu), grayscale veya bitmap olmalıdır @msg colour groups can't go into colour groups renk grupları renk gruplarının içine konulamaz @msg colour, mode and spot apply to solid-colour swatches only colour, mode ve spot yalnızca düz renkli renk örnekleri için geçerlidir -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read sütun {column}: `{cell}`, grafik veri dosyalarının bir `%` sütunudur ve bu dosyalar okunmaz +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası göreli bir yoldur: `base` ya da mutlak bir yol verin +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} satır {line}, sütun {column}: `{var}` için grafik veri dosyası okunamıyor: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_DATA_FILE} bayttan büyük +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_CSV} bayttan uzun bir grafik değeri veriyor +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all satır {line}, sütun {column}: grafik veri dosyaları toplamda {MAX_GRAPH_FILES_TOTAL} bayttan fazla +@msg `base` is empty `base` boş @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable sütun {column}: `{cell}`, {_1} türünde bir değişken olan `{name}` değişkenini belirtiyor @msg column {column}: `{cell}` names no variable sütun {column}: `{cell}` hiçbir değişkeni belirtmiyor @msg column {column}: the variable name is longer than {MAX_NAME} characters sütun {column}: değişken adı {MAX_NAME} karakterden uzun diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 411b2c3baf..cf1aa8cef5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7869,7 +7869,12 @@ breakText Glyphs Гліфи @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel має бути {own} (режим документа), grayscale або bitmap @msg colour groups can't go into colour groups групи кольорів не можна поміщати в групи кольорів @msg colour, mode and spot apply to solid-colour swatches only colour, mode і spot застосовуються лише до зразків суцільного кольору -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read стовпець {column}: `{cell}` — це стовпець `%` файлів даних діаграм, які не читаються +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` задано відносним шляхом: укажіть `base` або абсолютний шлях +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} рядок {line}, стовпець {column}: не вдається прочитати файл даних діаграми для `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` більший за {MAX_GRAPH_DATA_FILE} байтів +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` дає значення діаграми довше за {MAX_GRAPH_CSV} байтів +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all рядок {line}, стовпець {column}: файли даних діаграм разом містять понад {MAX_GRAPH_FILES_TOTAL} байтів +@msg `base` is empty `base` порожнє @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable стовпець {column}: `{cell}` указує `{name}`, а це змінна типу {_1} @msg column {column}: `{cell}` names no variable стовпець {column}: `{cell}` не вказує жодної змінної @msg column {column}: the variable name is longer than {MAX_NAME} characters стовпець {column}: ім’я змінної довше за {MAX_NAME} символів diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3fe2f9e009..f3875a12c5 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8229,7 +8229,12 @@ breakText Glyphs 字形 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel 必须是 {own} (文档的模式)、grayscale 或 bitmap @msg colour groups can't go into colour groups 颜色组不能放入颜色组 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只适用于纯色色板 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 第 {column} 列:`{cell}` 是图表数据文件的 `%` 列,不会读取 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 是相对路径:请提供 `base` 或绝对路径 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 列:无法读取 `{var}` 的图表数据文件:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 超过 {MAX_GRAPH_DATA_FILE} 字节 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 得到的图表值超过 {MAX_GRAPH_CSV} 字节 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 列:图表数据文件总计超过 {MAX_GRAPH_FILES_TOTAL} 字节 +@msg `base` is empty `base` 为空 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 第 {column} 列:`{cell}` 指定了 `{name}`,而它是 {_1} 变量 @msg column {column}: `{cell}` names no variable 第 {column} 列:`{cell}` 没有对应的变量 @msg column {column}: the variable name is longer than {MAX_NAME} characters 第 {column} 列:变量名称超过 {MAX_NAME} 个字符 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab7f9d9dd2..6d10ceced1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8157,7 +8157,12 @@ breakText Glyphs 字符 @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel 必須是 {own} (文件的模式)、grayscale 或 bitmap @msg colour groups can't go into colour groups 顏色群組不能放入顏色群組 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只適用於純色色票 -@msg column {column}: `{cell}` is a `%` column of graph data files, which are not read 第 {column} 欄:`{cell}` 是圖表資料檔案的 `%` 欄,不會讀取 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 是相對路徑:請提供 `base` 或絕對路徑 +@msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 欄:無法讀取 `{var}` 的圖表資料檔案:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 超過 {MAX_GRAPH_DATA_FILE} 位元組 +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 得到的圖表值超過 {MAX_GRAPH_CSV} 位元組 +@msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 欄:圖表資料檔案合計超過 {MAX_GRAPH_FILES_TOTAL} 位元組 +@msg `base` is empty `base` 為空 @msg column {column}: `{cell}` names `{name}`, which is a {_1} variable 第 {column} 欄:`{cell}` 指定了 `{name}`,而它是 {_1} 變數 @msg column {column}: `{cell}` names no variable 第 {column} 欄:`{cell}` 未指定任何變數 @msg column {column}: the variable name is longer than {MAX_NAME} characters 第 {column} 欄:變數名稱超過 {MAX_NAME} 個字元 diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 3ab5fc2484..f5ca49b025 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -528,6 +528,8 @@ mod tests { assert_eq!(app.ui.status, "a new document won't read these variables back with their kind: `#Tag`"); let warning = app.ui.status.clone(); app.run("variable.define", json!({"name": "%Rate", "kind": "text"})).unwrap(); + // A new document reads a `%` header's values as paths of graph data files. + app.run("dataset.new", json!({"name": "Rates", "values": {"%Rate": "5"}})).unwrap(); app.run("dataset.export", json!({"path": path})).unwrap(); assert_eq!(app.ui.status, "a new document refuses this file because of these variables: `%Rate`"); let refuses = app.ui.status.clone(); diff --git a/docs/mcp.md b/docs/mcp.md index 1288fe7fff..e5da18d198 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3329,7 +3329,7 @@ already walks Image Trace. Short agent entry points: - Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / - `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv}` / + `dataset.prev` (each `dataset.select` / next / prev is one undo step over every bound object), `dataset.import {path|data|dataBase64|csv, base?}` / `dataset.export {path?}` (CSV: one column per variable, and no column of data set names). `dataset.import` also reads tab-separated files. Every header cell is a variable, whatever its case (`name` and `Name` included). The first row holds the field names, as the @@ -3337,16 +3337,29 @@ already walks Image Trace. Short agent entry points: describes. The rows replace every data set of the document and are named `Data Set 1`, `Data Set 2` and so on, in file order; the document's variables and their bindings stay, and the reply's `deletedDataSets` lists the data sets that were replaced. An import error about a row's values gives the file line the row starts on. A header cell that names no variable defines one, unbound, in the same undo step as the - rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, and a cell without - a prefix defines a text variable. `dataset.export` writes a visibility variable's header as `#Shown` and an image - variable's as `@Photo`, and a text or graph variable's as its name alone. Its reply's `warning` names the variables - whose header or values make an import into a document without them refuse the file (a `%` header, a `#` header - whose values aren't true or false). Otherwise it names the variables that such an import does not read back with - their kind: text variables whose names start with `#` or `@`, and graph variables. Export is refused, naming both variables, when a variable's header is - another variable's name (a visibility variable `Show` next to a text variable `#Show`). A prefixed cell whose name - is already a variable of the prefix's kind names it; - one whose name is a variable of another kind fails the import. A `%` cell that isn't a variable's exact name (graph - data files) is refused, and so are two cells that name one variable (`City` twice, or `Shown` and `#Shown`). The + rows. `#Shown` defines a visibility variable `Shown`, `@Photo` defines an image variable `Photo`, `%Sales` defines a + graph variable `Sales`, and a cell without a prefix defines a text variable. The cells of a `%` column are paths of + graph data files, as the set-up page's example shows. Each file is read as the Graph Data window's Import Data reads + one ([add graph data](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/add-graph-data.html)): + at most 1 MB; tab-separated when any line holds a tab, else comma-separated; the first row holds the series labels + and the first column the category labels; UTF-16 by the rule below, else UTF-8. The data becomes the data set's + graph value, which `dataset.select` applies as `graph.setData` applies it, so the graph gets the data that Import + Data and Apply give it. A relative path is taken from `dataset.import`'s `base` folder, else from the folder of the + CSV file at `path`; with neither (`csv`, `data` or `dataBase64` and no `base`), it fails the import. This is + VectorCraft's own rule. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value + longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all fail the import with + the line and the column, and the document is left as it was. Each file is read once per import, however many cells + name it, and counts once toward the 256 MB; each cell's graph value counts every time. `dataset.export` writes a + visibility variable's header as `#Shown` and an image variable's as `@Photo`, and a text or graph variable's as its + name alone. Its reply's `warning` names the variables whose header or values make an import into a document without + them refuse the file (a `%` header over values, which such an import reads as file paths, and a `#` header whose + values aren't true or false). Otherwise it names the variables that such an import does not read back with their + kind: variables whose names start with `#`, `@` or `%` and aren't of that prefix's kind, and graph variables. Export + is refused, naming both variables, when a variable's header is another variable's name (a visibility variable + `Show` next to a text variable `#Show`). A prefixed cell whose name is already a variable of the prefix's kind names + it; one whose name is a variable of another kind fails the import, and so do two cells that name one variable + (`City` twice, or `Shown` and `#Shown`). A cell that is a variable's exact name, prefix included, names that + variable, so the cells under a graph variable named `%Sales` are read as graph data in CSV form. The reply's `defined` lists the variables the import defined. While the variables are locked, an import whose header would define a variable fails with "variables are locked". A `dataset.import` file that isn't UTF-8 is read as Windows-1252, unless it starts with the UTF-8 byte-order mark. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5980ecb89c..ba0b9b8f32 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -822,6 +822,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Import Data Sets… (`dataset.import`) reads a UTF-16 file without a byte-order mark, instead of refusing it, when at least half of its two-byte units hold a NUL byte; it uses the byte order that reads its line breaks. - Graphs: the Graph Data window's Import Data reads a UTF-16 text file without a byte-order mark by the same rule as Import Data Sets…, instead of filling the cells with NUL characters. It reads a file cut short by one byte, or with an unpaired surrogate, as it reads one after a byte-order mark. - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. + - Variables: Import Data Sets… (`dataset.import`) reads `%` columns instead of refusing them: `%Sales` defines or names the graph variable `Sales`, and each cell is the path of a graph data file, read as the Graph Data window's Import Data reads one and kept as the data set's graph value. A relative path is taken from the CSV file's folder, or from `base`. A missing, unreadable or larger than 1 MB file fails the import with its line and column, and the document is left as it was (`crates/engine/src/tests/variables.rs`). - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values. - JSON-lines control channel with real egui pointer and keyboard injection. From 0cb620a43636c863e6fda49bd5c4295d0fae4cc9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 22:07:49 -0800 Subject: [PATCH 055/138] Document Info: Document lists the transparency settings and the Artboard tool's selected artboards The Document category now lists File > Document Setup's transparency settings after Raster Effects: Grid Size, Grid Colors (a preset's name, or two custom colors by their values), Simulate Colored Paper and Flattener Preset. While the Artboard tool is the current tool, it also lists each artboard that tool has selected, with its width, height and the X and Y of its top-left corner from the ruler origin of the tool's active artboard. The panel refreshes when the tool's selection changes. document.info gives the same facts as document.transparency and document.selectedArtboards. The panel shows the values in the interface language; the new labels have rows in every catalog, and the Orange and Purple grid color presets get rows in the catalogs that lacked them. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/docinfo.rs | 184 +++++++++++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/gu.tsv | 7 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tests.rs | 22 ++- crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/panels/doc_info.rs | 100 +++++++++++++- docs/mcp.md | 9 +- docs/target-app-parity.md | 1 + 33 files changed, 460 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index b5ac1c13e5..c299d5c4ba 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds", has_doc, info ), @@ -178,14 +178,58 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S (entry, (name, format!("{}, {detail}", kind.label()))) } +/// The artboards the Artboard tool has selected while it is the current tool, in artboard order, +/// with the index of its active artboard; none with another tool or when it has none of the +/// document's artboards selected. Indices the document does not have are left out. +fn artboard_tool_selection(s: &Session) -> Option<(Vec, usize)> { + if s.tool_id() != "artboard" { + return None; + } + let n = s.active().map_or(0, |d| d.doc.artboards.len()); + let t = s.tool_options_of("artboard"); + let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n); + let mut picked: Vec = t["selected"].as_array().into_iter().flatten().filter_map(index).collect(); + picked.sort_unstable(); + picked.dedup(); + let first = *picked.first()?; + let active = index(&t["active"]).filter(|a| picked.contains(a)).unwrap_or(first); + Some((picked, active)) +} + +/// The artboards `picked` as Document Info › Document lists them while the Artboard tool is the +/// current tool: their `selectedArtboards` entries (in the document's units), and for each its +/// rows: its name, width, height and the X and Y of its top-left corner from the ruler origin of +/// artboard `active`. +fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec, Vec<(String, String)>) { + let (u, per) = (d.units, d.units.points()); + let origin = d.ruler_origin_for(active); + let mut entries = vec![]; + let mut rows = vec![]; + for &i in picked { + let Some(a) = d.artboards.get(i) else { continue }; + let (w, h, x, y) = (a.rect.width(), a.rect.height(), a.rect.x0 - origin.x, a.rect.y0 - origin.y); + entries.push(json!({ "index": i, "name": a.name, "width": w / per, "height": h / per, "x": x / per, "y": y / per })); + rows.extend([ + ("Artboard".to_string(), a.name.clone()), + ("Width".into(), u.format(w)), + ("Height".into(), u.format(h)), + ("X".into(), u.format(x)), + ("Y".into(), u.format(y)), + ]); + } + (entries, rows) +} + /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `document.info` reports), its fonts and their Font Details rows, its image objects, the rows of -/// the brushes its art uses, the rows of its Repeat objects and the rows of its objects filled or -/// stroked with a spot color, with a pattern and with a gradient. +/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts +/// and their Font Details rows, its image objects, the rows of the brushes its art uses, the rows +/// of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a +/// pattern and with a gradient. #[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, + selected_artboards: &[(String, String)], fonts: &BTreeSet, font_details: &[(String, String)], images: &[ImageRow], @@ -215,7 +259,19 @@ fn sections( rows.extend( d.artboards.iter().map(|a| (a.name.clone(), format!("{} × {}", u.format(a.rect.width()), u.format(a.rect.height())))), ); + rows.extend(selected_artboards.iter().cloned()); rows.push(("Raster Effects".into(), format!("{} ppi", d.raster_effects_ppi))); + let setup = &d.setup; + let colors = match setup.grid_colors_name() { + "Custom" => setup.grid_colors.map(|c| c.to_hex()).join(", "), + name => name.to_string(), + }; + rows.extend([ + ("Grid Size".to_string(), setup.grid_size.label().to_string()), + ("Grid Colors".into(), colors), + ("Simulate Colored Paper".into(), if setup.simulate_paper { "On" } else { "Off" }.into()), + ("Flattener Preset".into(), setup.flattener().to_string()), + ]); let counts = [ ("Swatches", "swatches"), ("Character Styles", "characterStyles"), @@ -556,6 +612,7 @@ fn info(s: &mut Session, p: &Value) -> Result { Some("text") => true, Some(f) => return Err(bad(C, format!("format `{f}`: text or json"))), }; + let artboard_tool = artboard_tool_selection(s); let st = s.doc()?; let d = &st.doc; let selection_only = bool_or(p, "selectionOnly", false); @@ -787,7 +844,22 @@ fn info(s: &mut Session, p: &Value) -> Result { }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &font_rows, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category); + let (selected_entries, selected_rows) = artboard_tool.map(|(picked, active)| selected_artboard_rows(d, &picked, active)).unwrap_or_default(); + out["document"]["selectedArtboards"] = json!(selected_entries); + let sections = sections( + d, + &out, + &selected_rows, + &fonts, + &font_rows, + &image_rows, + &brush_rows, + &repeat_rows, + &spot_rows, + &pattern_rows, + &gradient_rows, + category, + ); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -804,6 +876,13 @@ fn document_summary(d: &Document) -> Value { "unitId": d.units.key(), "artboards": d.artboards.iter().map(|a| json!({ "name": a.name, "width": a.rect.width() / u, "height": a.rect.height() / u })).collect::>(), "rasterEffectsPpi": d.raster_effects_ppi, + "transparency": { + "gridSize": d.setup.grid_size.id(), + "gridColors": d.setup.grid_colors.map(|c| c.to_hex()), + "gridColorsName": d.setup.grid_colors_name(), + "simulatePaper": d.setup.simulate_paper, + "flattenerPreset": d.setup.flattener(), + }, }) } @@ -877,6 +956,101 @@ mod tests { assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1); } + /// The Document category's rows from `info`, as (label, value) pairs. + fn document_rows(i: &Value) -> Vec<(String, String)> { + let doc = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == "document").unwrap(); + doc["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().to_string(), r[1].as_str().unwrap().to_string())).collect() + } + + /// Document lists File › Document Setup's transparency settings: the grid's size and colors + /// (a preset's name, else both colors), Simulate Colored Paper and the flattener preset. + #[test] + fn info_lists_the_transparency_settings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + let t = &i["document"]["transparency"]; + assert_eq!( + (t["gridSize"].clone(), t["gridColorsName"].clone(), t["simulatePaper"].clone(), t["flattenerPreset"].clone()), + (json!("medium"), json!("Light"), json!(false), json!("Medium Resolution")) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Raster Effects").unwrap(); + let expected = + [("Grid Size", "Medium"), ("Grid Colors", "Light"), ("Simulate Colored Paper", "Off"), ("Flattener Preset", "Medium Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + s.execute( + "document.setup", + &json!({"gridSize": "large", "gridColors": ["#ff0000", "#00ff00"], "simulatePaper": true, "flattenerPreset": "High Resolution"}), + ) + .unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["transparency"]["gridColors"], json!(["#ff0000", "#00ff00"])); + assert_eq!(i["document"]["transparency"]["gridColorsName"], "Custom"); + let rows = document_rows(&i); + let expected = + [("Grid Size", "Large"), ("Grid Colors", "#ff0000, #00ff00"), ("Simulate Colored Paper", "On"), ("Flattener Preset", "High Resolution")]; + assert_eq!(rows[at + 1..at + 5], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + let report = s.execute("document.info", &json!({"category": "document", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("Grid Colors: #ff0000, #00ff00\nSimulate Colored Paper: On\nFlattener Preset: High Resolution\n"), "{report}"); + } + + /// While the Artboard tool is the current tool, Document lists each artboard it has selected + /// after the artboards: its name, width, height and the X and Y of its top-left corner from the + /// ruler origin of the tool's active artboard. With another tool it lists none. + #[test] + fn info_lists_the_artboards_the_artboard_tool_selected() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 2, "name": "Back"})).unwrap(); + let before = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(before["document"]["selectedArtboards"], json!([])); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([2, 1, 7])); + let i = s.execute("document.info", &json!({})).unwrap(); + // Artboard 2 is active: positions are measured from its top-left corner. + assert_eq!( + i["document"]["selectedArtboards"], + json!([ + {"index": 1, "name": "Artboard 2", "width": 60.0, "height": 80.0, "x": -250.0, "y": 30.0}, + {"index": 2, "name": "Back", "width": 100.0, "height": 50.0, "x": 0.0, "y": 0.0}, + ]) + ); + let rows = document_rows(&i); + let at = rows.iter().position(|(l, _)| l == "Artboards").unwrap() + 4; + let expected = [ + ("Artboard", "Artboard 2"), + ("Width", "60 pt"), + ("Height", "80 pt"), + ("X", "-250 pt"), + ("Y", "30 pt"), + ("Artboard", "Back"), + ("Width", "100 pt"), + ("Height", "50 pt"), + ("X", "0 pt"), + ("Y", "0 pt"), + ("Raster Effects", "72 ppi"), + ]; + assert_eq!(rows[at..at + 11], expected.map(|(l, v)| (l.to_string(), v.to_string())), "{rows:?}"); + // The rows follow the document's units and its ruler origin. + s.execute("document.setup", &json!({"units": "Millimeters"})).unwrap(); + s.execute("document.setRulerOrigin", &json!({"x": 390, "y": 0, "artboard": 2})).unwrap(); + s.set_tool_option("selected", &json!([2])); + let i = s.execute("document.info", &json!({"category": "document"})).unwrap(); + let entry = &i["document"]["selectedArtboards"]; + assert_eq!((entry.as_array().unwrap().len(), entry[0]["index"].clone()), (1, json!(2))); + assert!((entry[0]["x"].as_f64().unwrap() - 10.0 * 25.4 / 72.0).abs() < 1e-9, "{entry}"); + let rows = document_rows(&i); + assert!(rows.contains(&("X".into(), "3.5278 mm".into())) && rows.contains(&("Y".into(), "3.5278 mm".into())), "{rows:?}"); + // Another tool: no artboard rows. + s.select_tool("selection", crate::tooling::ViewInfo::default()).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!(i["document"]["selectedArtboards"], json!([])); + assert!(!document_rows(&i).iter().any(|(l, _)| l == "X"), "{:?}", document_rows(&i)); + } + /// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a /// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 948b295e17..d5e385ab66 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3443,6 +3443,11 @@ digits Malayalam Малаялам Opacity Masks Маски за непрозрачност Objects with Effects Обекти с ефекти Path Length Дължина на пътя + Grid Size Размер на мрежата + Grid Colors Цветове на мрежата + Flattener Preset Предварителна настройка за сплескване + X X + Y Y Spot Colors Спот цветове Spot Colors… Спот цветове… Spread: Разпространение: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f8d6fa263b..031d8dee6e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3483,6 +3483,11 @@ theme Appearance Izgled Objects Objekti Paths Putanje Path Length Dužina putanje + Grid Size Veličina mreže + Grid Colors Boje mreže + Flattener Preset Predložak spljoštavanja + X X + Y Y Add Guide Dodaj vodilicu Edit Selection Uredi odabir Recall Selection Vrati odabir diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3ed3ca8331..cad94ee071 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3112,6 +3112,11 @@ digits Malayalam Malaiàlam Path Eraser Esborrador de traçats Path Eraser Tool Eina d’esborrador de traçats Path Length Longitud del traçat + Grid Size Mida de la quadrícula + Grid Colors Colors de la quadrícula + Flattener Preset Preajust de l’aplanador + X X + Y Y Path: Traçat: Pathfinder Cercador de traçats Pathfinder Options Opcions del cercador de traçats diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 161e235c56..2a1e905726 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3536,6 +3536,11 @@ theme Appearance Motiv Objects Objekty Paths Cesty Path Length Délka cest + Grid Size Velikost mřížky + Grid Colors Barvy mřížky + Flattener Preset Přednastavení sloučení + X X + Y Y Add Guide Přidat vodítko Edit Selection Upravit výběr Recall Selection Vyvolat výběr diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fd0b7c042e..c7cd7a7f1c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6259,6 +6259,11 @@ mark-style Japanese Japansk Edge Only Kun kant Overlay Edge Overlæg kant Path Length Stilængde + Grid Size Gitterstørrelse + Grid Colors Gitterfarver + Flattener Preset Forudindstilling til fladgøring + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer filens lag blev ikke læst ({_1}): den kommer ind som sin side, i ét lag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part filens lag blev ikke læst fra dens redigeringsdata ({_1}): de kommer fra dens PDF-del @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables ikke alle filens variabelbindinger blev læst (udeladte bindinger: {_1}): de objekter er ikke bundet til deres variabler diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a5f32a5d9..378042eea1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2488,6 +2488,13 @@ file-filter Templates Vorlagen Pathfinders: Pathfinder: Paths Pfade Path Length Pfadlänge + Grid Size Rastergröße + Grid Colors Rasterfarben + Flattener Preset Reduzierungsvorgabe + X X + Y Y + Orange Orange + Purple Lila Paths: {paths} Anchors: {anchors} Colors: {colors} Pfade: {paths} Ankerpunkte: {anchors} Farben: {colors} Pattern Muster Pattern Editing Musterbearbeitung diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b1b7b4d039..68b05865c4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4059,6 +4059,11 @@ digits Malayalam Μαλαγιάλαμ Opacity Masks Μάσκες αδιαφάνειας Objects with Effects Αντικείμενα με εφέ Path Length Μήκος διαδρομής + Grid Size Μέγεθος πλέγματος + Grid Colors Χρώματα πλέγματος + Flattener Preset Προεπιλογή ισοπέδωσης + X X + Y Y Spot Colors Πλακάτα χρώματα Spot Colors… Πλακάτα χρώματα… Stacked Bar Graph Tool Στοιβαγμένο ραβδόγραμμα (Stacked Bar Graph Tool) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b3c675f7b..94d50afbe8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2526,6 +2526,11 @@ font-technology Variable Variables Pathfinders: Buscatrazos: Paths Trazados Path Length Longitud de los trazados + Grid Size Tamaño de cuadrícula + Grid Colors Colores de cuadrícula + Flattener Preset Preajuste del acoplador + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Trazados: {paths} Anclas: {anchors} Colores: {colors} Pattern Motivo Pattern Editing Edición de motivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e77a617c52..8518e8e93b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6308,6 +6308,11 @@ mark-style Japanese Japanilainen Edge Only Vain reunat Overlay Edge Reunat päällä Path Length Polun pituus + Grid Size Ruudukon koko + Grid Colors Ruudukon värit + Flattener Preset Litistyksen esiasetus + X X + Y Y swatch [None] [Ei mitään] swatch [Registration] [Kohdistus] swatch White Valkoinen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2762d2a954..20fb6f19ec 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2518,6 +2518,11 @@ font-technology Variable Variables Pathfinders: Pathfinders : Paths Tracés Path Length Longueur des tracés + Grid Size Taille de la grille + Grid Colors Couleurs de la grille + Flattener Preset Paramètre prédéfini d’aplatissement + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Tracés : {paths} Points d’ancrage : {anchors} Couleurs : {colors} Pattern Motif Pattern Editing Modification du motif diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c96900b2b..d7a3b1629f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4711,3 +4711,10 @@ swatch [Registration] [રજિસ્ટ્રેશન] Repeat Objects પુનરાવર્તિત ઑબ્જેક્ટ્સ @msg `{path}` must be one of {_1}, not {got} `{path}` એ {_1}માંથી એક હોવું જોઈએ, {got} નહીં Path Length પાથની લંબાઈ + Grid Size ગ્રિડ સાઇઝ + Grid Colors ગ્રિડ રંગો + Flattener Preset ફ્લેટનર પ્રીસેટ + X X + Y Y + Orange નારંગી + Purple જાંબલી diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 548f961f51..4e607e2a1a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3399,6 +3399,11 @@ antiAlias Sharp शार्प Path Eraser पाथ इरेज़र Path Eraser Tool पाथ इरेज़र टूल Path Length पाथ की लंबाई + Grid Size ग्रिड साइज़ + Grid Colors ग्रिड रंग + Flattener Preset फ़्लैटनर प्रीसेट + X X + Y Y Path Only केवल पाथ Path Precision Tools पाथ परिशुद्धता टूल Path: पाथ: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 200b45d1b1..1075b47fbd 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3013,6 +3013,11 @@ file-filter Templates Sablonok Pathfinders: Útvonalkezelők: Paths Útvonalak Path Length Útvonalak hossza + Grid Size Rácsméret + Grid Colors Rács színei + Flattener Preset Lapítási előbeállítás + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Útvonalak: {paths} Horgonypontok: {anchors} Színek: {colors} Pattern Mintázat Pattern Brush Mintázatecset diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f3dcca3874..5485e6d985 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5649,6 +5649,11 @@ mark-style Japanese Jepang Edge Only Hanya tepi Overlay Edge Hamparkan tepi Path Length Panjang jalur + Grid Size Ukuran kisi + Grid Colors Warna kisi + Flattener Preset Preset flattener + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer lapisan file tidak terbaca ({_1}): file masuk sebagai halamannya, dalam satu lapisan @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part lapisan file tidak terbaca dari data pengeditannya ({_1}): lapisannya berasal dari bagian PDF file @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables tidak semua ikatan variabel file terbaca (ikatan yang dilewati: {_1}): objek-objek itu tidak terikat ke variabelnya diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 90ec79404c..274bd7bc81 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2564,6 +2564,13 @@ file-filter Templates Modelli Pathfinders: Elaborazioni tracciati: Paths Tracciati Path Length Lunghezza dei tracciati + Grid Size Dimensione griglia + Grid Colors Colori griglia + Flattener Preset Preset di appiattimento + X X + Y Y + Orange Arancione + Purple Viola Paths: {paths} Anchors: {anchors} Colors: {colors} Tracciati: {paths} Ancoraggi: {anchors} Colori: {colors} Pattern Motivo Pattern Editing Modifica motivo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d98acfa22d..da3f7ecc36 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2705,6 +2705,13 @@ antiAlias Sharp シャープ Pathfinders: パスファインダー: Paths パス Path Length パスの長さ + Grid Size グリッドのサイズ + Grid Colors グリッドのカラー + Flattener Preset 分割・統合プリセット + X X + Y Y + Orange オレンジ + Purple パープル Paths: {paths} Anchors: {anchors} Colors: {colors} パス:{paths} アンカー:{anchors} カラー:{colors} Pattern Editing パターン編集 Pattern options are available in pattern editing mode. パターンオプションはパターン編集モードで使用できます。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 794e5454a9..16a4780b92 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5801,6 +5801,11 @@ imageTrace Outline კონტური Hide Template შაბლონის დამალვა Show Template შაბლონის ჩვენება Path Length ტრაექტორიის სიგრძე + Grid Size ბადის ზომა + Grid Colors ბადის ფერები + Flattener Preset გაბრტყელების პრესეტი + X X + Y Y Filter ფილტრი Clear All ყველას გასუფთავება By Object ობიექტის მიხედვით diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bb8676df71..836ea2ece8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2695,6 +2695,13 @@ antiAlias Sharp 날카롭게 Pathfinders: 패스파인더: Paths 패스 Path Length 패스 길이 + Grid Size 격자 크기 + Grid Colors 격자 색상 + Flattener Preset 병합 프리셋 + X X + Y Y + Orange 주황 + Purple 보라 Paths: {paths} Anchors: {anchors} Colors: {colors} 패스: {paths} 앵커: {anchors} 색상: {colors} Pattern Editing 패턴 편집 Pattern options are available in pattern editing mode. 패턴 옵션은 패턴 편집 모드에서 사용할 수 있습니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a597a03fd0..7e82ffba6e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8048,6 +8048,11 @@ mark-style Japanese Japans Edge Only Alleen rand Overlay Edge Rand bedekken Path Length Padlengte + Grid Size Rastergrootte + Grid Colors Rasterkleuren + Flattener Preset Voorinstelling voor afvlakking + X X + Y Y @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer de lagen van het bestand zijn niet ingelezen ({_1}): het komt binnen als zijn pagina, in één laag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part de lagen van het bestand zijn niet ingelezen uit de bewerkingsgegevens ({_1}): ze komen uit het PDF-gedeelte @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables niet alle variabelekoppelingen van het bestand zijn ingelezen (overgeslagen koppelingen: {_1}): die objecten zijn niet aan hun variabelen gekoppeld diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 99ee2080b8..19994441c8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3415,6 +3415,13 @@ theme Appearance Wygląd Objects Obiekty Paths Ścieżki Path Length Długość ścieżek + Grid Size Rozmiar siatki + Grid Colors Kolory siatki + Flattener Preset Ustawienie spłaszczania + X X + Y Y + Orange Pomarańczowy + Purple Fioletowy Add Guide Dodaj linię pomocniczą Edit Selection Edytuj zaznaczenie Recall Selection Przywołaj zaznaczenie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 677c8e460f..9378f2b6bb 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7433,6 +7433,11 @@ swatch Orange Red Vermelho-alaranjado Overlay Edge Sobreposição de bordas Part of ArtCraft. MIT OR Apache-2.0. Fonts: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Icons: Lucide (ISC) + VectorCraft. Parte do ArtCraft. MIT OR Apache-2.0. Fontes: Source Sans 3, Inter, JetBrains Mono, Noto Sans SC (OFL). Ícones: Lucide (ISC) + VectorCraft. Path Length Comprimento do caminho + Grid Size Tamanho da Grade + Grid Colors Cores da Grade + Flattener Preset Predefinido de achatamento + X X + Y Y PDF/X-1a:2001 PDF/X-1a:2001 PDF/X-3:2002 PDF/X-3:2002 PDF/X-4:2010 PDF/X-4:2010 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 106343cddd..75f5f6a8dd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2551,6 +2551,11 @@ file-filter Templates Шаблоны Pathfinders: Обработка контуров: Paths Контуры Path Length Длина контуров + Grid Size Размер сетки + Grid Colors Цвета сетки + Flattener Preset Набор объединения + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Контуры: {paths} Опорные точки: {anchors} Цвета: {colors} Pattern Узор Pattern Editing Редактирование узора diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cc854aa362..5fd2d586e2 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6207,6 +6207,11 @@ theme Appearance Utseende Override Action "Open" Commands Ändra åtgärdens "Öppna"-kommandon lokalt Override Action "Save" Commands Ändra åtgärdens "Spara"-kommandon lokalt Path Length Banlängd + Grid Size Rutnätsstorlek + Grid Colors Rutnätsfärger + Flattener Preset Förinställning för tillplattning + X X + Y Y Play: Spela upp: Save and Close Spara och stäng Stop on Errors Stoppa vid fel diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 02fb1fbc9b..28f0172a4b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -506,13 +506,15 @@ fn control_bar_panel_menu_labels_are_in_complete_catalogs() { } /// Document Info's labels: every category title, which the panel and its menu show, every count -/// label of the Objects category, and the Document category's fixed row labels (the artboard rows -/// show artboard names and are left out). +/// label of the Objects category, and the Document category's fixed row labels, those of the +/// artboard the Artboard tool has selected included (the artboard rows show artboard names and are +/// left out). #[test] fn document_info_labels_are_in_complete_catalogs() { let mut session = vectorcraft_engine::Session::new(); session.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap(); session.execute("shape.rectangle", &serde_json::json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + session.select_tool("artboard", vectorcraft_engine::ViewInfo::default()).unwrap(); let info = session.execute("document.info", &serde_json::json!({})).unwrap(); let sections = info["sections"].as_array().unwrap(); let titles: Vec<&str> = sections.iter().filter_map(|s| s["title"].as_str()).collect(); @@ -527,7 +529,7 @@ fn document_info_labels_are_in_complete_catalogs() { let artboards = document.iter().position(|r| r[0] == "Artboards").unwrap(); let names = artboards + 1..=artboards + document[artboards][1].as_str().unwrap().parse::().unwrap(); let fixed: Vec<&str> = document.iter().enumerate().filter(|(k, _)| !names.contains(k)).filter_map(|(_, r)| r[0].as_str()).collect(); - assert_eq!(fixed.len(), 9, "{fixed:?}"); + assert_eq!(fixed.len(), 18, "{fixed:?}"); labels.extend(fixed); for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { for label in &labels { @@ -538,7 +540,8 @@ fn document_info_labels_are_in_complete_catalogs() { /// The values Document Info makes and shows in the interface language: the font states and /// embedding permissions, the templates of the font, image, raster effects and Repeat object -/// values, the names of gradients named by their kind, and the counted instances, rows and columns. +/// values, the names of gradients named by their kind, the counted instances, rows and columns, and +/// the transparency settings' values. #[test] fn document_info_values_are_in_complete_catalogs() { const VALUES: [&str; 20] = [ @@ -564,6 +567,17 @@ fn document_info_values_are_in_complete_catalogs() { "Freeform gradient", ]; const COUNTED: [(&str, &str); 3] = [("{n} instance", "{n} instances"), ("{n} row", "{n} rows"), ("{n} column", "{n} columns")]; + // The transparency settings' values: the grid's sizes and color presets, on and off, and the + // built-in flattener presets. + let transparency = ["Small", "Medium", "Large", "On", "Off", "High Resolution", "Medium Resolution", "Low Resolution"] + .into_iter() + .chain(vectorcraft_doc::setup::GRID_COLOR_PRESETS.iter().map(|(name, _)| *name)); + let transparency: Vec<&str> = transparency.collect(); + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for value in &transparency { + assert!(lang.catalog().plain(value).is_some(), "{} is missing {value}", lang.code); + } + } let gradient_kinds: Vec = vectorcraft_color::GradientKind::ALL.iter().map(|k| format!("{} gradient", k.label())).collect(); assert!(gradient_kinds.iter().all(|k| VALUES.contains(&k.as_str())), "{gradient_kinds:?}"); for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2888a30f0..8c98ac8385 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2310,6 +2310,11 @@ shape Open Açık Pathfinders: Yol Bulucular: Paths Yollar Path Length Yol Uzunluğu + Grid Size Izgara Boyutu + Grid Colors Izgara Renkleri + Flattener Preset Düzleştirici ön ayarı + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} Yollar: {paths} Bağlantılar: {anchors} Renkler: {colors} Pattern Desen Pattern Editing Desen Düzenleme diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 411b2c3baf..d869627f40 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2556,6 +2556,13 @@ file-filter Templates Шаблони Pathfinders: Обробка контурів: Paths Контури Path Length Довжина контурів + Grid Size Розмір сітки + Grid Colors Кольори сітки + Flattener Preset Набір зведення + X X + Y Y + Orange Помаранчевий + Purple Фіолетовий Paths: {paths} Anchors: {anchors} Colors: {colors} Контури: {paths} Опорні точки: {anchors} Кольори: {colors} Pattern Візерунок Pattern Editing Редагування візерунка diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1460910197..81c6825c33 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2830,6 +2830,13 @@ digits Hindi Hindi Pathfinders: Pathfinder: Paths Đường dẫn Path Length Độ dài đường dẫn + Grid Size Kích thước lưới + Grid Colors Màu lưới + Flattener Preset Thiết lập sẵn làm phẳng + X X + Y Y + Orange Cam + Purple Tím Paths: {paths} Anchors: {anchors} Colors: {colors} Đường dẫn: {paths} Điểm neo: {anchors} Màu: {colors} Pattern Họa tiết Pattern Brush Cọ họa tiết diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3fe2f9e009..59f1612077 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2418,6 +2418,11 @@ file-filter Templates 模板 Pathfinders: 路径查找器: Paths 路径 Path Length 路径长度 + Grid Size 网格大小 + Grid Colors 网格颜色 + Flattener Preset 拼合预设 + X X + Y Y Paths: {paths} Anchors: {anchors} Colors: {colors} 路径:{paths} 锚点:{anchors} 颜色:{colors} Pattern 图案 Pattern Editing 图案编辑 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab7f9d9dd2..fc241d673b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3636,6 +3636,13 @@ file-filter Templates 範本 Pathfinders: 路徑管理員: Paths 路徑 Path Length 路徑長度 + Grid Size 格點大小 + Grid Colors 格點顏色 + Flattener Preset 平面化預設集 + X X + Y Y + Orange 橙色 + Purple 紫色 Paths: {paths} Anchors: {anchors} Colors: {colors} 路徑:{paths} 錨點:{anchors} 顏色:{colors} Pattern 圖樣 Pattern Editing 圖樣編輯 diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 64144a2150..ff978ebb4f 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -11,10 +11,11 @@ use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; -/// `document.info` and what it was fetched for: (document uid, revision, selection only). +/// `document.info` and what it was fetched for: (document uid, revision, selection only, the +/// Artboard tool's options while it is the current tool, else null). #[derive(Clone, Default)] struct Cache { - key: Option<(u64, u64, bool)>, + key: Option<(u64, u64, bool, Value)>, info: Value, } @@ -31,10 +32,12 @@ pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { }); } -/// `document.info` with its categories, fetched again only when the document or the scope changes. +/// `document.info` with its categories, fetched again only when the document, the scope or the +/// artboards the Artboard tool has selected change. fn info(app: &mut VectorcraftApp, ctx: &egui::Context, sel_only: bool) -> Option { + let artboard_tool = if app.session.tool_id() == "artboard" { app.session.tool_options_of("artboard") } else { Value::Null }; let st = app.session.active()?; - let key = Some((st.uid, st.revision, sel_only)); + let key = Some((st.uid, st.revision, sel_only, artboard_tool)); let mut c: Cache = pstate(ctx, "docinfo-cache"); if c.key != key { c.info = app.session.execute("document.info", &json!({ "selectionOnly": sel_only })).ok()?; @@ -121,6 +124,9 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n let ppi = info["document"]["rasterEffectsPpi"].as_f64()?; Some(fill(tl!("{n} ppi"), &[("n", &ppi.to_string())])) } + "Grid Size" | "Grid Colors" | "Simulate Colored Paper" | "Flattener Preset" => { + transparency_value(&info["document"]["transparency"], label) + } _ => None, }, "brushes" => Some(brush_value(value).to_string()), @@ -136,6 +142,40 @@ fn shown_value(info: &Value, id: &str, k: usize, (label, value): (&str, &str), n } } +/// A transparency row of Document (`label`) in the interface language, from `document.info`'s +/// `document.transparency` (`t`): the grid's size, its colors' preset name (two custom colors stay +/// as `document.info` gives them), Simulate Colored Paper on or off, and a built-in flattener +/// preset's name (a saved preset's name stays as it is). +fn transparency_value(t: &Value, label: &str) -> Option { + let shown = match label { + "Grid Size" => match t["gridSize"].as_str()? { + "small" => tl!("Small"), + "medium" => tl!("Medium"), + "large" => tl!("Large"), + _ => return None, + }, + "Grid Colors" => match t["gridColorsName"].as_str()? { + "Custom" => return None, + name if vectorcraft_doc::setup::GRID_COLOR_PRESETS.iter().any(|(n, _)| *n == name) => tl!(name), + _ => return None, + }, + "Simulate Colored Paper" => { + if t["simulatePaper"].as_bool()? { + tl!("On") + } else { + tl!("Off") + } + } + _ => match t["flattenerPreset"].as_str()? { + "High Resolution" => tl!("High Resolution"), + "Medium Resolution" => tl!("Medium Resolution"), + "Low Resolution" => tl!("Low Resolution"), + _ => return None, + }, + }; + Some(shown.to_string()) +} + /// [`crate::i18n::fill_once`]: a name that holds `{…}` text stays as it is. fn fill(template: &str, args: &[(&str, &str)]) -> String { crate::i18n::fill_once(template, args) @@ -553,6 +593,58 @@ mod tests { assert!(report.contains("Units: Millimeters\n") && report.contains("Radial Repeat, 6 instances"), "{report}"); } + /// Document shows the transparency settings with their values in the interface language (two + /// custom grid colors as they are), and while the Artboard tool is the current tool the + /// artboards it has selected, following its selection without an edit to the document. + #[test] + fn document_shows_transparency_and_the_artboard_tools_selection() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + app.session.execute("artboard.setProps", &json!({"index": 1, "name": "Back"})).unwrap(); + let ctx = egui::Context::default(); + let document = |app: &mut VectorcraftApp| { + let info = info(app, &ctx, false).unwrap(); + shown_rows(&info, "document") + }; + let value = |rows: &[(String, String)], label: &str| rows.iter().find(|(l, _)| l == label).map(|(_, v)| v.clone()); + let english = document(&mut app); + assert_eq!(value(&english, "Grid Colors").as_deref(), Some("Light")); + assert_eq!(value(&english, "X"), None, "no artboard rows with another tool: {english:?}"); + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([1])); + let rows = document(&mut app); + let at = rows.iter().position(|(l, v)| l == "Artboard" && v == "Back").unwrap_or_else(|| panic!("{rows:?}")); + assert_eq!(rows[at + 1..at + 5].iter().map(|(_, v)| v.as_str()).collect::>(), ["60 pt", "80 pt", "0 pt", "0 pt"]); + // Selecting another artboard changes the rows, though the document did not change. + app.session.set_tool_option("selected", &json!([0, 1])); + let rows = document(&mut app); + assert_eq!(rows.iter().filter(|(l, _)| l == "Artboard").count(), 2, "{rows:?}"); + assert!(rows.contains(&("X".into(), "150 pt".into())) && rows.contains(&("Y".into(), "40 pt".into())), "from artboard 1's corner: {rows:?}"); + app.session + .execute( + "document.setup", + &json!({"gridSize": "large", "simulatePaper": true, "flattenerPreset": "Low Resolution", "gridColors": "Purple"}), + ) + .unwrap(); + let Some(de) = crate::i18n::Lang::from_code("de") else { panic!("no German catalog") }; + crate::i18n::set_current(de); + let german = document(&mut app); + let painted = crate::tests_labels::painted_text(&mut app, show); + crate::i18n::set_current(crate::i18n::Lang::EN); + let shown = |label: &str| value(&german, label).unwrap_or_else(|| panic!("no {label} in {german:?}")); + assert_eq!( + [shown("Grid Size"), shown("Grid Colors"), shown("Simulate Colored Paper"), shown("Flattener Preset")], + ["Groß", "Lila", "Ein", "Niedrige Auflösung"] + ); + assert!(painted.contains("Rastergröße") && painted.contains("Groß") && painted.contains("Back"), "{painted}"); + app.session.execute("document.setup", &json!({"gridColors": ["#ff0000", "#00ff00"]})).unwrap(); + crate::i18n::set_current(de); + let custom = value(&document(&mut app), "Grid Colors"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(custom.as_deref(), Some("#ff0000, #00ff00")); + } + /// A Repeat object's counts take each language's plural forms, and a grid that draws fewer /// instances than its rows and columns give is followed by the number it draws. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 8ca4121032..c2d4bc4298 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7738,7 +7738,14 @@ file name, null for a built-in face; `embedding` is `allowed`, `editing`, `previ face is found), `imageObjects` (`[{name, width, height, linked, file}]`: the image objects in the order the linkedImages and embeddedImages categories list them, with the file a linked image's row shows and null for an embedded one), `document.unitId` (the document's units as Preferences › Units names them, such as `millimeters`, beside -the English `document.units`), `brushNames` (the brushes the art's strokes use, each once, hidden strokes, strokes at an opacity of 0, strokes with no +the English `document.units`), `document.transparency` (`{gridSize, gridColors, gridColorsName, simulatePaper, +flattenerPreset}`: File › Document Setup's transparency settings, the grid's size (`small`, `medium` or `large`), its +two colors as `#rrggbb`, their preset's name or `Custom`, Simulate Colored Paper and the flattener preset, which the +document category lists as Grid Size, Grid Colors (two custom colors by their values), Simulate Colored Paper and +Flattener Preset), `document.selectedArtboards` (`[{index, name, width, height, x, y}]`: while the Artboard tool is the +current tool, the artboards it has selected, in artboard order and in the document's units, with `x` and `y` those of +the top-left corner measured from the ruler origin of the tool's active artboard; the document category lists each +after the artboards as Artboard, Width, Height, X and Y; empty with any other tool), `brushNames` (the brushes the art's strokes use, each once, hidden strokes, strokes at an opacity of 0, strokes with no paint or width, guides, paths with no segment, type that draws no characters, a group's or layer's own strokes, a compound path member's own strokes and an image's strokes without a shape left out; with `selectionOnly`, the brushes the selected objects' strokes use), `brushes` (`[{name, type}]`: those brushes with their types, `calligraphic`, `scatter`, `art`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4424700be..3040f6ef11 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1634,6 +1634,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Document Info's Spot Color Objects category lists the objects that use spot colors, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as objects using spot color separations. Each object is listed by name with the spot colors it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "spotColors"}`, `spotObjects`). Taking a solid color or a gradient stop linked to a spot swatch at a tint above 0 and a grayscale image colorized with one, leaving out process colors that look the same, Registration, gradients whose stops are all at an opacity of 0, gradient stops at an opacity of 0 that mix only with other stops at an opacity of 0 or only over stretches with no width, fills and strokes at an opacity of 0, paint that draws nothing by the rules Pattern Objects follows, spot swatches no art uses and spot colors inside patterns, symbols, opacity masks, effects and placed files, are VectorCraft's own rules. A stop at an opacity of 0 next to a stop above it stays listed, since the stretch between them is drawn in its color. Objects counts the listed objects as Spot Color Objects. Tests: `cmd::docinfo::tests::info_lists_the_spot_color_objects`, `spot_color_objects_take_colorized_images_and_skip_clear_gradients`, `spot_color_objects_skip_clear_fills_and_strokes`, `spot_color_objects_skip_spot_stops_only_in_clear_stretches` and `drawn_stops_follow_the_sampled_stretches` (vectorcraft-engine). Document Info's Brushes, Spot Color Objects, Pattern Objects and Gradient Objects categories leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0, their characters' paints and colorized images included. With Selection Only an object selected inside such a group or layer is left out too, and Objects still counts every object as before. This is VectorCraft's own rule. Test: `cmd::docinfo::tests::info_skips_paints_on_hidden_and_clear_objects_and_their_members` (vectorcraft-engine). Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. + Document Info's Document category lists the document's transparency settings, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes: File › Document Setup's grid size, grid colors, Simulate Colored Paper and flattener preset (`document.info`'s `document.transparency`). While the Artboard tool is the current tool, it also lists the width, height and position of each artboard that tool has selected, as the same page describes for the selected artboard (`document.selectedArtboards`). Listing every selected artboard, measuring the position at the top-left corner from the ruler origin of the tool's active artboard, and naming two custom grid colors by their values are VectorCraft's own rules. The panel shows the values in the interface language, and the report keeps them in English. Tests: `cmd::docinfo::tests::info_lists_the_transparency_settings` and `info_lists_the_artboards_the_artboard_tool_selected` (vectorcraft-engine), `panels::doc_info::tests::document_shows_transparency_and_the_artboard_tools_selection` (vectorcraft-ui-egui). Document Info's category menu and headings show every category title in the interface language, Font Details, Linked Images and Embedded Images included, and the Objects category shows every count label in it too: Compound Paths, Text Objects, Placed Documents, Symbol Instances, Gradient Meshes, Blends, Envelopes, Intertwine Groups, Opacity Masks and Objects with Effects. The Document category's Pattern Swatches row and the Objects category's Path Length row are translated in every catalog that has every menu label. `document.info` and the saved report keep the English labels. Showing these labels in the interface language is VectorCraft's own rule. Test: `i18n::tests::document_info_labels_are_in_complete_catalogs` (vectorcraft-ui-egui). Document Info shows the values it makes in the interface language too: the Units, the Raster Effects resolution, each font's file, substitution and embedding permission (or that it is built in or missing), each image's size and linked file, each Repeat object's kind with its instances, rows and columns in the language's plural forms, and gradients named by their kind. Font, face, file, swatch and other names stay as they are, a gradient swatch named like a kind included, and `document.info`, Save… and Package's report keep the English values (`document.unitId`, `fontDetails`, `imageObjects`, `gradientObjects` `kinds`). Showing these values in the interface language is VectorCraft's own rule. Tests: `panels::doc_info::tests::values_follow_interface_language_and_keep_names`, `repeat_value_uses_locale_plural_forms_and_drawn_count`, `i18n::tests::document_info_values_are_in_complete_catalogs` (vectorcraft-ui-egui), `cmd::docinfo::tests::info_exposes_structured_font_details_without_changing_english_rows`, `info_exposes_ordered_images_and_unit_id` and `gradient_kinds_tell_kinds_from_swatch_names` (vectorcraft-engine). The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). From 7337434733006c39028d705b3fcfaf92b27bc645 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 00:19:10 -0800 Subject: [PATCH 056/138] i18n: Polish translates five dimension errors that showed in English The Polish catalog had no message row for five errors of the dimension commands (original artwork, locked or hidden, mode and source, offset, point), so each one showed in English. A test checks that each message is translated. --- crates/ui-egui/src/i18n/pl.tsv | 5 +++++ crates/ui-egui/src/i18n/tests.rs | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 93969d2bc3..dea86873ba 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6084,18 +6084,23 @@ mark-style Japanese Japońskie Precision: Dokładność: Update Dimensions Aktualizuj wymiary @msg Angles require two straight segments Kąty wymagają dwóch prostych odcinków +@msg Choose original artwork, not a dimension's generated paths Wybierz oryginalną kompozycję, a nie ścieżki wygenerowane przez wymiar @msg Choose two different points Wybierz dwa różne punkty @msg Choose two non-parallel straight segments Wybierz dwa nierównoległe proste odcinki @msg Choose two nonzero angle arms Wybierz dwa niezerowe ramiona kąta +@msg Dimension is locked or hidden Wymiar jest zablokowany lub ukryty +@msg Dimension mode does not match its source Tryb wymiaru nie odpowiada jego źródłu @msg Dimension point is outside the canvas Punkt wymiaru leży poza obszarem roboczym @msg Dimension size is outside its supported range Rozmiar wymiaru jest poza obsługiwanym zakresem @msg First measured segment no longer exists Pierwszy mierzony odcinek już nie istnieje @msg Invalid dimension distance Nieprawidłowa odległość wymiaru @msg Invalid dimension font name Nieprawidłowa nazwa czcionki wymiaru +@msg Invalid dimension offset Nieprawidłowe odsunięcie wymiaru @msg Invalid drawing scale Nieprawidłowa skala rysunku @msg Invalid real scale Nieprawidłowa skala rzeczywista @msg Measured anchor no longer exists Mierzony punkt kontrolny już nie istnieje @msg Invalid measured point Nieprawidłowy mierzony punkt +@msg Invalid point Nieprawidłowy punkt @msg Measured segment no longer exists Mierzony odcinek już nie istnieje @msg Non-finite dimension Wymiar nie jest liczbą skończoną @msg Only linear dimensions are horizontal or vertical Tylko wymiary liniowe są poziome lub pionowe diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 44db5d3dfd..0a58604f58 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5011,6 +5011,20 @@ fn pl() -> Lang { Lang::from_code("pl").expect("pl registered") } +/// Polish translates the dimension commands' errors. +#[test] +fn polish_translates_dimension_messages() { + for english in [ + "Choose original artwork, not a dimension's generated paths", + "Dimension is locked or hidden", + "Dimension mode does not match its source", + "Invalid dimension offset", + "Invalid point", + ] { + assert_ne!(message(pl(), english), english); + } +} + #[test] fn polish_plurals_have_three_forms() { let forms: Vec = [0, 1, 2, 4, 5, 11, 12, 14, 21, 22, 25, 101, 112, 122].into_iter().map(plural_polish).collect(); From 06e212e1bbe1a53d5e3d41dcee5df7ba4fc6009c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:20:21 -0800 Subject: [PATCH 057/138] Variables: Import Data Sets follows % column paths as image paths A `%` column's cell was read as given when absolute, or joined to the CSV's folder or `base`, so a CSV could make dataset.import open a file on another computer (a UNC path or a `file:` URL with a host). Each cell now goes through fileio::document_path, as an image variable's path does when a data set is selected (crates/engine/src/cmd/links.rs:1169-1173), with the CSV's folder or `base` as the document's folder. Paths on another computer or on another network share, devices and URLs are refused before any file is read, with the line, the column and the reason. Absolute local paths, `file:` URLs without a host and relative paths are still read, as image paths are. The params text and docs/mcp.md state the rule, and that relative `%` paths are taken from the CSV's folder at import while relative `@` paths are taken from the document's folder when a data set is selected. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/cmd/variablecmds/csv.rs | 34 ++++++++++--------- crates/engine/src/tests/variables.rs | 40 +++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/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/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 12 ++++--- 20 files changed, 84 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index e8867d5505..63119257bc 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -1054,7 +1054,7 @@ pub fn specs() -> Vec { "Import Data Sets…", ["Window", "Variables"], None, - "{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}", + "{path? | data? | dataBase64? | csv?, base?: folder} replace every dataset with the rows of a CSV, comma- or tab-separated, in UTF-16 (with a byte-order mark, or without one when at least half of its two-byte units hold a NUL byte and only one byte order reads a line break; any other file with NUL bytes is refused), UTF-8 or else Windows-1252 (header: one variable name per column, whatever its case; one row per dataset, named Data Set 1, 2… in file order). The document's variables and their bindings stay. A header that names no variable defines one, unbound: `#Name` defines a visibility variable, `@Name` defines an image variable, `%Name` defines a graph variable, and a header without a prefix defines a text variable. A `%Name` column's cells are paths of graph data files, each read as Graph Data's Import Data reads one (at most 1 MB; tab-separated when a line holds a tab, else comma-separated; UTF-16 by dataset.import's rule, else UTF-8, with bytes that aren't UTF-8 read as replacement characters; the first row holds the series labels and the first column the category labels) and kept as the data set's graph value, which applies as graph.setData applies it. The files are read at import. A relative path is taken from `base`, else from the folder of the CSV file at `path`; with neither, it is refused (an `@Name` column's relative paths are kept as they are and taken from the document's folder when a data set is selected). A path on another computer, or on a network share other than the one `base` or the CSV is on, a device and a URL other than a `file:` URL without a host are refused, as image variables' paths are, before anything is read. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all (each file counted once, each cell's value every time) refuse the import, naming the line and the column. A prefixed header whose name is a variable of another kind is refused, and so are two headers that name one variable and a header that would define a variable while the variables are locked. An import that leaves the variables and data sets as they were adds no undo step → {imported, names, defined, deletedDataSets}", has_doc, dataset_import ), diff --git a/crates/engine/src/cmd/variablecmds/csv.rs b/crates/engine/src/cmd/variablecmds/csv.rs index 0d3d1057c9..856ea4060e 100644 --- a/crates/engine/src/cmd/variablecmds/csv.rs +++ b/crates/engine/src/cmd/variablecmds/csv.rs @@ -397,27 +397,31 @@ struct GraphFiles { /// The graph value of a `%` column's cell `path` on file line `line`, in 1-based `column`, for the /// graph variable `var`: the graph data file at `path` (taken from the folder `base` when /// relative), read as Graph Data's Import Data reads one ([`crate::cmd::graph::graph_csv_from_file`]), -/// or no value for an empty cell. A relative path without `base`, a file that can't be read or is -/// larger than 1 MB, a file that gives a graph value longer than [`MAX_GRAPH_CSV`] bytes and more -/// than [`MAX_GRAPH_FILES_TOTAL`] bytes in all are refused, with the line and the column. +/// or no value for an empty cell. The path is followed as an image variable's path is +/// ([`crate::cmd::fileio::document_path`]): only files on this computer, or on the network share +/// `base` is on, are read. A relative path without `base`, a path on another computer or share, a +/// device or a URL, a file that can't be read or is larger than 1 MB, a file that gives a graph +/// value longer than [`MAX_GRAPH_CSV`] bytes and more than [`MAX_GRAPH_FILES_TOTAL`] bytes in all +/// are refused, with the line and the column. fn graph_file_value(files: &mut GraphFiles, path: &str, base: Option<&str>, var: &str, (line, column): (usize, usize)) -> Result> { const C: &str = "dataset.import"; let path = path.trim(); if path.is_empty() { return Ok(None); } - let full = match base { - _ if std::path::Path::new(path).is_absolute() => path.to_string(), - Some(base) => std::path::Path::new(base).join(path).to_string_lossy().into_owned(), - None => { - return Err(bad( - C, - format!( - "line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path" - ), - )); - } - }; + // Without `base`, a path that stays relative once a `file:` URL is read is refused here, so the + // error says what to give. + if base.is_none() && craft_docpath::resolve(path, None).is_ok_and(|p| !p.is_absolute()) { + return Err(bad( + C, + format!("line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path"), + )); + } + // `document_path` takes a relative path from the folder of a document; any file name in `base` + // stands for the CSV there. + let document = base.map(|base| std::path::Path::new(base).join("data sets.csv").to_string_lossy().into_owned()); + let full = crate::cmd::fileio::document_path(path, document.as_deref()) + .map_err(|r| bad(C, format!("line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r}")))?; let csv = match files.read.get(&full) { Some(csv) => csv.clone(), None => { diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 604e372a09..711c7c40bb 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -2229,6 +2229,46 @@ fn datasets_csv_refuses_unreadable_graph_data_files() { assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('2')), "{value:?}"); } +/// A `%` column's path is followed as an image variable's path is: a path on another computer (a +/// UNC path or a `file:` URL with a host) or a URL other than `file:` refuses the import with the +/// line and column and the reason, before any file is read, and leaves the variables and data sets +/// as they were. A relative path inside the CSV's folder is still read, and so is a `file:` URL +/// without a host when no folder is given. +#[test] +fn datasets_csv_refuses_graph_data_files_on_other_computers() { + let dir = Folder::new("vars-csv-graph-network"); + write(&dir.file("sub/ok.txt"), b"\tA\nX\t1\n"); + let path = dir.file("data.csv"); + write(&path, b"Name,%Chart\na,sub/ok.txt\n"); + let base = dir.0.to_string_lossy().into_owned(); + + let mut s = session(); + let imp = s.execute("dataset.import", &json!({"path": path})).unwrap(); + assert_eq!(imp["imported"], 1); + let value = s.doc().unwrap().doc.variables.datasets[0].values.get("Chart").cloned(); + assert!(matches!(&value, Some(vectorcraft_doc::DataValue::Graph(c)) if c.contains('A')), "{value:?}"); + // A `file:` URL without a host is a path on this computer, read without a folder to take it from. + let file = dir.file("sub/ok.txt").replace('\\', "/"); + let url = if file.starts_with('/') { format!("file://{file}") } else { format!("file:///{file}") }; + let imp = s.execute("dataset.import", &json!({"csv": format!("%Chart\n{url}")})).unwrap(); + assert_eq!(imp["imported"], 1, "{url}"); + let before = s.doc().unwrap().doc.variables.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for (cell, reason) in [ + (r"\\server\share\ok.txt", "the path is on another computer"), + ("//server/share/ok.txt", "the path is on another computer"), + ("file://server/share/ok.txt", "the path is on another computer"), + ("https://example.com/ok.txt", "the link is not a file path"), + ] { + let want = format!("line 3, column 2: the graph data file `{cell}` for `Chart` isn't followed: {reason}"); + let p = json!({"csv": format!("Name,%Chart\na,sub/ok.txt\nb,{cell}"), "base": base}); + let e = s.execute("dataset.import", &p).unwrap_err().to_string(); + assert!(e.contains(&want), "{cell}: {e}"); + assert_eq!(s.doc().unwrap().doc.variables, before, "{cell}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cell}"); + } +} + /// Two header cells that name one variable, by the same name or by a name and its prefix, are /// refused with both columns, and the import changes nothing. #[test] diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0061c153a3..8f24867021 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8390,6 +8390,7 @@ breakText Glyphs Glyfy @msg colour, mode and spot apply to solid-colour swatches only colour, mode a spot platí jen pro položky vzorníku s plnou barvou @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je zadán relativní cestou: zadejte `base` nebo absolutní cestu @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} řádek {line}, sloupec {column}: soubor dat grafu pro `{var}` nelze přečíst: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` se nenačítá: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` je větší než {MAX_GRAPH_DATA_FILE} bajtů @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes řádek {line}, sloupec {column}: soubor dat grafu `{path}` pro `{var}` dává hodnotu grafu delší než {MAX_GRAPH_CSV} bajtů @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all řádek {line}, sloupec {column}: soubory dat grafu obsahují celkem více než {MAX_GRAPH_FILES_TOTAL} bajtů diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c5c18e601d..0f64a2feb6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8071,6 +8071,7 @@ breakText Glyphs Glyphen @msg colour, mode and spot apply to solid-colour swatches only colour, mode und spot gelten nur für Vollfarbfelder @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist ein relativer Pfad: Geben Sie `base` oder einen absoluten Pfad an @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} Zeile {line}, Spalte {column}: die Diagrammdatendatei für `{var}` kann nicht gelesen werden: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} Zeile {line}, Spalte {column}: der Diagrammdatendatei `{path}` für `{var}` wird nicht gefolgt: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ist größer als {MAX_GRAPH_DATA_FILE} Byte @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes Zeile {line}, Spalte {column}: die Diagrammdatendatei `{path}` für `{var}` ergibt einen Diagrammwert, der länger als {MAX_GRAPH_CSV} Byte ist @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all Zeile {line}, Spalte {column}: die Diagrammdatendateien enthalten insgesamt mehr als {MAX_GRAPH_FILES_TOTAL} Byte diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 72cfd4fb39..5d97577cb7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8250,6 +8250,7 @@ breakText Glyphs Glyphes @msg colour groups can't go into colour groups un groupe de couleurs ne peut pas aller dans un groupe de couleurs @msg colour, mode and spot apply to solid-colour swatches only couleur, mode et ton direct s’appliquent uniquement aux nuances de couleur unie @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` est un chemin relatif : indiquez `base` ou un chemin absolu +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` n’est pas suivi : {r} @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} ligne {line}, colonne {column} : impossible de lire le fichier de données de graphe pour `{var}` : {e} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` dépasse {MAX_GRAPH_DATA_FILE} octets @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes ligne {line}, colonne {column} : le fichier de données de graphe `{path}` pour `{var}` donne une valeur de graphe de plus de {MAX_GRAPH_CSV} octets diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3b171d2ed7..d07235e525 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6703,6 +6703,7 @@ antiAlias Sharp शार्प @msg colour, mode and spot apply to solid-colour swatches only रंग, मोड और स्पॉट केवल ठोस रंग वाले स्वॉच पर लागू होते हैं @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` एक सापेक्ष पाथ है: `base` या एक पूर्ण पाथ दें @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल पढ़ी नहीं जा सकती: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` का पालन नहीं किया गया है: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` {MAX_GRAPH_DATA_FILE} बाइट्स से बड़ी है @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes लाइन {line}, कॉलम {column}: `{var}` के लिए ग्राफ़ डेटा फ़ाइल `{path}` से मिलने वाला ग्राफ़ मूल्य {MAX_GRAPH_CSV} बाइट्स से अधिक है @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all लाइन {line}, कॉलम {column}: ग्राफ़ डेटा फ़ाइलों में कुल मिलाकर {MAX_GRAPH_FILES_TOTAL} बाइट्स से अधिक हैं diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87a55ff0a2..82ec1d41c0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8261,6 +8261,7 @@ breakText Glyphs Glifák @msg colour, mode and spot apply to solid-colour swatches only colour, mode és spot: csak egyszínű színmintákra vonatkozik @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja relatív elérési út: adja meg a `base` értéket vagy egy abszolút elérési utat @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}. sor, {column}. oszlop: a(z) `{var}` diagramadat-fájlja nem olvasható: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line}. sor, {column}. oszlop: a(z) `{var}` diagramadat-fájlja nem lesz követve: `{path}`: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja nagyobb {MAX_GRAPH_DATA_FILE} bájtnál @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}. sor, {column}. oszlop: a(z) `{var}` `{path}` diagramadat-fájlja {MAX_GRAPH_CSV} bájtnál hosszabb diagramértéket ad @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}. sor, {column}. oszlop: a diagramadat-fájlok összesen több mint {MAX_GRAPH_FILES_TOTAL} bájtot tartalmaznak diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6632a9e43c..2179049bf1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8121,6 +8121,7 @@ breakText Glyphs Glifi @msg colour, mode and spot apply to solid-colour swatches only colore, metodo e spot si applicano solo ai campioni di colore pieno @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` è un percorso relativo: indica `base` o un percorso assoluto @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} riga {line}, colonna {column}: impossibile leggere il file di dati del grafico per `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` non viene seguito: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` supera i {MAX_GRAPH_DATA_FILE} byte @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes riga {line}, colonna {column}: il file di dati del grafico `{path}` per `{var}` dà un valore di grafico che supera i {MAX_GRAPH_CSV} byte @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all riga {line}, colonna {column}: i file di dati dei grafici contengono in tutto più di {MAX_GRAPH_FILES_TOTAL} byte diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 93e85b0fbf..bf433e9eb7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7322,6 +7322,7 @@ axis Y Axis Y 軸 @msg colour, mode and spot apply to solid-colour swatches only colour、mode、spot を適用できるのは単色のスウォッチだけです @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` は相対パスです: `base` か絶対パスを指定してください @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line} 行目、列 {column}: `{var}` のグラフデータファイルを読み込めません: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` は参照しません: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` が {MAX_GRAPH_DATA_FILE} バイトを超えています @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line} 行目、列 {column}: `{var}` のグラフデータファイル `{path}` から得られるグラフの値が {MAX_GRAPH_CSV} バイトを超えています @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line} 行目、列 {column}: グラフデータファイルが合計で {MAX_GRAPH_FILES_TOTAL} バイトを超えています diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 052958a93e..0326de8152 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7986,6 +7986,7 @@ breakText Glyphs 글리프 @msg colour, mode and spot apply to solid-colour swatches only colour, mode, spot은 단색 견본에만 적용됩니다 @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`은(는) 상대 경로입니다. `base` 또는 절대 경로를 지정하세요 @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} {line}행, {column}열: `{var}`의 그래프 데이터 파일을 읽을 수 없습니다: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`을(를) 따라가지 않습니다: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`이(가) {MAX_GRAPH_DATA_FILE}바이트보다 큽니다 @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes {line}행, {column}열: `{var}`의 그래프 데이터 파일 `{path}`에서 나온 그래프 값이 {MAX_GRAPH_CSV}바이트보다 깁니다 @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all {line}행, {column}열: 그래프 데이터 파일이 모두 합쳐 {MAX_GRAPH_FILES_TOTAL}바이트를 넘습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a586ff049e..2962182786 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6308,6 +6308,7 @@ imageTrace Outline Contour @msg colour, mode and spot apply to solid-colour swatches only colour, mode en spot gelden alleen voor stalen met een effen kleur @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is een relatief pad: geef `base` of een absoluut pad op @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} regel {line}, kolom {column}: het grafiekgegevensbestand voor `{var}` kan niet worden gelezen: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` wordt niet gevolgd: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` is groter dan {MAX_GRAPH_DATA_FILE} bytes @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes regel {line}, kolom {column}: het grafiekgegevensbestand `{path}` voor `{var}` geeft een grafiekwaarde langer dan {MAX_GRAPH_CSV} bytes @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all regel {line}, kolom {column}: de grafiekgegevensbestanden bevatten samen meer dan {MAX_GRAPH_FILES_TOTAL} bytes diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 24010e54e6..fe612ca322 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8362,6 +8362,7 @@ breakText Glyphs Glify @msg colour, mode and spot apply to solid-colour swatches only color, mode i spot dotyczą tylko próbek kolorów jednolitych @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` ma ścieżkę względną: podaj `base` albo ścieżkę bezwzględną @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} wiersz {line}, kolumna {column}: nie można odczytać pliku danych wykresu dla `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` nie jest pobierany: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` jest większy niż {MAX_GRAPH_DATA_FILE} bajtów @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes wiersz {line}, kolumna {column}: plik danych wykresu `{path}` dla `{var}` daje wartość wykresu dłuższą niż {MAX_GRAPH_CSV} bajtów @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all wiersz {line}, kolumna {column}: pliki danych wykresu zawierają łącznie ponad {MAX_GRAPH_FILES_TOTAL} bajtów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 75d0408eb0..f86d87853b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8452,6 +8452,7 @@ swatch Yellow Green Verde-amarelado @msg colour, mode and spot apply to solid-colour swatches only colour, mode e spot se aplicam somente a amostras de cor sólida @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` é um caminho relativo: informe `base` ou um caminho absoluto @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} linha {line}, coluna {column}: não é possível ler o arquivo de dados de gráfico de `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` não é seguido: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` tem mais de {MAX_GRAPH_DATA_FILE} bytes @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes linha {line}, coluna {column}: o arquivo de dados de gráfico `{path}` de `{var}` gera um valor de gráfico com mais de {MAX_GRAPH_CSV} bytes @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all linha {line}, coluna {column}: os arquivos de dados de gráfico têm mais de {MAX_GRAPH_FILES_TOTAL} bytes no total diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index de31b66c23..d213772382 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8029,6 +8029,7 @@ digits Hindi Hindi @msg colour, mode and spot apply to solid-colour swatches only färg, läge och dekor gäller endast enfärgade färgrutor @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är en relativ sökväg: ange `base` eller en absolut sökväg @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} rad {line}, kolumn {column}: diagramdatafilen för `{var}` kan inte läsas: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` följs inte: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` är större än {MAX_GRAPH_DATA_FILE} byte @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes rad {line}, kolumn {column}: diagramdatafilen `{path}` för `{var}` ger ett diagramvärde som är längre än {MAX_GRAPH_CSV} byte @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all rad {line}, kolumn {column}: diagramdatafilerna innehåller sammanlagt mer än {MAX_GRAPH_FILES_TOTAL} byte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 407588758f..195693612c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7705,6 +7705,7 @@ axis Y Axis Y ekseni @msg colour, mode and spot apply to solid-colour swatches only colour, mode ve spot yalnızca düz renkli renk örnekleri için geçerlidir @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası göreli bir yoldur: `base` ya da mutlak bir yol verin @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} satır {line}, sütun {column}: `{var}` için grafik veri dosyası okunamıyor: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası izlenmiyor: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_DATA_FILE} bayttan büyük @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes satır {line}, sütun {column}: `{var}` için `{path}` grafik veri dosyası {MAX_GRAPH_CSV} bayttan uzun bir grafik değeri veriyor @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all satır {line}, sütun {column}: grafik veri dosyaları toplamda {MAX_GRAPH_FILES_TOTAL} bayttan fazla diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 311894ad57..8979298d23 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7988,6 +7988,7 @@ breakText Glyphs Гліфи @msg colour, mode and spot apply to solid-colour swatches only colour, mode і spot застосовуються лише до зразків суцільного кольору @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` задано відносним шляхом: укажіть `base` або абсолютний шлях @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} рядок {line}, стовпець {column}: не вдається прочитати файл даних діаграми для `{var}`: {e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} рядок {line}, стовпець {column}: перехід до файлу даних діаграми `{path}` для `{var}` не виконується: {r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` більший за {MAX_GRAPH_DATA_FILE} байтів @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes рядок {line}, стовпець {column}: файл даних діаграми `{path}` для `{var}` дає значення діаграми довше за {MAX_GRAPH_CSV} байтів @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all рядок {line}, стовпець {column}: файли даних діаграм разом містять понад {MAX_GRAPH_FILES_TOTAL} байтів diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 6132c78d9f..659c8297bf 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8348,6 +8348,7 @@ breakText Glyphs 字形 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只适用于纯色色板 @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 是相对路径:请提供 `base` 或绝对路径 @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 列:无法读取 `{var}` 的图表数据文件:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} 第 {line} 行,第 {column} 列:未跟随 `{var}` 的图表数据文件 `{path}`:{r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 超过 {MAX_GRAPH_DATA_FILE} 字节 @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 列:`{var}` 的图表数据文件 `{path}` 得到的图表值超过 {MAX_GRAPH_CSV} 字节 @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 列:图表数据文件总计超过 {MAX_GRAPH_FILES_TOTAL} 字节 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e034fcb82a..732fe86def 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8276,6 +8276,7 @@ breakText Glyphs 字符 @msg colour, mode and spot apply to solid-colour swatches only colour、mode 和 spot 只適用於純色色票 @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is a relative path: give `base`, or an absolute path 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 是相對路徑:請提供 `base` 或絕對路徑 @msg line {line}, column {column}: the graph data file for `{var}` can't be read: {e} 第 {line} 行,第 {column} 欄:無法讀取 `{var}` 的圖表資料檔案:{e} +@msg line {line}, column {column}: the graph data file `{path}` for `{var}` isn't followed: {r} 第 {line} 行,第 {column} 欄:未跟隨 `{var}` 的圖表資料檔案 `{path}` 的連結:{r} @msg line {line}, column {column}: the graph data file `{path}` for `{var}` is larger than {MAX_GRAPH_DATA_FILE} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 超過 {MAX_GRAPH_DATA_FILE} 位元組 @msg line {line}, column {column}: the graph data file `{path}` for `{var}` gives a graph value longer than {MAX_GRAPH_CSV} bytes 第 {line} 行,第 {column} 欄:`{var}` 的圖表資料檔案 `{path}` 得到的圖表值超過 {MAX_GRAPH_CSV} 位元組 @msg line {line}, column {column}: the graph data files hold more than {MAX_GRAPH_FILES_TOTAL} bytes in all 第 {line} 行,第 {column} 欄:圖表資料檔案合計超過 {MAX_GRAPH_FILES_TOTAL} 位元組 diff --git a/docs/mcp.md b/docs/mcp.md index 495d415593..4f3b2f6c30 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3486,10 +3486,14 @@ already walks Image Trace. Short agent entry points: at most 1 MB; tab-separated when any line holds a tab, else comma-separated; the first row holds the series labels and the first column the category labels; UTF-16 by the rule below, else UTF-8. The data becomes the data set's graph value, which `dataset.select` applies as `graph.setData` applies it, so the graph gets the data that Import - Data and Apply give it. A relative path is taken from `dataset.import`'s `base` folder, else from the folder of the - CSV file at `path`; with neither (`csv`, `data` or `dataBase64` and no `base`), it fails the import. This is - VectorCraft's own rule. A file that is missing, can't be read or is larger than 1 MB, a file that gives a graph value - longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all fail the import with + Data and Apply give it. The files are read at import. A relative path is taken from `dataset.import`'s `base` + folder, else from the folder of the CSV file at `path`; with neither (`csv`, `data` or `dataBase64` and no `base`), + it fails the import. This is VectorCraft's own rule, and it differs from an `@` column's: an image path is kept as + the cell gives it, and a relative one is taken from the document's folder when a data set is selected. A `%` path is + followed as an image path is: a path on another computer, or on a network share other than the one `base` or the + CSV file is on, a device, and a URL other than a `file:` URL without a host fail the import with the line, the + column and the reason, and no file is read. A file that is missing, can't be read or is larger than 1 MB, a file + that gives a graph value longer than 256 KB, and `%` columns whose files and graph values hold more than 256 MB in all fail the import with the line and the column, and the document is left as it was. Each file is read once per import, however many cells name it, and counts once toward the 256 MB; each cell's graph value counts every time. `dataset.export` writes a visibility variable's header as `#Shown` and an image variable's as `@Photo`, and a text or graph variable's as its From 6635cd77486ba4ac655f83ade33705d4d744faa9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:43:03 -0800 Subject: [PATCH 058/138] Recolor Artwork: a Color Groups list selects, saves, adds and deletes color groups The dialog lists the document's color groups on its right, or under the tabs in a narrow window, and the Show Color Groups button beside the tabs shows or hides the list. A click on a group makes it the group being edited: with art, the art is reduced again to a row per color of the group, which become the rows' new colors; without art, the rows are the group's colors. Save Changes rewrites the selected group with the colors OK would give it and the name in the name field, New Color Group saves the rows' new colors as a new group, and Delete removes the selected group. Each is its own undo step, and the Swatches panel shows it. When the art has colors of the group, Save Changes keeps the group's swatches in order: a swatch whose color a row lists takes that row's new color, and the others keep theirs. After a save with art the rows' new colors take the Global Adjust, which goes back to 0%, and when the save recolored linked art the rows are read from the art again. The dialog fields are group, groupStorage and groupAction (save, new or delete). A name no group has, a groupAction of another value, and save or delete with no group selected are refused. swatch.editGroup given a group's own colors in order and no new name records no undo step. --- crates/engine/src/cmd/swatch.rs | 8 + crates/engine/src/tests/swatchcmds.rs | 22 + crates/ui-egui/src/dialogs.rs | 6 +- crates/ui-egui/src/dialogs/recolor.rs | 806 +++++++++++++++++++++++++- docs/control-protocol.md | 5 +- docs/mcp.md | 27 +- docs/target-app-parity.md | 1 + 7 files changed, 856 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 3388b8344b..77d7aab06e 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -1291,6 +1291,14 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result { let colors: Vec = colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect(); let rename = str_param(p, "rename"); + // The group's own colors, in order, under its own name change nothing: no undo step. + if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group) + && rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group) + && old.len() == colors.len() + && old.iter().zip(&colors).all(|(o, c)| *o == Some(*c)) + { + return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::>(), "relinked": 0})); + } let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?; e.defaults(s)?; Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked})) diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index af059e5e33..88276a9e31 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -423,6 +423,28 @@ fn edit_color_group_numbers_extra_colors_after_the_names_it_keeps() { assert_eq!(*doc(&s), before); } +/// `swatch.editGroup` with the group's own colors, in order, and its own name (or a blank one) +/// records no undo step; a new order, a new color or a new name records one. +#[test] +fn edit_color_group_with_its_own_colors_records_no_undo_step() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00"], "keepModel": true})); + let undo = undo_len(&s); + for p in [ + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"]}), + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": "Mine"}), + json!({"group": "Mine", "colors": ["#ff0000", "#00ff00"], "rename": " "}), + ] { + let r = run(&mut s, "swatch.editGroup", p.clone()); + assert_eq!(r, json!({"name": "Mine", "swatches": ["R=255 G=0 B=0", "R=0 G=255 B=0"], "relinked": 0}), "{p}"); + assert_eq!(undo_len(&s), undo, "{p}: no undo step"); + } + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"]})); + assert_eq!(undo_len(&s), undo + 1, "a new order is a step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#00ff00", "#ff0000"], "rename": "Yours"})); + assert_eq!(undo_len(&s), undo + 2, "a new name is a step"); +} + #[test] fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4ac6da2fbe..55a4b9c79d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -636,12 +636,16 @@ pub(crate) fn parent(d: &Dialog) -> Option { /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields /// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in -/// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. +/// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor +/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); return Ok(()); } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == recolor::KIND) { + return recolor::field_set(app, field); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index d2bbeb3013..dee96dfe08 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -31,6 +31,22 @@ //! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new //! colours as a colour group named `groupName`. //! +//! The Color Groups list on the right (under the tabs in a window too narrow for both; the Show +//! Color Groups button beside the tabs shows or hides it, and it opens shown) lists the document's color groups with their colors. A click on one makes it +//! the group being edited, as opening on it would: with art the art is reduced to as many rows as +//! it has colors, which become their new colors, and without art the rows are its colors. Save +//! Changes rewrites the selected group with the rows' new colors (`swatch.editGroup`, renamed by +//! `groupName`), New Color Group saves them as a new group (`swatch.newGroup`), and Delete removes +//! the selected group with its swatches (`swatch.delete`); each is a step of its own, which the +//! Swatches panel shows. When the art has colors of the group, Save Changes keeps the group's +//! swatches in order: a swatch whose color a row lists takes that row's new color (its own color +//! when the row is excluded), and every other swatch keeps its color. After a save with art the +//! rows' new colors take the Global Adjust, which goes back to 0%. When the save recolors art +//! linked to the group's global swatches, the rows are read from the art again (a color the save +//! gave the art is excluded, and a color the art had before keeps its row's new color). Until the +//! rows or the Global Adjust change, OK changes the saved group only by its name. After a Delete +//! without art, OK saves the rows as a new color group. +//! //! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an //! object takes the palette of the object a Selection tool click takes, a drag takes the palette //! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The @@ -48,8 +64,11 @@ //! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`; //! unset: `smooth`), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as //! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as -//! `recolor.weigh`'s; a new list moves the rows' current colors toward them). Changing `colors`, a -//! preserve flag or `limitTo` reduces the rows again (and drops `weights`). +//! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `groupStorage` (the +//! Color Groups list is shown), `groupAction` (`save`, `new` or `delete`: the list's buttons, +//! checked as the field is set and run by the next frame, or by OK first). Setting `group` to a color group's name selects it in the list, and null +//! selects none. Changing `colors`, a preserve flag or `limitTo` reduces the rows again (and drops +//! `weights`). use egui::{Rect, Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -76,10 +95,25 @@ pub(super) const SPEC: DialogSpec = DialogSpec { confirm, preview: true, min_width: 540.0, - max_width: Some(560.0), + max_width: Some(MAIN_W + STORAGE_GAP + STORAGE_W), + inputs: |_| &[GROUP_ACTION], ..DialogSpec::FORM }; +/// Widths of the dialog's main part (the tabs), of the Color Groups list and of the gap between +/// them; the height of a group's row in the list. +const MAIN_W: f32 = 560.0; +const STORAGE_W: f32 = 170.0; +const STORAGE_GAP: f32 = 12.0; +const GROUP_ROW_H: f32 = 34.0; +/// The fields of the Color Groups list: whether it is shown, a request from its buttons, and the +/// group whose colors the rows were last given. +const GROUP_STORAGE: &str = "groupStorage"; +const GROUP_ACTION: &str = "groupAction"; +const GROUP_LOADED: &str = "__groupLoaded"; +/// The `recolor.reduce` parameters the art's rows were last reduced with. +const REDUCED: &str = "__reduced"; + const CMD: &str = "recolor.apply"; /// Width of the current colours of a row. const CURRENT_W: f32 = 250.0; @@ -162,6 +196,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { "preserveGrays": kept("preserveGrays", false), "limitTo": limit, "group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true, "preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, "__art": art, "__assign": assign, "__newGroup": new_group, + GROUP_STORAGE: true, GROUP_LOADED: group, }); let mut d = Dialog::new(KIND, fields); // Without art the rows are there from the start: limit them now (art's rows snap as they reduce). @@ -195,7 +230,7 @@ fn reduce_params(d: &Dialog) -> Value { /// Reduce the art's colours into rows again when the count, preserve flags or library changed /// (assigning a group's colours or the opener's colours as the new colours). fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { - const DONE: &str = "__reduced"; + const DONE: &str = REDUCED; let sig = reduce_params(d); if !d.bool("__art") || d.fields.get(DONE) == Some(&sig) { return; @@ -387,7 +422,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator Result<(), String> { let rs = rows(d); let order: Vec = match which { "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(), @@ -395,12 +430,364 @@ fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) { }; let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i))); if colors.is_empty() { - return; + return Ok(()); } // The group is added to the document itself, not to the preview, which runs again afterwards. cancel_preview(app, d); - if let Err(e) = app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})) { - app.status(e); + app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})).map(|_| ()) +} + +/// The colors of the document's color groups, by name, in the Swatches panel's order. +fn doc_groups(app: &VectorcraftApp) -> Vec<(String, Vec)> { + let Some(st) = app.session.active() else { return vec![] }; + st.doc.swatch_groups.iter().map(|g| (g.name.clone(), g.swatches.iter().filter_map(|w| w.paint.color()).collect())).collect() +} + +/// Make the `group` field's color group (none when it is null) the group being edited, when its +/// colors aren't the rows' yet: with art the art is reduced again to as many rows as the group has +/// colors, which become their new colors (as [`open`] does); without art the rows are its colors. +/// A name no color group has is refused, and the field goes back to the group being edited. +fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let want = d.fields.get("group").cloned().unwrap_or(Value::Null); + let loaded = d.fields.get(GROUP_LOADED).cloned().unwrap_or(Value::Null); + if want == loaded { + return Ok(()); + } + // The preview gives the group being edited the name in `groupName`, which the list shows: unless + // the document (without the preview) has another group of that name, it is the same group. + if let Value::String(n) = &want + && loaded.is_string() + && *n == d.str("groupName") + && d.fields.contains_key(super::form::PREVIEWED) + { + cancel_preview(app, d); + if !doc_groups(app).iter().any(|(g, _)| g == n) { + d.fields.insert("group".into(), loaded); + return Ok(()); + } + } + let art = d.bool("__art"); + let name = match &want { + Value::Null => { + // No group: without art OK saves the rows as a new color group. + d.fields.insert(GROUP_LOADED.into(), Value::Null); + if !art { + d.fields.insert("__newGroup".into(), json!(true)); + d.fields.insert("groupName".into(), json!(NEW_GROUP)); + } + return Ok(()); + } + Value::String(n) => n.clone(), + v => { + d.fields.insert("group".into(), loaded); + return Err(format!("`group` must be a color group name, not {v}")); + } + }; + // The group's own colors, not those the preview (which rewrites the group being edited) shows. + if doc_groups(app).iter().any(|(n, _)| *n == name) { + cancel_preview(app, d); + } + let Some((_, colors)) = doc_groups(app).into_iter().find(|(n, _)| *n == name) else { + d.fields.insert("group".into(), loaded); + return Err(format!("no colour group `{name}`")); + }; + let assign: Vec = colors.iter().map(key).collect(); + d.fields.insert(GROUP_LOADED.into(), json!(name)); + d.fields.insert("groupName".into(), json!(name)); + d.fields.insert("__newGroup".into(), json!(false)); + // The group's colors take the place of colors picked with the Color Theme Picker. + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(SAVED_ROWS); + d.fields.remove(SAVED_COLORS); + if art { + // The art is reduced again (`sync`) into a row per color of the group. + d.fields.insert("colors".into(), json!(assign.len().max(1))); + d.fields.remove(REDUCED); + } else { + let mut rs: Vec = assign.iter().map(|k| json!({"from": [k], "to": k})).collect(); + snap(app, d, &mut rs); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("__sel".into(), json!([])); + d.fields.remove(COMPS); + } + d.fields.insert("__assign".into(), Value::Array(assign)); + Ok(()) +} + +/// Run a button of the Color Groups list: `save` rewrites the selected group with the rows' new +/// colors as OK gives them to it (with art, followed by the group's colors no row took) and the +/// name in `groupName`; `new` saves the new colors of the rows that aren't excluded as a new group; +/// `delete` removes the selected group and its swatches. Each is an undo step of its own on the +/// document, not on the preview, which runs again afterwards. +fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Result<(), String> { + check_group_action(d, action)?; + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // The rows as OK reads them (a group just selected reduces the art again). + sync(app, d); + sync_theme(app, d); + sync_weights(app, d); + match action.as_str() { + Some("new") => save_group(app, d, "all"), + Some("save") if unchanged_since_save(d) => { + // Nothing changed since the last save but perhaps the name. + let name = d.str("groupName"); + if name.trim().is_empty() || group.as_deref() == Some(name.as_str()) { + return Ok(()); + } + cancel_preview(app, d); + let colors: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "rename": name}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + Ok(()) + } + Some("save") => { + let rs = rows(d); + let p = apply_params(d); + // With art, the group's colors no row took follow, adjusted and snapped as OK gives them. + let rest: Vec = + p["groupColors"].as_array().map(|a| a.iter().skip(rs.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); + let mut colors = group_colors(app, d, rs.iter().chain(&rest)); + cancel_preview(app, d); + // With art in a color of the group, the group keeps its swatch order: a swatch whose color + // a row lists takes that row's new color (its own color when the row is excluded), so the + // art linked to it takes the color its row shows, and every other swatch keeps its color. + let own: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + let row_of = |k: &Value| rs.iter().find(|r| r["from"].as_array().is_some_and(|f| f.contains(k))); + if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { + colors = own + .iter() + .map(|k| match row_of(k) { + Some(r) if !excluded(r) => group_colors(app, d, std::iter::once(r)).into_iter().next().unwrap_or_else(|| k.clone()), + _ => k.clone(), + }) + .collect(); + } + let before = art_colors(app); + let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "keepModel": true, "rename": p["rename"]}))?; + let name = r["name"].clone(); + d.fields.insert("group".into(), name.clone()); + d.fields.insert(GROUP_LOADED.into(), name.clone()); + d.fields.insert("groupName".into(), name); + if d.bool("__art") { + // The saved group holds the Global Adjust: the rows' new colors take it, and it goes + // back to 0%, so neither the preview nor OK applies it again. + bake_adjust(app, d); + let rs = rows(d); + if art_colors(app) == before { + mark_saved(app, d); + } else { + reread_rows(app, d, &rs, &before); + } + } + Ok(()) + } + Some("delete") => { + cancel_preview(app, d); + app.run("swatch.delete", json!({"names": [group]}))?; + d.fields.insert("group".into(), Value::Null); + select_group(app, d) + } + _ => Ok(()), + } +} + +/// After Save Changes recolored the art linked to the group's global swatches, read the rows from +/// the art again. A row that lists a color the save gave the art (a paint of a selected object +/// that differs from `before`, [`art_colors`] before the save) is excluded with its first color, +/// so the art keeps it, also when other art has that color: `recolor.apply` recolors every use +/// of a color alike, so the row cannot keep that art's earlier new color without undoing the save. Any other row whose first current color one of the `old` rows listed takes +/// that row's new color and exclusion (art the save left as it was keeps its recolor); the rest +/// are excluded too. +fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec]) { + let given: Vec = + art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); + d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(REDUCED); + sync(app, d); + let mut rs = rows(d); + for r in &mut rs { + let Some(first) = r["from"].as_array().and_then(|f| f.first()).cloned() else { continue }; + let from_save = r["from"].as_array().is_some_and(|f| f.iter().any(|c| given.contains(c))); + match old.iter().find(|o| o["from"].as_array().is_some_and(|f| f.contains(&first))).filter(|_| !from_save) { + Some(o) => { + r["to"] = o["to"].clone(); + r["exclude"] = json!(excluded(o)); + } + None => { + r["to"] = first; + r["exclude"] = json!(true); + } + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + mark_saved(app, d); +} + +/// Give each row's new color the Global Adjust (and Limit to Library) as OK would, and set the +/// Global Adjust back to 0%; nothing changes when it is 0%. +fn bake_adjust(app: &VectorcraftApp, d: &mut Dialog) { + if global_adjust(adjust_values(d)).is_identity() { + return; + } + let mut rs = rows(d); + for r in &mut rs { + if to_color(r).is_some() + && let Some(c) = group_colors(app, d, std::iter::once(&*r)).into_iter().next() + { + r["to"] = c; + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("globalAdjust".into(), Value::Object(ADJUSTS.iter().map(|k| (k.to_string(), json!(0.0))).collect())); +} + +/// After Save Changes with art: until the rows or the Global Adjust change, OK and the preview +/// leave the selected group's colors as they were saved. +fn mark_saved(app: &VectorcraftApp, d: &mut Dialog) { + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + d.fields.insert(SAVED_COLORS.into(), Value::Array(saved)); + d.fields.insert(SAVED_ROWS.into(), Value::Array(rows(d))); + d.fields.insert(SAVED_ADJUST.into(), json!(adjust_values(d))); +} + +/// Whether the rows and the Global Adjust are as [`mark_saved`] recorded them. +fn unchanged_since_save(d: &Dialog) -> bool { + d.fields.get(SAVED_ROWS).and_then(Value::as_array).is_some_and(|s| *s == rows(d)) + && d.fields.get(SAVED_ADJUST).is_some_and(|a| *a == json!(adjust_values(d))) +} + +/// The Global Adjust amounts [`mark_saved`] recorded. +const SAVED_ADJUST: &str = "__savedAdjust"; + +/// The colors of each selected object and what is inside it, as row keys, in paint order. +fn art_colors(app: &VectorcraftApp) -> Vec> { + let Some(st) = app.session.active() else { return vec![] }; + st.selection + .objects + .iter() + .map(|id| { + let mut cs = vec![]; + if let Some(n) = st.doc.node(*id) { + vectorcraft_doc::swatches::node_colors(n, &mut |c, _| cs.push(key(c))); + } + cs + }) + .collect() +} + +/// The rows [`mark_saved`] recorded after Save Changes; while the rows are these, OK and the preview +/// leave the group's colors as saved ([`SAVED_COLORS`]) and change only its name. +const SAVED_ROWS: &str = "__savedRows"; + +/// The selected group's colors after Save Changes, which OK gives it again with a new name. +const SAVED_COLORS: &str = "__savedColors"; + +/// Refuse a `groupAction` other than `save`, `new` or `delete`, and `save` or `delete` with no +/// group selected. +fn check_group_action(d: &Dialog, action: &Value) -> Result<(), String> { + match action.as_str() { + Some("new") => Ok(()), + Some("save" | "delete") if d.fields.get("group").is_some_and(Value::is_string) => Ok(()), + Some("save" | "delete") => Err("missing `group`".into()), + _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), + } +} + +/// Run the button of the Color Groups list that `groupAction` holds, if any. +fn run_group_action(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + match d.fields.remove(GROUP_ACTION) { + Some(a) => group_action(app, d, &a), + None => Ok(()), + } +} + +/// `ui.dialog.set` of `group`, `groupStorage` or `groupAction`: select the group, or check the +/// button, which the next frame (or OK) runs. +pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), String> { + let Some(mut d) = app.ui.dialog.take() else { return Ok(()) }; + let r = match field { + "group" => select_group(app, &mut d), + GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { + Some(a) => check_group_action(&d, &a), + None => Ok(()), + }, + GROUP_STORAGE if !d.fields.get(GROUP_STORAGE).is_some_and(Value::is_boolean) => Err(format!("`{GROUP_STORAGE}` must be true or false")), + _ => Ok(()), + }; + app.ui.dialog = Some(d); + r +} + +/// The Color Groups list: a row per color group of the document with its name and colors (a click +/// selects it), and the Save Changes, New Color Group and Delete buttons under it. +fn group_storage(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, max_h: f32) { + let t = Tokens::get(ui.ctx()); + let groups = doc_groups(app); + let mut current = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + // While the art previews, the group being edited shows under its new name. + if current.is_some() && d.fields.contains_key(super::form::PREVIEWED) && !groups.iter().any(|(n, _)| Some(n) == current.as_ref()) { + current = Some(d.str("groupName")); + } + let mut picked = None; + egui::ScrollArea::vertical().id_salt("recolor-groups").max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { + for (name, colors) in &groups { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_ROW_H), Sense::click()); + let on = current.as_deref() == Some(name.as_str()); + if on { + ui.painter().rect_filled(r, 2.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.hover); + } + let inner = r.shrink2(vec2(4.0, 3.0)); + ui.painter().text(inner.left_top(), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(12.0), t.text); + let fit = ((inner.width() + 2.0) / 12.0).floor().max(0.0) as usize; + for (n, c) in colors.iter().take(fit).enumerate() { + let x = inner.left() + n as f32 * 12.0; + chip(ui, Rect::from_min_size(pos2(x, inner.bottom() - 10.0), vec2(10.0, 10.0)), *c, false); + } + let resp = resp.on_hover_text(name); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), on, name)); + if resp.clicked() { + picked = Some(name.clone()); + } + } + }); + if let Some(name) = picked { + d.fields.insert("group".into(), json!(name)); + if let Err(e) = select_group(app, d) { + app.status(e); + } + } + ui.add_space(4.0); + let selected = current.is_some(); + let any = rows(d).iter().any(|r| !excluded(r)); + let mut action = None; + ui.horizontal(|ui| { + if widgets::icon_button_enabled(ui, "save", tl!("Save Changes"), false, selected, 24.0).clicked() { + action = Some("save"); + } + if widgets::icon_button_enabled(ui, "dc-folder", tl!("New Color Group"), false, any, 24.0).clicked() { + action = Some("new"); + } + if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete"), false, selected, 24.0).clicked() { + action = Some("delete"); + } + }); + if let Some(a) = action { + d.fields.insert(GROUP_ACTION.into(), json!(a)); } } @@ -565,13 +952,25 @@ fn selection(d: &Dialog) -> Vec { /// colours: the rows' new colours, then (with art) the group's colours no row took. fn apply_params(d: &Dialog) -> Value { let rs = rows(d); - let group = d.fields.get("group").and_then(Value::as_str).map(|g| { - let rest = - d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], |a| a.get(rs.len()..).unwrap_or_default()); - let colors: Vec<&Value> = rs.iter().map(|r| &r["to"]).chain(rest).collect(); + // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. + let saved = unchanged_since_save(d); + let group = d.fields.get("group").and_then(Value::as_str).and_then(|g| { let name = d.str("groupName"); let rename = (!name.trim().is_empty() && name != g).then_some(name); - json!({"group": g, "groupColors": colors, "rename": rename}) + let colors: Vec<&Value> = if saved { + // Only a new name changes the group. + rename.as_ref()?; + d.fields.get(SAVED_COLORS).and_then(Value::as_array).map(|a| a.iter().collect())? + } else { + let rest = d + .fields + .get("__assign") + .and_then(Value::as_array) + .filter(|_| d.bool("__art")) + .map_or(&[][..], |a| a.get(rs.len()..).unwrap_or_default()); + rs.iter().map(|r| &r["to"]).chain(rest).collect() + }; + Some(json!({"group": g, "groupColors": colors, "rename": rename})) }); // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); @@ -586,10 +985,49 @@ fn apply_params(d: &Dialog) -> Value { p } +/// The tabs, and the Color Groups list on their right while it is shown. fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + if let Err(e) = select_group(app, d) { + app.status(e); + } + let room = ui.available_width(); + // Without the room for both side by side (a narrow window), the list goes under the tabs. + let beside = room >= SPEC.min_width + STORAGE_GAP + STORAGE_W; + if !d.bool(GROUP_STORAGE) || !beside { + ui.vertical(|ui| { + ui.set_width(room.min(MAIN_W)); + main(app, ui, d); + if d.kind == KIND && d.bool(GROUP_STORAGE) { + ui.add_space(6.0); + group_storage(app, ui, d, 3.0 * GROUP_ROW_H); + } + }); + return false; + } + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width((room - STORAGE_GAP - STORAGE_W).clamp(0.0, MAIN_W)); + main(app, ui, d); + }); + // A double-click on a new color turns the dialog into the Color Picker. + if d.kind == KIND { + ui.add_space(STORAGE_GAP); + ui.vertical(|ui| { + ui.set_width(STORAGE_W); + group_storage(app, ui, d, TAB_H - 30.0); + }); + } + }); + false +} + +fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) { sync(app, d); sync_theme(app, d); sync_weights(app, d); + if let Err(e) = run_group_action(app, d) { + app.status(e); + } let t = Tokens::get(ui.ctx()); let picking = d.bool(THEME_PICKER); ui.horizontal(|ui| { @@ -603,6 +1041,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { d.fields.insert(THEME_PICKER.into(), json!(!picking)); } + let storage = d.bool(GROUP_STORAGE); + if widgets::icon_button(ui, "library", tl!("Show Color Groups"), storage, 24.0).clicked() { + d.fields.insert(GROUP_STORAGE.into(), json!(!storage)); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // The label is drawn after the menu (right-to-left), so it cannot name it by adjacency. if let Some(i) = widgets::dropdown_named(ui, "recolor-preset", Some(tl!("Preset:")), PRESETS[preset_of(d)], &PRESETS, 130.0) { @@ -634,8 +1076,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("rows".into(), Value::Array(rs)); } sync_weights(app, d); - if let Some(which) = d.fields.remove(SAVE_GROUP) { - save_group(app, d, which.as_str().unwrap_or_default()); + if let Some(which) = d.fields.remove(SAVE_GROUP) + && let Err(e) = save_group(app, d, which.as_str().unwrap_or_default()) + { + app.status(e); } if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") { ui.add_space(6.0); @@ -651,7 +1095,6 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { if let Some(c) = pick.and_then(|i| Some((i, to_color(rows(d).get(i)?)?))) { *d = super::color_picker::over_recolor(d, c.1, c.0); } - false } /// `d` with row `i`'s new colour set to `c` (the Color Picker's OK), snapped to Limit to Library. @@ -670,9 +1113,19 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C /// save colours opened alone as a new colour group). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); + select_group(app, &mut d)?; sync(app, &mut d); sync_theme(app, &mut d); sync_weights(app, &mut d); + // A Color Groups button set with OK in one request runs first, once: the open dialog takes + // its result, so an OK that fails afterwards does not run it again. + if d.fields.contains_key(GROUP_ACTION) { + let r = run_group_action(app, &mut d); + if let Some(live) = app.ui.dialog.as_mut().filter(|x| x.kind == KIND) { + *live = d.clone(); + } + r?; + } if d.bool("__newGroup") { let colors = group_colors(app, &d, rows(&d).iter().filter(|r| !excluded(r))); return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true})); @@ -2031,4 +2484,325 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("a new color group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), [Color::rgb8(255, 128, 0)]); } + + /// Sets `field` of the open dialog to `value` as `ui.dialog.set` does: a refused value leaves + /// the dialog as it was. + fn set(app: &mut VectorcraftApp, field: &str, value: Value) -> Result<(), String> { + let before = app.ui.dialog.clone(); + let old = app.ui.dialog.as_ref().and_then(|d| d.fields.get(field).cloned()); + if let Some(d) = app.ui.dialog.as_mut() { + crate::dialogs::set_field(d, field.into(), value); + } + let r = crate::dialogs::field_set(app, field, old.as_ref()); + if r.is_err() { + app.ui.dialog = before; + } + r + } + + fn group_hex(app: &VectorcraftApp, name: &str) -> Option> { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.iter().find(|g| g.name == name).map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Sets `groupAction` to `a` as `ui.dialog.set` does and draws the frame that runs it. + fn act(app: &mut VectorcraftApp, ctx: &egui::Context, t: f64, a: &str) -> Result<(), String> { + set(app, GROUP_ACTION, json!(a))?; + frame(app, ctx, t, vec![], 0); + Ok(()) + } + + /// Without art: a group picked in the Color Groups list (the `group` field) gives the rows its + /// colors, and a name no group has is refused. Save Changes rewrites the selected group with the + /// rows' new colors and the name field, as one step, and records none when nothing changes; + /// Delete removes it, after which OK saves the rows as a new group; New Color Group adds one. + #[test] + fn the_color_groups_list_selects_saves_and_deletes_groups() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], true, "the list opens shown"); + + set(&mut app, "group", json!("B")).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("groupName"), "B"); + assert_eq!(set(&mut app, "group", json!("Nope")), Err("no colour group `Nope`".into())); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "B", "a refused name leaves B selected"); + assert!(set(&mut app, GROUP_STORAGE, json!("yes")).is_err()); + assert!(set(&mut app, GROUP_ACTION, json!("rename")).is_err()); + + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + d.fields.insert("groupName".into(), json!("Night")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Night"), Some(vec!["#000000".into(), "#ffff00".into(), "#ffffff".into()])); + assert_eq!(group_hex(&app, "B"), None, "renamed"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["group"], "Night"); + assert_eq!(undo_len(&app), undo + 1, "one step"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(undo_len(&app), undo + 1, "saving the same colors again records no step"); + + act(&mut app, &ctx, 0.3, "delete").unwrap(); + assert_eq!(group_hex(&app, "Night"), None); + assert_eq!(undo_len(&app), undo + 2); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(d.fields["group"].is_null() && d.bool("__newGroup"), "{:?}", d.fields); + assert_eq!(act(&mut app, &ctx, 0.4, "delete"), Err("missing `group`".into())); + assert_eq!(act(&mut app, &ctx, 0.5, "save"), Err("missing `group`".into())); + assert_eq!(undo_len(&app), undo + 2, "a refused button records no step"); + + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + act(&mut app, &ctx, 0.6, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), n + 1); + let last: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + assert_eq!(last, ["#000000", "#ffff00", "#ffffff"]); + assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); + } + + /// Save Changes on a group whose global swatches the selected art is linked to: the art takes + /// the group's new colors, and the rows are read from the art again, so they list its colors as + /// they are now. A color the art had before keeps its row's new color; a color the save gave + /// it stays as it is. + #[test] + fn saving_a_group_the_art_links_to_reads_the_rows_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["from"].as_array().is_some_and(|f| f.contains(&json!("rgb 255 0 0"))) { + r["to"] = json!("rgb 0 128 0"); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + // The rows took the group's colors in their order, so one of the swatches is now green. + let saved = group_hex(&app, "Linked").unwrap(); + assert!(saved.len() == 2 && saved.contains(&"#008000".to_string()), "{saved:?}"); + let mut want = saved.clone(); + want.sort(); + assert_eq!(fill_hex(&app, red), "#008000", "the red square keeps the new color its row gave it"); + for r in super::rows(app.ui.dialog.as_ref().unwrap()) { + if !from_colors(&r).iter().any(|c| ["#ff0000", "#0000ff"].contains(&c.to_hex().as_str())) { + assert!(excluded(&r) && r["to"] == r["from"][0], "a color the save gave the art stays: {r}"); + } + } + let mut froms: Vec = super::rows(app.ui.dialog.as_ref().unwrap()).iter().flat_map(from_colors).map(|c| c.to_hex()).collect(); + froms.sort(); + assert_eq!(froms, want, "the rows list the art's colors as they are now"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + // OK with only a new name keeps the preview as one step and renames the group, keeping its + // saved colors. + let undo = undo_len(&app); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("groupName".into(), json!("Renamed")); + confirm(&mut app, &d).unwrap(); + assert_eq!(group_hex(&app, "Renamed"), Some(saved)); + assert_eq!(group_hex(&app, "Linked"), None); + assert_eq!(fill_hex(&app, red), "#008000"); + assert_eq!(undo_len(&app), undo + 1); + } + + /// Save Changes where one row's new color is another row's current color: the art linked to the + /// group keeps the colors the save gave it, and is not recolored again by the other row; a + /// Global Adjust set afterwards gives OK the group again. + #[test] + fn saving_a_group_keeps_the_colors_it_gave_the_linked_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let from = from_colors(r).first().map(|c| c.to_hex()); + r["to"] = match from.as_deref() { + Some("#ff0000") => json!("rgb 0 0 255"), + _ => json!("rgb 0 128 0"), + }; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + let mut group = group_hex(&app, "Linked").unwrap(); + group.sort(); + let mut fills = vec![fill_hex(&app, red), fill_hex(&app, blue)]; + fills.sort(); + assert_eq!(fills, group, "the art shows the saved group's colors, not a second recolor"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none()); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_some(), "a new Global Adjust rewrites the group at OK"); + } + + /// Save Changes with art in only some colors of the group: the swatches keep their order, and a + /// swatch no row lists keeps its color. + #[test] + fn saving_a_group_keeps_the_swatches_the_art_does_not_use() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the swatches keep their order and the red one its color"); + assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); + } + + /// Save Changes with art in the group's colors that is not linked to its swatches: the art is + /// left to the preview, and OK leaves the saved group as it is until the rows change. + #[test] + fn saving_a_group_with_unlinked_art_keeps_the_saved_group_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => json!("rgb 0 128 0"), + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(fill_hex(&app, blue), "#008000", "the art previews its row's new color"); + assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); + } + + /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and + /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. + #[test] + fn saving_a_group_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("method".into(), json!(Method::Exact.id())); + d.fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(adjust_values(d), [0.0; 4]); + d.fields.insert("groupName".into(), json!("Dark")); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert!(p.get("globalAdjust").is_none(), "{p}"); + let sent: Vec = p["groupColors"].as_array().unwrap().iter().map(|k| to_color(&json!({"to": k})).unwrap().to_hex()).collect(); + assert_eq!(sent, saved, "OK renames the group with its saved colors"); + } + + /// With art: a group picked in the list reduces the art to a row per color of the group, which + /// become the rows' new colors, and the art previews them; the list draws beside the tabs and + /// hides with `groupStorage`. + #[test] + fn a_group_picked_in_the_list_recolors_the_art() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Warm", "colors": ["#ffff00", "#00ff00"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Cool", "colors": ["#0000ff"], "keepModel": true})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + assert_eq!(fill_hex(&app, red), "#ff0000"); + // A button set with the group, before a frame, saves the rows the group gives the art. + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + set(&mut app, "group", json!("Warm")).unwrap(); + act(&mut app, &ctx, 0.1, "new").unwrap(); + let doc = &app.session.doc().unwrap().doc; + let mut saved: Vec = doc.swatch_groups.last().unwrap().swatches.iter().filter_map(|w| w.paint.color()).map(|c| c.to_hex()).collect(); + saved.sort(); + assert_eq!((doc.swatch_groups.len(), saved), (n + 1, vec!["#00ff00".to_string(), "#ffff00".to_string()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(super::rows(d).len(), 2); + assert_eq!(d.str("groupName"), "Warm"); + let mut shown = [fill_hex(&app, red), fill_hex(&app, blue)]; + shown.sort(); + assert_eq!(shown, ["#00ff00", "#ffff00"], "the art previews the group's colors"); + // The name the preview gives the group being edited picks that group in the list. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Sunny")); + frame(&mut app, &ctx, 0.21, vec![], 0); + set(&mut app, "group", json!("Sunny")).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["group"], &d.fields[GROUP_LOADED], d.str("groupName")), (&json!("Warm"), &json!("Warm"), "Sunny".into())); + // A group the document has under that name is picked instead. + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Cool")); + frame(&mut app, &ctx, 0.22, vec![], 0); + set(&mut app, "group", json!("Cool")).unwrap(); + frame(&mut app, &ctx, 0.23, vec![], 0); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields[GROUP_LOADED], super::rows(d).len()), (&json!("Cool"), 1)); + set(&mut app, GROUP_STORAGE, json!(false)).unwrap(); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields[GROUP_STORAGE], false); + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e6f3621e8e..a4e8da06bd 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -290,7 +290,10 @@ luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-ze colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches, 24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click -selects its row for the sliders and a drag moves the row without changing a color). Setting +selects its row for the sliders and a drag moves the row without changing a color). `groupStorage` shows the Color +Groups list (true when the dialog opens); setting `group` to a color group's name makes it the group being edited, +as opening on it does, and refuses a name no group has; `groupAction` (`save`, `new` or `delete`) runs the list's Save +Changes, New Color Group or Delete button on the next frame, or first on confirm (see `docs/mcp.md`). Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews `recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, diff --git a/docs/mcp.md b/docs/mcp.md index 8ca4121032..a043dd9178 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4337,7 +4337,8 @@ the others turn by the same hue). `limitTo` snaps new colours to a swatch librar `exclude: true` keeps its colours. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo -step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the +step (art linked to its global swatches follows); given the group's own colors in order and no new name, it records no +undo step. And `recolor.apply` with `group` recolours the art and rewrites the group together. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still reaches it; the reply's `relinked` counts the other linked paints that took the group's new colors. Art in a row that @@ -4404,6 +4405,30 @@ become the `weights` field, which moves the rows' current colors and previews th beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors of the rows that are not excluded, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow +for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). +The Show Color Groups button beside the tabs shows or hides the list (the `groupStorage` field, true when the dialog +opens). A click on a group, or `ui.dialog.set` of the `group` field to a group's name, makes it the group being +edited: with art the art is reduced again to a row per color of the group, which become the rows' new colors, and +without art the rows are the group's colors. A name that no group has is refused with `` no colour group `` ``, +and a `group` of null selects none. The buttons under the list are the `groupAction` field. Setting it checks the value, and the next frame of the +dialog runs it (OK with it set in the same request runs it first): +`save` (Save Changes) runs `swatch.editGroup` on the selected group with the colors OK would give it and the name in +`groupName`, `new` (New Color Group) saves the new colors of the rows that are not excluded as `swatch.newGroup` does, +and `delete` (Delete) runs `swatch.delete` on the selected group. Each is its own undo step, and the art keeps its +preview. When the art has colors of the group, `save` keeps the group's swatches in order: a swatch whose color a row +lists takes that row's new color (its own color when the row is excluded), so art linked to the swatch takes the color +its row shows, and every other swatch keeps its color. After a `save` with art, the rows' new colors take the Global +Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a +color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its +colors alike. Until the rows or the Global Adjust change, OK changes the saved group only by the name +in `groupName`. `save` and `delete` with no group selected answer `` missing `group` ``, and any other value is +refused. After a Delete without art, OK saves the rows as a new color group. + +```json +{"name":"answer_dialog","arguments":{"set":[{"field":"group","value":"Brights"},{"field":"groupAction","value":"save"}]}} +``` + ```json {"name":"run_command","arguments":{"command":"recolor.weigh","params":{"map":[{"from":["rgb 255 0 0","rgb 128 0 204"],"to":"#00ff00"},{"from":["rgb 0 0 255"],"to":"#ffff00"}],"weights":[1,1]}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4424700be..41f49aed06 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1591,6 +1591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. + - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups` and `a_group_picked_in_the_list_recolors_the_art` in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` in `crates/engine/src/tests/swatchcmds.rs`. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. From 3c0d32c1c34565737e026eb964048318ef74d0bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:28:07 -0800 Subject: [PATCH 059/138] Graphs: CSV graph data keeps the series labels given, as Graph Data does Graph data applied as CSV kept a blank series label for each column after the last label given, because to_csv writes one for every series without a label. A graph data file named in an Import Data Sets % column therefore gave the graph ["A", ""] where Graph Data's Import Data and Apply give it ["A"]. The CSV branch of apply_data now drops trailing blank labels, as graph_data_from_grid does; blank labels between given ones stay. --- crates/engine/src/cmd/graph/data.rs | 5 +++++ crates/engine/src/tests/variables.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/crates/engine/src/cmd/graph/data.rs b/crates/engine/src/cmd/graph/data.rs index b231ee2051..11cfd4ed26 100644 --- a/crates/engine/src/cmd/graph/data.rs +++ b/crates/engine/src/cmd/graph/data.rs @@ -245,6 +245,11 @@ pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result Date: Sun, 15 Nov 2026 08:50:04 -0800 Subject: [PATCH 060/138] Brushes: Options of Selected Object changes one brushed path's brush settings without changing the brush MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Brushes panel menu gains Options of Selected Object…. It opens the brush type's options dialog for the selected brushed paths, without the Name row, and OK stores the changed values on those paths' strokes only. The brush and its other strokes keep their settings. - brush.objectOptions {ids?, params?, reset?} sets the settings, clears them with reset, and returns them when given neither. It refuses params with reset, a selection with no brushed path, brushes of different types, a bristle brush, a field the type does not take and a value of the wrong kind. One undo step, none when nothing changes. - The stroke saves the settings as brush_options in the native file, and the brush renderer, the expansion of pattern tiles whose brushes vary at random and color conversion of Hue Shift keys read them. - Applying another brush, removing the brush or a brush change carried by Global Edit clears them; renaming the brush keeps them. - Docs: docs/mcp.md, docs/ui-parity.md; i18n rows for the new strings. --- crates/brush/src/lib.rs | 195 +++++++++++++++++- crates/brush/src/tests.rs | 61 ++++++ crates/doc/src/appearance/layers.rs | 6 + crates/engine/src/cmd/brushsym.rs | 13 +- crates/engine/src/cmd/brushsym/brushes.rs | 90 +++++++- crates/engine/src/cmd/buildcmds.rs | 1 + crates/engine/src/cmd/colormgmt.rs | 21 +- crates/engine/src/cmd/expand.rs | 18 +- crates/engine/src/cmd/globaledit.rs | 7 +- crates/engine/src/cmd/stroke.rs | 4 + crates/engine/src/tests/brushsym.rs | 110 ++++++++++ crates/engine/src/tests/globaledit.rs | 18 ++ crates/engine/src/tests/objexpand.rs | 22 ++ crates/engine/tests/command_sweep.rs | 11 + crates/mcp/src/ui_catalog.rs | 6 + .../ui-egui/src/dialogs/brush_art_options.rs | 14 +- crates/ui-egui/src/dialogs/brush_options.rs | 134 +++++++++++- .../src/dialogs/brush_options/tests.rs | 85 ++++++++ crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/palette.rs | 1 + crates/ui-egui/src/panels/brushes.rs | 6 + docs/mcp.md | 16 +- docs/ui-parity.md | 1 + 53 files changed, 976 insertions(+), 24 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 0b48f586cd..7f83931f25 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -753,6 +753,185 @@ impl Brush { } } +// ---------- stroke options ---------- + +/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]). +#[derive(Serialize, Deserialize)] +struct ScatterOptions { + size: (f64, f64), + spacing: (f64, f64), + scatter: (f64, f64), + rotation: (f64, f64), + modes: Option<[Variation; 4]>, + rotation_relative_to_path: bool, + colorization: Colorization, +} + +/// The Art brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct ArtOptions { + width: f64, + width_mode: Option, + width_max: Option, + flip_along: bool, + flip_across: bool, + overlap: bool, + colorization: Colorization, +} + +/// The Pattern brush fields a stroke can set for itself. +#[derive(Serialize, Deserialize)] +struct PatternOptions { + scale: f64, + spacing: f64, + fit: PatternFit, + flip_along: bool, + flip_across: bool, + colorization: Colorization, +} + +impl BrushKind { + /// The definition fields, by their `brush.options` names, that one stroke can set for itself + /// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle + /// brush has none. + pub fn stroke_option_keys(&self) -> &'static [&'static str] { + match self { + BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], + BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], + BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], + BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Bristle(_) => &[], + } + } + + /// The values of [`Self::stroke_option_keys`], as a JSON object. + fn option_values(&self) -> serde_json::Value { + let v = match self { + BrushKind::Calligraphic(c) => serde_json::to_value(c), + BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions { + size: s.size, + spacing: s.spacing, + scatter: s.scatter, + rotation: s.rotation, + modes: s.modes, + rotation_relative_to_path: s.rotation_relative_to_path, + colorization: s.colorization, + }), + BrushKind::Art(a) => serde_json::to_value(ArtOptions { + width: a.width, + width_mode: a.width_mode, + width_max: a.width_max, + flip_along: a.flip_along, + flip_across: a.flip_across, + overlap: a.overlap, + colorization: a.colorization, + }), + BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { + scale: p.scale, + spacing: p.spacing, + fit: p.fit, + flip_along: p.flip_along, + flip_across: p.flip_across, + colorization: p.colorization, + }), + BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())), + }; + v.unwrap_or_default() + } + + /// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives + /// them). An error when a value is of the wrong kind. + fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> { + match self { + BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?, + BrushKind::Scatter(s) => { + let o: ScatterOptions = serde_json::from_value(v)?; + (s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes); + (s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization); + } + BrushKind::Art(a) => { + let o: ArtOptions = serde_json::from_value(v)?; + (a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across); + (a.overlap, a.colorization) = (o.overlap, o.colorization); + } + BrushKind::Pattern(p) => { + let o: PatternOptions = serde_json::from_value(v)?; + (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = + (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + } + BrushKind::Bristle(_) => {} + } + Ok(()) + } +} + +impl Brush { + /// The brush as a stroke whose own settings are `options` draws it: each field of + /// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization` + /// object changes only the fields it gives), and the values are kept within their ranges + /// ([`Brush::sanitize`]). Fields the type does not take are passed over. An error when a value + /// is of the wrong kind. + pub fn with_stroke_options(&self, options: &serde_json::Map) -> Result { + let keys = self.kind.stroke_option_keys(); + let mut values = self.kind.option_values(); + let Some(o) = values.as_object_mut() else { return Ok(self.clone()) }; + for (k, v) in options { + if !keys.contains(&k.as_str()) { + continue; + } + match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) { + (Some(inner), Some(fields)) if k == "colorization" => { + for (f, fv) in fields { + inner.insert(f.clone(), fv.clone()); + } + } + _ => { + o.insert(k.clone(), v.clone()); + } + } + } + // A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it. + if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut) + && c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift") + && c.get("key").is_none_or(serde_json::Value::is_null) + { + let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK); + c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?); + } + let mut b = self.clone(); + b.kind.set_option_values(values).map_err(|e| e.to_string())?; + b.sanitize(); + Ok(b) + } + + /// The stroke options of `options` that make the brush draw differently: each field of + /// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs + /// from the brush's own, with that value (kept within its range). An error for a field the + /// type does not take and for a value of the wrong kind. + pub fn stroke_options_that_differ( + &self, + options: &serde_json::Map, + ) -> Result, String> { + let keys = self.kind.stroke_option_keys(); + if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) { + return Err(if keys.is_empty() { + format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase()) + } else { + format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", ")) + }); + } + let edited = self.with_stroke_options(options)?.kind.option_values(); + let own = self.kind.option_values(); + Ok(keys + .iter() + .filter_map(|k| { + let v = edited.get(*k)?; + (own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone())) + }) + .collect()) + } +} + // ---------- library ---------- /// The brush library of `doc`: its stored brushes, or the defaults when it has none. @@ -842,8 +1021,22 @@ fn tolerance(scale: f64) -> f64 { /// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id /// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush, /// and what they draw by name that would draw one is left out ([`leave_out_brushed`]). -/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). +/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own +/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values +/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is. pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec { + let edited; + let brush = if stroke.brush_options.is_empty() { + brush + } else { + match brush.with_stroke_options(&stroke.brush_options) { + Ok(b) => { + edited = b; + &edited + } + Err(_) => brush, + } + }; let w = if stroke.width > 0.0 { stroke.width } else { 1.0 }; let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index de178c76ac..cb4e560ff5 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1,3 +1,4 @@ +use serde_json::json; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes}; @@ -2037,3 +2038,63 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() { } } } + +/// `options` as a stroke's own brush settings. +fn with_options(options: serde_json::Value) -> StrokeLayer { + StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) } +} + +#[test] +fn a_strokes_own_options_change_its_art_and_leave_the_brush() { + let doc = Document::new(1.0, 1.0); + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let path = line(20.0, 50.0, 220.0, 50.0); + let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0}))); + assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half)); + assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush"); + let BrushKind::Art(a) = &brush.kind else { panic!("art brush") }; + assert_eq!(a.width, 100.0, "the brush keeps its width"); + // A calligraphic stroke's own size and angle. + let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0}))); + assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib)); + // A pattern stroke's own scale doubles the tiles across it. + let pattern = pattern_brush(PatternFit::Stretch, false); + let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height(); + let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height(); + assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}"); +} + +#[test] +fn stroke_options_are_checked_and_kept_within_their_ranges() { + let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // Out of range: clamped; equal to the brush's own value: left out. + let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0})); + // A field the type does not take, and a value of the wrong kind, are errors. + assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle")); + assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err()); + let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err()); + assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty()); + // A colorization object changes only the fields it gives: Hue Shift keeps the key it has. + let key = Color::rgb(0.0, 0.0, 1.0); + let hue = Brush { + name: "h".into(), + kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }), + }; + let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap(); + assert_eq!(tints.kind.colorization(), Colorization::Tints); + let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + assert!(back.is_empty(), "the brush's own colorization: {back:?}"); + // Hue Shift without a key takes the art's main color, as brush.options gives it. + let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap(); + let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK); + assert_eq!(keyless["colorization"]["method"], json!("hueShift")); + assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap()); + // Settings that do not read draw the brush as it is. + let doc = Document::new(1.0, 1.0); + let path = line(20.0, 50.0, 220.0, 50.0); + let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]}))); + assert!(near(bounds(&odd).height(), 4.0, 1e-6)); +} diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index f8a58758d8..5e07dc6cde 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -71,6 +71,11 @@ pub struct StrokeLayer { /// Brush applied to the stroke (by brush name). #[serde(default, skip_serializing_if = "Option::is_none")] pub brush: Option, + /// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush + /// definition fields, by their `brush.options` names, that replace the brush's values on this + /// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub brush_options: serde_json::Map, #[serde(default = "one", skip_serializing_if = "crate::skip::is_one")] pub opacity: f32, #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -170,6 +175,7 @@ impl StrokeLayer { arrow_scale: (100.0, 100.0), profile: None, brush: None, + brush_options: serde_json::Map::new(), opacity: 1.0, blend: BlendMode::Normal, visible: true, diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 1046cada1c..4a9339f2ca 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -33,8 +33,8 @@ mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; use brushes::{ - brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art, - brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, + brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, + brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; @@ -166,6 +166,15 @@ pub fn specs() -> Vec { has_doc, brush_options ), + cmd!( + "brush.objectOptions", + "Options of Selected Object…", + [], + None, + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle, roundness, size, variation, modes; scatter size, spacing, scatter, rotation, modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, or stroke.setAdvanced with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + has_doc, + brush_object_options + ), cmd!( "object.expandBrush", "Expand Brush Strokes", diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 7fd8c9aa9a..007e47f5ce 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -1,7 +1,7 @@ use super::{ AppearanceItem, Arc, BTreeSet, Bristle, Brush, BrushKind, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, Result, Session, Value, anchor, bad, brush, check_numbers, find_command, id_param, ids_json, json, name_param, names_param, ok, roots, selection_art, set_unknown, - str_param, + str_param, switch_or, }; // ---------- brushes ---------- @@ -57,6 +57,8 @@ pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: st.width = 1.0; } st.brush = Some(name.to_string()); + // The path's own brush settings (Options of Selected Object) go with the brush they set. + st.brush_options.clear(); } } } @@ -85,6 +87,7 @@ pub(super) fn brush_remove(s: &mut Session, p: &Value) -> Result { for it in &mut n.appearance.items { if let AppearanceItem::Stroke(st) = it { st.brush = None; + st.brush_options.clear(); } } } @@ -129,13 +132,17 @@ fn merge(base: &mut Value, patch: &Value) { } } -/// Sets brush `to` on the strokes in `items` that paint with brush `from`. +/// Sets brush `to` on the strokes in `items` that paint with brush `from`. A renamed brush keeps +/// each stroke's own settings for it; a stroke left without a brush loses them. fn set_stroke_brush(items: &mut [AppearanceItem], from: &str, to: Option<&str>) { for it in items { if let AppearanceItem::Stroke(st) = it && st.brush.as_deref() == Some(from) { st.brush = to.map(str::to_string); + if to.is_none() { + st.brush_options.clear(); + } } } } @@ -494,6 +501,85 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "name": out })) } +/// Options of Selected Object: set the brush settings of the brushed strokes of the selected paths +/// (or `ids`) on those strokes only, leaving the brush as it is. `params` adds to each stroke's +/// own settings, `reset` clears them; without either, nothing changes and the settings are given. +pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result { + const C: &str = "brush.objectOptions"; + let params = match p.get("params") { + None | Some(Value::Null) => serde_json::Map::new(), + Some(Value::Object(o)) => o.clone(), + Some(_) => { + let key = "params"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let reset = switch_or(p, "reset", false, C)?; + if reset && !params.is_empty() { + return Err(bad(C, "give `params` or `reset`, not both")); + } + let d = &s.doc()?.doc; + let lib = brush::library(d); + let ids = brush_targets(d, &roots(s, p)?); + // Each brushed stroke: its path, its place in the appearance, its brush and its settings now. + let mut strokes = vec![]; + for id in &ids { + let Some(n) = d.node(*id) else { continue }; + for (i, it) in n.appearance.items.iter().enumerate() { + let AppearanceItem::Stroke(st) = it else { continue }; + if let Some(b) = st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) { + strokes.push((*id, i, b, &st.brush_options)); + } + } + } + let Some(&(_, _, first, _)) = strokes.first() else { return Err(bad(C, "no path painted with a brush is selected")) }; + if strokes.iter().any(|(_, _, b, _)| b.kind.type_id() != first.kind.type_id()) { + return Err(bad(C, "the selected paths are painted with brushes of different types")); + } + // Only a bristle brush has none. + if first.kind.stroke_option_keys().is_empty() { + return Err(bad(C, "a bristle brush has no options of its own on a path")); + } + let out: Vec = ids.iter().copied().filter(|id| strokes.iter().any(|(s, ..)| s == id)).collect(); + // Without params or reset the settings are only given: nothing is normalized or changed. + if !reset && params.is_empty() { + let keys = first.kind.stroke_option_keys(); + let own: serde_json::Map = + strokes[0].3.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + return Ok(json!({ "ids": ids_json(&out), "changed": [], "options": own })); + } + let mut changes = vec![]; + let mut options = None; + for (id, i, b, own) in &strokes { + let next = if reset { + serde_json::Map::new() + } else { + // Settings saved for another type of brush are left out. + let keys = b.kind.stroke_option_keys(); + let mut merged: serde_json::Map = + own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + merged.extend(params.clone()); + b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? + }; + options.get_or_insert_with(|| next.clone()); + if &next != *own { + changes.push((*id, *i, next)); + } + } + let changed: Vec = ids.iter().copied().filter(|id| changes.iter().any(|(c, ..)| c == id)).collect(); + if !changes.is_empty() { + s.edit("Options of Selected Object", |d, _| { + for (id, i, next) in changes { + if let Some(AppearanceItem::Stroke(st)) = d.node_mut(id).and_then(|n| n.appearance.items.get_mut(i)) { + st.brush_options = next; + } + } + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() })) +} + /// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it /// places them; `brush.replaceArt` reads a group of that name as that tile. const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index f694a2b144..99f73b564e 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -658,6 +658,7 @@ fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) { } s.profile = None; s.brush = None; + s.brush_options.clear(); } if !starts { s.start_arrow = None; diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 5922787723..40ff3e1592 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -628,10 +628,12 @@ fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof } /// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the -/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// effect colors ([`map_effect_colors`]), the Hue Shift key colors of strokes' own brush settings +/// ([`map_stroke_brush_keys`]), the series paints and label styles a graph keeps /// ([`map_graph_colors`]) and the art of every opacity mask. fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { map_effect_colors(&mut n.appearance, f); + map_stroke_brush_keys(&mut n.appearance, f); if let Some(e) = n.extras_if_any() { if let Some(g) = e.graph.as_deref_mut() { map_graph_colors(g, f); @@ -647,6 +649,23 @@ fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proo } } +/// `f` applied to the Hue Shift key color of each stroke's own brush settings in appearance `a` +/// (Options of Selected Object, `colorization.key` of [`StrokeLayer::brush_options`]); a key +/// that does not read is left as it is. +/// +/// [`StrokeLayer::brush_options`]: vectorcraft_doc::StrokeLayer::brush_options +fn map_stroke_brush_keys(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for it in &mut a.items { + let vectorcraft_doc::AppearanceItem::Stroke(st) = it else { continue }; + let Some(c) = st.brush_options.get_mut("colorization").and_then(Value::as_object_mut) else { continue }; + let Some(key) = c.get("key").and_then(|k| serde_json::from_value::(k.clone()).ok()) else { continue }; + let n = f(&key, None); + if n != key { + c.insert("key".into(), json!(n)); + } + } +} + /// Whether art color `c` is the Hue Shift key color `key`, with the tolerance the brush's /// colorization matches it with. fn matches_key(c: &Color, key: &Color) -> bool { diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 43975fe4e4..6e8bbc2448 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -1147,21 +1147,27 @@ fn random_brushes_baked<'a>( std::borrow::Cow::Owned(def) } -/// Does brush `name` of `brushes` draw different art for different points: a calligraphic or -/// scatter brush with Random variation, or a bristle brush? -fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str) -> bool { +/// Does brush `name` of `brushes`, with the stroke's own brush settings `options`, draw different +/// art for different points: a calligraphic or scatter brush with Random variation, or a bristle +/// brush? +fn draws_random_art(brushes: &[vectorcraft_brush::Brush], name: &str, options: &serde_json::Map) -> bool { use vectorcraft_brush::{BrushKind, Variation}; - brushes.iter().find(|b| b.name == name).is_some_and(|b| match &b.kind { + let Some(brush) = brushes.iter().find(|b| b.name == name) else { return false }; + let edited = if options.is_empty() { None } else { brush.with_stroke_options(options).ok() }; + let b = edited.as_ref().unwrap_or(brush); + match &b.kind { BrushKind::Calligraphic(c) => c.modes().contains(&Variation::Random), BrushKind::Scatter(s) => s.modes().contains(&Variation::Random), BrushKind::Bristle(_) => true, BrushKind::Art(_) | BrushKind::Pattern(_) => false, - }) + } } /// Is `n` a path with a visible stroke whose brush varies at random ([`draws_random_art`])? fn random_brushed(brushes: &[vectorcraft_brush::Brush], n: &Node) -> bool { - let random = |st: &vectorcraft_doc::appearance::StrokeLayer| st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b)); + let random = |st: &vectorcraft_doc::appearance::StrokeLayer| { + st.visible && st.brush.as_deref().is_some_and(|b| draws_random_art(brushes, b, &st.brush_options)) + }; matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if random(st))) } diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 879767d8be..29fbf97fac 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -769,6 +769,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut arrow_scale, profile, brush, + brush_options, opacity, blend, visible, @@ -781,7 +782,11 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut bearing: _, rotation: _, } = m; - give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); + // A stroke's own brush settings go with the brush they set: a new brush takes the model's. + if a.brush != b.brush { + n.brush_options = brush_options.clone(); + } } _ => {} } diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 09ae0b8e41..369c8ef8e5 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -542,6 +542,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) }; arrows_and_profile(st); if let Some(b) = &brush { + // The path's own brush settings (Options of Selected Object) go with the brush they set. + if st.brush != *b { + st.brush_options.clear(); + } st.brush = b.clone(); } Ok(()) diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index bc4ce76c83..b313ec64c3 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -81,6 +81,116 @@ fn apply_and_remove_brush_with_undo() { assert!(s.execute("brush.apply", &json!({"name": "Nope"})).is_err()); } +/// The own brush settings of the first stroke of `id`. +fn own_options(s: &Session, id: NodeId) -> Value { + Value::Object(node(s, id).appearance.stroke().map(|st| st.brush_options.clone()).unwrap_or_default()) +} + +/// The height of the brush art of `id`, drawn along a level line. +fn art_height(s: &Session, id: NodeId) -> f64 { + let d = &s.doc().unwrap().doc; + vectorcraft_brush::pieces_bounds(&vectorcraft_brush::node_pieces(d, &node(s, id)).unwrap()).unwrap().height() +} + +#[test] +fn options_of_selected_object_change_one_path_and_leave_the_brush() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + select(&mut s, &[a, b]); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + let width = s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"].clone(); + select(&mut s, &[a]); + let steps = undo_steps(&s); + let r = s.execute("brush.objectOptions", &json!({"params": {"width": 50, "flip_along": false}})).unwrap(); + assert_eq!(r["changed"], json!([a.0])); + assert_eq!(own_options(&s, a), json!({"width": 50.0}), "flip_along equals the brush's own value and is dropped"); + assert_eq!(own_options(&s, b), json!({})); + assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["width"], width, "the brush keeps its width"); + assert_eq!(undo_steps(&s), steps + 1); + assert!((art_height(&s, a) * 2.0 - art_height(&s, b)).abs() < 1e-6, "{} vs {}", art_height(&s, a), art_height(&s, b)); + // The same settings again, and a call without params, change nothing and add no undo step. + assert_eq!(s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap()["changed"], json!([])); + assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"width": 50.0})); + assert_eq!(undo_steps(&s), steps + 1); + // An edit of the brush reaches the settings the path does not set. + s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 200, "flip_across": true}})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + // The settings are saved in the native file. + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let st = back.node(a).and_then(|n| n.appearance.stroke().cloned()).unwrap(); + assert_eq!(Value::Object(st.brush_options), json!({"width": 50.0})); + // Undo puts the path back on the brush's settings. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + // Reset clears them, and so do applying a brush and removing it. + s.execute("brush.objectOptions", &json!({"reset": true})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("brush.remove", &json!({})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + // Stroke Options' brush change clears them as well, and keeping the same brush keeps them. + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("stroke.setAdvanced", &json!({"brush": "Arrow"})).unwrap(); + assert_eq!(own_options(&s, a), json!({"overlap": true})); + s.execute("stroke.setAdvanced", &json!({"brush": null})).unwrap(); + assert_eq!(own_options(&s, a), json!({})); + // Asking for the settings changes nothing, even when the brush has come to equal them. + s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap(); + s.execute("brush.objectOptions", &json!({"params": {"overlap": true}})).unwrap(); + s.execute("brush.options", &json!({"name": "Arrow", "params": {"overlap": true}})).unwrap(); + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({})).unwrap()["options"], json!({"overlap": true})); + assert_eq!(own_options(&s, a), json!({"overlap": true})); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn options_of_selected_object_keys_convert_with_the_document() { + let mut s = session(); + let a = line(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap(); + let key = json!({"model": "rgb", "r": 0.2, "g": 0.6, "b": 0.3}); + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"colorization": {"method": "hueShift", "key": key}}})).unwrap(); + assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("rgb")); + s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert_eq!(own_options(&s, a)["colorization"]["key"]["model"], json!("cmyk"), "{}", own_options(&s, a)); +} + +#[test] +fn options_of_selected_object_refuse_what_they_cannot_set() { + let mut s = session(); + let a = line(&mut s); + let c = line(&mut s); + let plain = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap(); + s.execute("brush.apply", &json!({"name": "3 pt. Round", "ids": [c.0]})).unwrap(); + let steps = undo_steps(&s); + let err = |s: &mut Session, p: Value| s.execute("brush.objectOptions", &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [plain.0], "params": {"width": 50}})).contains("brush")); + assert!(err(&mut s, json!({"ids": [a.0, c.0], "params": {"width": 50}})).contains("different types")); + assert!(err(&mut s, json!({"ids": [a.0], "params": {"angle": 10}})).contains("angle")); + assert!(!err(&mut s, json!({"ids": [a.0], "params": {"width": "wide"}})).is_empty()); + assert!(!err(&mut s, json!({"ids": [a.0], "params": [1]})).is_empty()); + assert!(err(&mut s, json!({"ids": [a.0], "params": {"width": 50}, "reset": true})).contains("reset")); + assert!(err(&mut s, json!({"ids": [a.0], "reset": "yes"})).contains("reset")); + s.execute("brush.apply", &json!({"name": "Bristle Round", "ids": [c.0]})).unwrap(); + let steps_bristle = undo_steps(&s); + assert!(err(&mut s, json!({"ids": [c.0], "params": {"size": 2}})).contains("bristle")); + assert_eq!(undo_steps(&s), steps_bristle); + assert_eq!(steps + 1, steps_bristle, "only the bristle brush's apply added a step"); + // Values outside their ranges are clamped, as brush.options clamps them. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 1e308}})).unwrap(); + assert_eq!(own_options(&s, a), json!({"width": 1000.0})); +} + #[test] fn apply_adds_a_stroke_when_missing_and_reaches_into_groups() { let mut s = session(); diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 9a4cb7d138..3bfe6039fa 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -454,6 +454,24 @@ fn a_stroke_weight_change_leaves_each_members_own_fill_and_stroke_colour() { assert_eq!((fill(&s, a), fill(&s, c)), (a_fill, c_fill)); } +#[test] +fn a_brush_change_clears_each_members_own_brush_settings_and_other_changes_keep_them() { + let mut s = session(); + let [a, b, c, ..] = squares(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0, c.0]})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 50}})).unwrap(); + let own = |s: &Session, id: NodeId| Value::Object(node(s, id).appearance.stroke().unwrap().brush_options.clone()); + assert_eq!(own(&s, b), json!({"width": 50.0})); + start(&mut s, a, json!({})); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + assert_eq!(own(&s, b), json!({"width": 50.0}), "a weight change keeps the copy's own settings"); + s.execute("brush.apply", &json!({"name": "Diamonds"})).unwrap(); + for id in [a, b, c] { + assert_eq!(node(&s, id).appearance.stroke().unwrap().brush.as_deref(), Some("Diamonds")); + assert_eq!(own(&s, id), json!({}), "the settings for the old brush go with it"); + } +} + #[test] fn a_fill_colour_change_reaches_the_fills_and_not_the_strokes() { let mut s = session(); diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 3788185ae6..5b680b02e9 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -1313,6 +1313,28 @@ fn a_random_brush_in_the_tile_art_draws_every_tile_alike() { } } +#[test] +fn a_path_set_to_random_by_its_own_brush_options_draws_every_tile_alike() { + // The brush scatters at fixed values; the tile path's own settings (Options of Selected + // Object) make it scatter at random, so the expanded tiles must still match the canvas. + let mut s = session(); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 12, "height": 12}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + run(&mut s, "brush.apply", json!({"name": "Confetti"})); + run(&mut s, "brush.options", json!({"name": "Confetti", "params": {"modes": ["fixed", "fixed", "fixed", "fixed"]}})); + run(&mut s, "brush.objectOptions", json!({"ids": [tile], "params": {"modes": ["random", "random", "random", "random"]}})); + run(&mut s, "object.pattern.make", json!({"ids": [tile], "name": "Confetti", "width": 60, "height": 60, "edit": false})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "edit.clear", json!({})); + run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 160, "height": 160})); + run(&mut s, "paint.setFill", json!({"swatch": "Confetti"})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let before = render(&s); + expand_to_tiles(&mut s); + assert_eq!(differing(&before, &render(&s), 64), 0, "every tile as on the canvas"); +} + #[test] fn roughen_in_the_tile_art_of_a_scaled_pattern_keeps_its_detail() { // Roughen's detail is per inch: the canvas roughens the 10 pt square and scales the tile, so diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index fce3742d11..2713109b7f 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -604,6 +604,17 @@ fn structured_junk() { ("brush.options", json!({"name": "Arrow", "params": {"width": -5, "direction": "diagonal", "flip_along": "yes"}})), ("brush.options", json!({"name": "Chain", "params": {"scale": 1e308, "spacing": -1e308, "fit": "approximate", "flip_across": true}})), ("brush.options", json!({"name": "Chain", "params": {"scale": 0, "spacing": 1e308, "fit": "nope", "side": null}})), + ("brush.apply", json!({"name": "Chain", "id": 2})), + ( + "brush.objectOptions", + json!({"id": 2, "params": {"scale": 1e308, "spacing": -1e308, "fit": "approximate", "colorization": {"method": "hueShift"}}}), + ), + ("brush.objectOptions", json!({"id": 2, "params": {"scale": "x", "fit": "nope", "side": null}})), + ( + "brush.objectOptions", + json!({"id": 2, "params": {"colorization": {"method": "hueShift", "key": {"model": "rgb", "r": 1e308, "g": -1e308, "b": 0}}}}), + ), + ("brush.objectOptions", json!({"ids": [1e308, -1], "params": {}, "reset": true})), ("path.curvature", json!({"points": [{"x": 0, "y": 0}]})), ("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 1000, "x": 0, "y": 0})), ("path.curvatureEdit", json!({"id": 2, "op": "move", "anchor": 0, "x": 1e308, "y": -1e308})), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c41e6fe86f..cb63f15b71 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -903,6 +903,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), + ( + "ui.brushObjectOptions", + "Options of Selected Object…", + "", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened, and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + ), ( "ui.graphicStyleOptions", "Graphic Style Options…", diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 8bc0e66a2e..62d4a2e368 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -472,6 +472,13 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("widthMode".into(), json!(m.id())); } }); + // A path sets its own width, flips, overlap and colorization, not how the art scales or runs. + if d.bool(super::brush_options::OBJECT) { + flips(ui, d); + ui.add_space(4.0); + super::form::check(ui, d, "overlap", tl!("Overlap")); + return; + } ui.add_space(4.0); widgets::section_header(ui, tl!("Brush Scale Options")); let scales = [ @@ -532,8 +539,11 @@ fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { slider_row(ui, d, "scale", tl!("Scale:"), PatternBrush::SCALE_RANGE); widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| number(ui, d, "spacing", PatternBrush::SPACING_RANGE, "%", true)); ui.add_space(6.0); - tiles(ui, d); - ui.add_space(6.0); + // The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization. + if !d.bool(super::brush_options::OBJECT) { + tiles(ui, d); + ui.add_space(6.0); + } flips(ui, d); widgets::section_header(ui, tl!("Fit")); let fits = [("stretch", tl!("Stretch to fit")), ("addSpace", tl!("Add space to fit")), ("approximate", tl!("Approximate path"))]; diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index bcc880958a..501ed7ec8d 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -17,10 +17,17 @@ //! New Brush opens the dialog for a brush that does not exist yet ([`open_new`]), with `__create` //! and, for dropped art, `__ids`: OK runs `brush.new` instead, which gives a name another brush has //! a number, and Cancel adds nothing. +//! +//! The panel menu's Options of Selected Object opens the dialog on the brush of the first selected +//! brushed path, with that path's own settings ([`open_object`]), with `__object`, `__targets` (the +//! brushed paths) and `__opened` (the values it opened with). It has no name, and of the Art and +//! Pattern brush options only those a path can set for itself. OK runs `brush.objectOptions` with +//! the values changed since it opened: the paths change and the brush stays as it is. use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{Bristle, Brush, BrushKind, Calligraphic, Variation}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; use super::swatch_options::{grid, label}; use super::{DialogSpec, brush_art_options, form}; @@ -39,6 +46,15 @@ const CREATE: &str = "__create"; /// The field of such a dialog holding the ids of the art dropped on the Brushes panel. const IDS: &str = "__ids"; +/// The field of a Brush Options dialog that Options of Selected Object opened. +pub(super) const OBJECT: &str = "__object"; + +/// The field of such a dialog holding the brushed paths it sets. +const TARGETS: &str = "__targets"; + +/// The field of such a dialog holding the `brush.objectOptions` params it opened with. +const OPENED: &str = "__opened"; + /// Calligraphic values: (field, label, suffix, decimals), in [`Calligraphic::RANGES`] order. const CALLI: [(&str, &str, &str, usize); 3] = [("angle", "Angle:", "°", 0), ("roundness", "Roundness:", "%", 0), ("size", "Size:", " pt", 1)]; @@ -73,6 +89,9 @@ const NIB_W: f32 = 120.0; const STROKE_W: f32 = 400.0; fn heading(d: &Dialog) -> String { + if d.bool(OBJECT) { + return tl!("Options of Selected Object").into(); + } match d.str("__type").as_str() { "bristle" => tl!("Bristle Brush Options").into(), "calligraphic" => tl!("Calligraphic Brush Options").into(), @@ -146,6 +165,96 @@ fn target(app: &VectorcraftApp) -> Option { selected.or_else(|| vectorcraft_brush::current(&st.doc)) } +/// The brush that the first brushed stroke of path `id` paints with, in library `lib`. +fn stroke_brush<'a>(app: &VectorcraftApp, lib: &'a [Brush], id: NodeId) -> Option<&'a Brush> { + let n = app.session.active()?.doc.node(id)?; + n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Stroke(st) => st.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)), + AppearanceItem::Fill(_) => None, + }) +} + +/// Can Options of Selected Object open: does a selected path or compound path (or one in a +/// selected group, but not a path inside a compound path, as `brush.objectOptions` takes them) +/// paint with a brush, are all their brushes of one type, and can a path set options of its own +/// for that type? These are the selections `brush.objectOptions` takes. +pub fn object_available(app: &VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let ids = st.selection.subjects(); + if ids.is_empty() { + return false; + } + let lib = vectorcraft_brush::library(&st.doc); + let doc = &st.doc; + // The brush of every brushed stroke of the paths the command sets. + let mut brushes: Vec<&Brush> = vec![]; + for id in ids { + let Some(n) = doc.node(*id) else { continue }; + n.walk(&mut |c| { + let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); + let in_compound = doc.parent_of(c.id).and_then(|p| doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if !own || in_compound { + return; + } + for i in &c.appearance.items { + if let AppearanceItem::Stroke(s) = i + && let Some(b) = s.brush.as_deref().and_then(|name| lib.iter().find(|b| b.name == name)) + { + brushes.push(b); + } + } + }); + } + let Some(first) = brushes.first() else { return false }; + !first.kind.stroke_option_keys().is_empty() && brushes.iter().all(|b| b.kind.type_id() == first.kind.type_id()) +} + +/// Open Options of Selected Object: the Brush Options of the brush the first selected brushed path +/// paints with, at that path's own settings, without the name and with only the options a path can +/// set for itself. +pub fn open_object(app: &mut VectorcraftApp) -> Result { + let r = app.run("brush.objectOptions", json!({}))?; + let targets = r["ids"].clone(); + let first = targets.get(0).and_then(Value::as_u64).map(NodeId).ok_or("no path painted with a brush is selected")?; + let lib = vectorcraft_brush::library(&app.session.active().ok_or("no document open")?.doc); + let b = stroke_brush(app, &lib, first).ok_or("no path painted with a brush is selected")?; + let own: Map = serde_json::from_value(r["options"].clone()).unwrap_or_default(); + let edited = b.with_stroke_options(&own)?; + let def = serde_json::to_value(&edited).map_err(|e| e.to_string())?; + let mut f = fields(&edited, def)?; + f.insert("__brush".into(), json!(b.name)); + f.insert(OBJECT.into(), json!(true)); + f.insert(TARGETS.into(), targets); + let mut d = Dialog { kind: KIND.into(), fields: f }; + let opened = object_params(&d, b.kind.stroke_option_keys()); + d.fields.insert(OPENED.into(), Value::Object(opened)); + d.fields.insert("__keys".into(), json!(b.kind.stroke_option_keys())); + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +/// The fields' `brush.options` params that a path can set for itself (`keys`). +fn object_params(d: &Dialog, keys: &[&str]) -> Map { + match params(d) { + Value::Object(p) => p.into_iter().filter(|(k, _)| keys.contains(&k.as_str())).collect(), + _ => Map::new(), + } +} + +/// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the +/// values changed since it opened. The dialog closes when they are set. +fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let keys: Vec = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); + let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); + let changed: Map = object_params(d, &keys).into_iter().filter(|(k, v)| opened.get(k) != Some(v)).collect(); + let r = app.run("brush.objectOptions", json!({ "ids": d.fields.get(TARGETS).cloned().unwrap_or_default(), "params": changed })); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// Open the Brush Options of a new brush of type `ty` (`calligraphic` | `scatter` | `art` | /// `bristle` | `pattern`), the second step of New Brush. The fields start from the type's default /// values and the name "New Brush", numbered when another brush has it. A scatter or art @@ -240,7 +349,13 @@ fn create(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// OK: make the new brush when New Brush opened the dialog, else edit the brush. fn ok(app: &mut VectorcraftApp, d: &Dialog) -> Result { - if d.bool(CREATE) { create(app, d) } else { confirm(app, d) } + if d.bool(CREATE) { + create(app, d) + } else if d.bool(OBJECT) { + confirm_object(app, d) + } else { + confirm(app, d) + } } /// The value of field `key` within `range`. @@ -279,13 +394,16 @@ fn params(d: &Dialog) -> Value { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - grid(ui, |ui| { - label(ui, tl!("Name:")); - let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; - form::text_edit_limited(ui, d, "name", 240.0, max); - ui.end_row(); - }); - ui.add_space(10.0); + // Options of Selected Object sets a path's settings, not the brush, so it has no name. + if !d.bool(OBJECT) { + grid(ui, |ui| { + label(ui, tl!("Name:")); + let max = if d.str("__type") == "bristle" { Bristle::MAX_NAME_CHARS } else { usize::MAX }; + form::text_edit_limited(ui, d, "name", 240.0, max); + ui.end_row(); + }); + ui.add_space(10.0); + } match d.str("__type").as_str() { "bristle" => bristle_body(app, ui, d), "calligraphic" => calligraphic_body(app, ui, d), diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 9ff55da454..e997e92805 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -862,3 +862,88 @@ fn art_width_and_pattern_scale_have_sliders() { let shown = tree(|ui| super::super::show(&mut app, ui.ctx())); assert_eq!(slider_value(&shown, "Scale:"), (Some(100.0), Some(1.0), Some(10000.0), Some("100%".into()))); } + +/// A level line, selected, painted with brush `brush`. +fn brushed_line(app: &mut VectorcraftApp, y: f64, brush: &str) -> u64 { + let id = app.run("shape.line", json!({"x1": 20, "y1": y, "x2": 220, "y2": y})).unwrap()["id"].as_u64().unwrap(); + app.run("brush.apply", json!({"name": brush, "ids": [id]})).unwrap(); + id +} + +/// The own brush settings of the first stroke of path `id`. +fn own_options(app: &VectorcraftApp, id: u64) -> Value { + let st = app.session.active().unwrap().doc.node(NodeId(id)).and_then(|n| n.appearance.stroke().cloned()).unwrap(); + Value::Object(st.brush_options) +} + +fn select(app: &mut VectorcraftApp, ids: &[u64]) { + app.run("select.set", json!({ "ids": ids })).unwrap(); +} + +#[test] +fn options_of_selected_object_set_one_paths_art_brush_settings() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + let b = brushed_line(&mut app, 100.0, "Arrow"); + select(&mut app, &[a]); + assert!(object_available(&app)); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Options of Selected Object", "Width:", "Flip Along", "Flip Across", "Overlap", "Colorization", "OK"] { + assert!(text.contains(label), "{label} in {text}"); + } + for label in ["Name:", "Brush Scale Options", "Direction:"] { + assert!(!text.contains(label), "{label} in {text}"); + } + set(&mut app, json!({"width": 50})); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); + assert_eq!(own_options(&app, b), json!({})); + assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(100.0), "the brush keeps its width"); + // Opened again, it shows the path's own width, and OK without a change changes nothing. + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 50.0); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"width": 50.0})); +} + +#[test] +fn options_of_selected_object_show_what_a_path_can_set_for_each_type() { + let mut app = app(); + // Calligraphic: OK without a change leaves the path on the brush's settings. + let c = brushed_line(&mut app, 40.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Angle:", "Roundness:", "Size:"] { + assert!(text.contains(label), "{label} in {text}"); + } + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, c), json!({})); + // Pattern: scale, spacing, flips and fit, not the tiles. + let p = brushed_line(&mut app, 80.0, "Diamonds"); + select(&mut app, &[p]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let text = shown(&mut app); + for label in ["Scale:", "Spacing:", "Fit", "Flip Along"] { + assert!(text.contains(label), "{label} in {text}"); + } + assert!(!text.contains("Side Tile"), "{text}"); + set(&mut app, json!({"scale": 200})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, p), json!({"scale": 200.0})); + // Bristle brushes, nothing selected and two brush types are refused. + let r = brushed_line(&mut app, 120.0, "Bristle Round"); + select(&mut app, &[r]); + assert!(!object_available(&app)); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + select(&mut app, &[c, p]); + assert!(!object_available(&app), "the menu item is off for two brush types"); + assert!(app.run("ui.brushObjectOptions", json!({})).is_err()); + assert!(app.ui.dialog.is_none()); + select(&mut app, &[p, r]); + assert!(!object_available(&app), "the menu item is off for a pattern and a bristle brush"); + app.run("select.none", json!({})).unwrap(); + assert!(!object_available(&app)); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8534505172..f1e8ec1cb7 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -347,6 +347,8 @@ font-technology Variable Променливи Brush Definition Дефиниция на четка Brush Libraries Библиотеки с четки Brush Options… Опции за четката… + Options of Selected Object… Опции на избрания обект… + Options of Selected Object Опции на избрания обект Brush Strokes Щрихи с четка Brushes Четки Built-in Libraries Вградени библиотеки diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 1a1b1bdbff..4471934ea8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3362,6 +3362,8 @@ theme Appearance Izgled Break Link to Symbol Prekini vezu sa simbolom Brush Definition Definicija četkice Brush Options… Opcije četkice… + Options of Selected Object… Opcije odabranog objekta… + Options of Selected Object Opcije odabranog objekta Current Brush Trenutna četkica Current Symbol Trenutni simbol Delete Brush Izbriši četkicu diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a7fcccfe2f..562b519a4d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -582,6 +582,12 @@ antiAlias Sharp Nítid Brush Libraries Menu Menú de biblioteques de pinzells Brush Library Biblioteca de pinzells Brush Options… Opcions del pinzell… + Options of Selected Object… Opcions de l’objecte seleccionat… + Options of Selected Object Opcions de l’objecte seleccionat +@msg no path painted with a brush is selected no hi ha cap traçat pintat amb un pinzell seleccionat +@msg the selected paths are painted with brushes of different types els traçats seleccionats estan pintats amb pinzells de tipus diferents +@msg give `params` or `reset`, not both indiqueu `params` o `reset`, no tots dos +@msg a bristle brush has no options of its own on a path un pinzell de cerres no té opcions pròpies en un traçat Brush Scale Options Opcions d’escala del pinzell Brush Size Mida del pinzell Brush Strokes Traços del pinzell diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index acab417f65..79856ad8dc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3412,6 +3412,12 @@ theme Appearance Motiv Break Link to Symbol Zrušit propojení se symbolem Brush Definition Definice štětce Brush Options… Možnosti štětce… + Options of Selected Object… Možnosti vybraného objektu… + Options of Selected Object Možnosti vybraného objektu +@msg no path painted with a brush is selected není vybrána žádná cesta malovaná štětcem +@msg the selected paths are painted with brushes of different types vybrané cesty jsou malovány štětci různých typů +@msg give `params` or `reset`, not both zadejte `params` nebo `reset`, ne obojí +@msg a bristle brush has no options of its own on a path štětinový štětec nemá na cestě vlastní možnosti Current Brush Aktuální štětec Current Symbol Aktuální symbol Delete Brush Odstranit štětec diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9e74a00a64..02a92cbd40 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3754,6 +3754,12 @@ theme Appearance Udseende Break Link to Symbol Bryd link til symbol Brush Definition Penseldefinition Brush Options… Penselindstillinger… + Options of Selected Object… Indstillinger for markeret objekt… + Options of Selected Object Indstillinger for markeret objekt +@msg no path painted with a brush is selected ingen sti malet med en pensel er markeret +@msg the selected paths are painted with brushes of different types de markerede stier er malet med pensler af forskellige typer +@msg give `params` or `reset`, not both angiv `params` eller `reset`, ikke begge +@msg a bristle brush has no options of its own on a path en børstepensel har ingen egne indstillinger på en sti Current Brush Aktuel pensel Current Symbol Aktuelt symbol Delete Brush Slet pensel diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 527b1c89e8..830635f8b1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -335,6 +335,12 @@ font-technology Variable Variabel Brush Definition Pinseldefinition Brush Libraries Pinsel-Bibliotheken Brush Options… Pinseloptionen… + Options of Selected Object… Optionen für ausgewähltes Objekt… + Options of Selected Object Optionen für ausgewähltes Objekt +@msg no path painted with a brush is selected kein mit einem Pinsel gemalter Pfad ausgewählt +@msg the selected paths are painted with brushes of different types die ausgewählten Pfade sind mit Pinseln verschiedener Typen gemalt +@msg give `params` or `reset`, not both `params` oder `reset` angeben, nicht beides +@msg a bristle brush has no options of its own on a path ein Borstenpinsel hat auf einem Pfad keine eigenen Optionen Brush Strokes Pinselstriche Brushes Pinsel Built-in Libraries Integrierte Bibliotheken diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a7dd7ed926..bc016388d5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -338,6 +338,12 @@ font-technology Variable Μεταβλητές Brush Definition Ορισμός πινέλου Brush Libraries Βιβλιοθήκες πινέλων Brush Options… Επιλογές πινέλου… + Options of Selected Object… Επιλογές επιλεγμένου αντικειμένου… + Options of Selected Object Επιλογές επιλεγμένου αντικειμένου +@msg no path painted with a brush is selected δεν έχει επιλεγεί διαδρομή βαμμένη με πινέλο +@msg the selected paths are painted with brushes of different types οι επιλεγμένες διαδρομές είναι βαμμένες με πινέλα διαφορετικών τύπων +@msg give `params` or `reset`, not both δώστε `params` ή `reset`, όχι και τα δύο +@msg a bristle brush has no options of its own on a path ένα πινέλο με τρίχες δεν έχει δικές του επιλογές σε διαδρομή Brush Strokes Πινελιές Brushes Πινέλα Built-in Libraries Ενσωματωμένες βιβλιοθήκες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cf3d0bbf96..451a6f063d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -360,6 +360,12 @@ font-technology Variable Variables Brush Definition Definición del pincel Brush Libraries Bibliotecas de pinceles Brush Options… Opciones de pincel… + Options of Selected Object… Opciones del objeto seleccionado… + Options of Selected Object Opciones del objeto seleccionado +@msg no path painted with a brush is selected no hay ningún trazado pintado con un pincel seleccionado +@msg the selected paths are painted with brushes of different types los trazados seleccionados están pintados con pinceles de tipos distintos +@msg give `params` or `reset`, not both indique `params` o `reset`, no ambos +@msg a bristle brush has no options of its own on a path un pincel de cerdas no tiene opciones propias en un trazado Brush Strokes Trazos de pincel Brushes Pinceles Built-in Libraries Bibliotecas integradas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 24b7858169..9b0895a4d4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3351,6 +3351,12 @@ theme Appearance Ulkoasu Break Link to Symbol Katkaise linkki symboliin Brush Definition Siveltimen määritys Brush Options… Siveltimen asetukset… + Options of Selected Object… Valitun objektin asetukset… + Options of Selected Object Valitun objektin asetukset +@msg no path painted with a brush is selected siveltimellä maalattua polkua ei ole valittu +@msg the selected paths are painted with brushes of different types valitut polut on maalattu eri tyyppisillä siveltimillä +@msg give `params` or `reset`, not both anna `params` tai `reset`, ei molempia +@msg a bristle brush has no options of its own on a path harjassiveltimellä ei ole polulla omia asetuksia Current Brush Nykyinen sivellin Current Symbol Nykyinen symboli Delete Brush Poista sivellin diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8303bbae94..5cde2a4ec4 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -361,6 +361,12 @@ font-technology Variable Variables Brush Definition Définition de la forme Brush Libraries Bibliothèques de formes Brush Options… Options de forme… + Options of Selected Object… Options de l’objet sélectionné… + Options of Selected Object Options de l’objet sélectionné +@msg no path painted with a brush is selected aucun tracé peint avec une forme n’est sélectionné +@msg the selected paths are painted with brushes of different types les tracés sélectionnés sont peints avec des formes de types différents +@msg give `params` or `reset`, not both indiquez `params` ou `reset`, pas les deux +@msg a bristle brush has no options of its own on a path une forme Soies n’a pas d’options propres sur un tracé Brush Strokes Contours de forme Brushes Formes Built-in Libraries Bibliothèques intégrées diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 551c39d1f8..3d508daaa8 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -446,6 +446,8 @@ Brush Library બ્રશ લાઇબ્રેરી Brush Options બ્રશ વિકલ્પો Brush Options… બ્રશ વિકલ્પો… + Options of Selected Object… પસંદ કરેલા ઑબ્જેક્ટના વિકલ્પો… + Options of Selected Object પસંદ કરેલા ઑબ્જેક્ટના વિકલ્પો Brush Scale Options બ્રશ સ્કેલ વિકલ્પો Brush Strokes બ્રશ સ્ટ્રોક Brushes બ્રશ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6a135dccaa..557e8e72c5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -691,6 +691,12 @@ antiAlias Sharp शार्प Brush Library ब्रश लाइब्रेरी Brush Options ब्रश ऑप्शन्स Brush Options… ब्रश ऑप्शन्स… + Options of Selected Object… सिलेक्टेड ऑब्जेक्ट के ऑप्शन्स… + Options of Selected Object सिलेक्टेड ऑब्जेक्ट के ऑप्शन्स +@msg no path painted with a brush is selected ब्रश से पेंट किया गया कोई पाथ नहीं चुना गया +@msg the selected paths are painted with brushes of different types चुने गए पाथ अलग-अलग प्रकार के ब्रश से पेंट किए गए हैं +@msg give `params` or `reset`, not both `params` या `reset` दें, दोनों नहीं +@msg a bristle brush has no options of its own on a path ब्रिसल ब्रश के किसी पाथ पर अपने ऑप्शन्स नहीं होते Brush Scale Options ब्रश स्केल ऑप्शन्स Brush Size ब्रश साइज़ Brush Strokes ब्रश स्ट्रोक्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 09a9797d3e..53d2a83f3e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -495,6 +495,12 @@ font-technology Variable Változó Brush Definition Ecsetdefiníció Brush Libraries Ecsetkönyvtárak Brush Options… Ecset beállításai… + Options of Selected Object… Kijelölt objektum beállításai… + Options of Selected Object Kijelölt objektum beállításai +@msg no path painted with a brush is selected nincs kijelölt ecsettel festett útvonal +@msg the selected paths are painted with brushes of different types a kijelölt útvonalak különböző típusú ecsetekkel vannak festve +@msg give `params` or `reset`, not both `params` vagy `reset` adható meg, a kettő együtt nem +@msg a bristle brush has no options of its own on a path a sörteecsetnek nincsenek saját beállításai egy útvonalon Brush Scale Options Ecsetméretezési beállítások Brush Strokes Ecsetvonások Brushes Ecsetek diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 32283beade..931fdd92c6 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3145,6 +3145,8 @@ theme Appearance Tampilan Break Link to Symbol Putuskan tautan ke simbol Brush Definition Definisi kuas Brush Options… Opsi kuas… + Options of Selected Object… Opsi objek yang dipilih… + Options of Selected Object Opsi objek yang dipilih Current Brush Kuas saat ini Current Symbol Simbol saat ini Delete Brush Hapus kuas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2c8cc708dc..857889158a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -360,6 +360,12 @@ font-technology Variable Variabili Brush Definition Definizione pennello Brush Libraries Librerie pennelli Brush Options… Opzioni pennello… + Options of Selected Object… Opzioni dell’oggetto selezionato… + Options of Selected Object Opzioni dell’oggetto selezionato +@msg no path painted with a brush is selected nessun tracciato dipinto con un pennello selezionato +@msg the selected paths are painted with brushes of different types i tracciati selezionati sono dipinti con pennelli di tipi diversi +@msg give `params` or `reset`, not both indica `params` o `reset`, non entrambi +@msg a bristle brush has no options of its own on a path un pennello a setole non ha opzioni proprie su un tracciato Brush Strokes Pennellate Brushes Pennelli Built-in Libraries Librerie integrate diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index bd03123f11..3bdebe7723 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1200,6 +1200,12 @@ antiAlias Sharp シャープ Brush Affects: ブラシの影響: Brush Definition ブラシの定義 Brush Options… ブラシオプション… + Options of Selected Object… 選択中のオブジェクトのオプション… + Options of Selected Object 選択中のオブジェクトのオプション +@msg no path painted with a brush is selected ブラシで描かれたパスが選択されていません +@msg the selected paths are painted with brushes of different types 選択したパスは種類の異なるブラシで描かれています +@msg give `params` or `reset`, not both `params` と `reset` は同時に指定できません +@msg a bristle brush has no options of its own on a path 剛毛ブラシにはパスごとのオプションがありません Built-in presets are read-only: New… starts an editable copy. 組み込みのプリセットは読み取り専用です。「新規…」で編集可能なコピーを作成できます。 Built-in presets don't change: New makes a copy you can edit. 組み込みのプリセットは変更できません。「新規」で編集可能なコピーを作成します。 Built-in presets don't change: New… starts an editable copy. 組み込みのプリセットは変更できません。「新規…」で編集できる複製を作成します。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 54445dffb9..0b7f193fc8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2988,6 +2988,12 @@ theme Appearance იერსახე Break Link to Symbol სიმბოლოსთან კავშირის გაწყვეტა Brush Definition ფუნჯის განსაზღვრება Brush Options… ფუნჯის პარამეტრები… + Options of Selected Object… მონიშნული ობიექტის პარამეტრები… + Options of Selected Object მონიშნული ობიექტის პარამეტრები +@msg no path painted with a brush is selected ფუნჯით დახატული კონტური მონიშნული არ არის +@msg the selected paths are painted with brushes of different types მონიშნული კონტურები სხვადასხვა ტიპის ფუნჯებითაა დახატული +@msg give `params` or `reset`, not both მიუთითეთ `params` ან `reset`, არა ორივე +@msg a bristle brush has no options of its own on a path ჯაგრის ფუნჯს კონტურზე საკუთარი პარამეტრები არ აქვს Current Brush მიმდინარე ფუნჯი Current Symbol მიმდინარე სიმბოლო Delete Brush ფუნჯის წაშლა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2f91553467..066ea9b05d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1190,6 +1190,12 @@ antiAlias Sharp 날카롭게 Brush Affects: 브러시 적용 대상: Brush Definition 브러시 정의 Brush Options… 브러시 옵션… + Options of Selected Object… 선택한 오브젝트 옵션… + Options of Selected Object 선택한 오브젝트 옵션 +@msg no path painted with a brush is selected 브러시로 칠한 패스가 선택되지 않았습니다 +@msg the selected paths are painted with brushes of different types 선택한 패스가 서로 다른 유형의 브러시로 칠해져 있습니다 +@msg give `params` or `reset`, not both `params`와 `reset` 중 하나만 지정하세요 +@msg a bristle brush has no options of its own on a path 강모 브러시는 패스별 옵션이 없습니다 Built-in presets are read-only: New… starts an editable copy. 기본 제공 프리셋은 읽기 전용입니다. 새로 만들기…를 누르면 편집 가능한 복사본이 만들어집니다. Built-in presets don't change: New makes a copy you can edit. 기본 제공 프리셋은 변경되지 않습니다. 새로 만들기를 누르면 편집 가능한 복사본이 만들어집니다. Built-in presets don't change: New… starts an editable copy. 기본 제공 프리셋은 변경되지 않습니다. 새로 만들기…를 누르면 편집 가능한 복사본이 만들어집니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b8eede91bd..2d768bb883 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3663,6 +3663,12 @@ theme Appearance Vormgeving Break Link to Symbol Koppeling met symbool verbreken Brush Definition Penseeldefinitie Brush Options… Penseelopties… + Options of Selected Object… Opties voor geselecteerd object… + Options of Selected Object Opties voor geselecteerd object +@msg no path painted with a brush is selected geen met een penseel geschilderd pad geselecteerd +@msg the selected paths are painted with brushes of different types de geselecteerde paden zijn geschilderd met penselen van verschillende typen +@msg give `params` or `reset`, not both geef `params` of `reset`, niet beide +@msg a bristle brush has no options of its own on a path een borstelpenseel heeft geen eigen opties op een pad Current Brush Huidig penseel Current Symbol Huidig symbool Delete Brush Penseel verwijderen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index b846ae308c..7c73cfc6e5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3291,6 +3291,12 @@ theme Appearance Wygląd Break Link to Symbol Zerwij łącze z symbolem Brush Definition Definicja pędzla Brush Options… Opcje pędzla… + Options of Selected Object… Opcje zaznaczonego obiektu… + Options of Selected Object Opcje zaznaczonego obiektu +@msg no path painted with a brush is selected nie zaznaczono ścieżki malowanej pędzlem +@msg the selected paths are painted with brushes of different types zaznaczone ścieżki są malowane pędzlami różnych typów +@msg give `params` or `reset`, not both podaj `params` albo `reset`, nie oba +@msg a bristle brush has no options of its own on a path pędzel włosiankowy nie ma własnych opcji na ścieżce Current Brush Bieżący pędzel Current Symbol Bieżący symbol Delete Brush Usuń pędzel diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9b74bba16e..198a39e4e4 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -330,6 +330,12 @@ antiAlias Sharp Nítido Brush Definition Definição do Pincel Brush Libraries Bibliotecas de Pincéis Brush Options… Opções de Pincel… + Options of Selected Object… Opções do Objeto Selecionado… + Options of Selected Object Opções do Objeto Selecionado +@msg no path painted with a brush is selected nenhum demarcador pintado com pincel selecionado +@msg the selected paths are painted with brushes of different types os demarcadores selecionados estão pintados com pincéis de tipos diferentes +@msg give `params` or `reset`, not both informe `params` ou `reset`, não ambos +@msg a bristle brush has no options of its own on a path um pincel de cerdas não tem opções próprias em um demarcador Brush Strokes Traços de Pincel Brushes Pincéis Built-in Libraries Bibliotecas Integradas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cd904e1224..6be2e96f1a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -358,6 +358,12 @@ font-technology Variable Вариативные Brush Definition Определение кисти Brush Libraries Библиотеки кистей Brush Options… Параметры кисти… + Options of Selected Object… Параметры выделенного объекта… + Options of Selected Object Параметры выделенного объекта +@msg no path painted with a brush is selected не выделен контур, нарисованный кистью +@msg the selected paths are painted with brushes of different types выделенные контуры нарисованы кистями разных типов +@msg give `params` or `reset`, not both укажите `params` или `reset`, но не оба +@msg a bristle brush has no options of its own on a path у щетинной кисти нет собственных параметров на контуре Brush Strokes Мазки кисти Brushes Кисти Built-in Libraries Встроенные библиотеки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5d20472e7b..12f7d06d4c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -349,6 +349,12 @@ font-technology Variable Variabla Brush Definition Penseldefinition Brush Libraries Penselbibliotek Brush Options… Penselalternativ… + Options of Selected Object… Alternativ för markerat objekt… + Options of Selected Object Alternativ för markerat objekt +@msg no path painted with a brush is selected ingen bana målad med en pensel är markerad +@msg the selected paths are painted with brushes of different types de markerade banorna är målade med penslar av olika typer +@msg give `params` or `reset`, not both ange `params` eller `reset`, inte båda +@msg a bristle brush has no options of its own on a path en borstpensel har inga egna alternativ på en bana Brush Strokes Penseldrag Brushes Penslar Built-in Libraries Inbyggda bibliotek diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9bdf0c5036..2a8319bbe2 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -344,6 +344,12 @@ font-technology Variable Değişken Brush Definition Fırça Tanımı Brush Libraries Fırça Kitaplıkları Brush Options… Fırça Seçenekleri… + Options of Selected Object… Seçili Nesnenin Seçenekleri… + Options of Selected Object Seçili Nesnenin Seçenekleri +@msg no path painted with a brush is selected fırçayla boyanmış yol seçilmedi +@msg the selected paths are painted with brushes of different types seçili yollar farklı türde fırçalarla boyanmış +@msg give `params` or `reset`, not both `params` veya `reset` verin, ikisini birden değil +@msg a bristle brush has no options of its own on a path kıl fırçanın bir yolda kendine ait seçenekleri yoktur Brush Strokes Fırça Darbeleri Brushes Fırçalar Built-in Libraries Yerleşik Kütüphaneler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 7395cdec64..9c8e7efaae 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -354,6 +354,12 @@ font-technology Variable Варіативні Brush Definition Визначення пензля Brush Libraries Бібліотеки пензлів Brush Options… Параметри пензля… + Options of Selected Object… Параметри виділеного об’єкта… + Options of Selected Object Параметри виділеного об’єкта +@msg no path painted with a brush is selected не виділено контур, намальований пензлем +@msg the selected paths are painted with brushes of different types виділені контури намальовано пензлями різних типів +@msg give `params` or `reset`, not both укажіть `params` або `reset`, але не обидва +@msg a bristle brush has no options of its own on a path щетинний пензель не має власних параметрів на контурі Brush Strokes Мазки пензля Brushes Пензлі Built-in Libraries Вбудовані бібліотеки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8df980ee37..0be0fbea43 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -413,6 +413,12 @@ font-technology Variable Biến thiên Brush Definition Định nghĩa cọ Brush Libraries Thư viện cọ Brush Options… Tùy chọn cọ… + Options of Selected Object… Tùy chọn của đối tượng đã chọn… + Options of Selected Object Tùy chọn của đối tượng đã chọn +@msg no path painted with a brush is selected chưa chọn đường được vẽ bằng cọ +@msg the selected paths are painted with brushes of different types các đường đã chọn được vẽ bằng các loại cọ khác nhau +@msg give `params` or `reset`, not both chỉ cung cấp `params` hoặc `reset`, không cả hai +@msg a bristle brush has no options of its own on a path cọ lông không có tùy chọn riêng trên một đường Brush Scale Options Tùy chọn tỷ lệ cọ Brush Strokes Nét cọ Brushes Cọ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ca19647856..01a4c7448b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -308,6 +308,12 @@ antiAlias Sharp 锐利 Brush Definition 画笔定义 Brush Libraries 画笔库 Brush Options… 画笔选项… + Options of Selected Object… 所选对象的选项… + Options of Selected Object 所选对象的选项 +@msg no path painted with a brush is selected 未选择用画笔绘制的路径 +@msg the selected paths are painted with brushes of different types 所选路径使用了不同类型的画笔 +@msg give `params` or `reset`, not both 请提供 `params` 或 `reset`,不能同时提供 +@msg a bristle brush has no options of its own on a path 鬃毛画笔在路径上没有自己的选项 Brush Strokes 画笔描边 Brushes 画笔 Built-in Libraries 内置库 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 748ff1848b..def9b22041 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -322,6 +322,12 @@ font-technology Variable 可變 Brush Definition 筆刷定義 Brush Libraries 筆刷資料庫 Brush Options… 筆刷選項… + Options of Selected Object… 所選物件的選項… + Options of Selected Object 所選物件的選項 +@msg no path painted with a brush is selected 未選取以筆刷繪製的路徑 +@msg the selected paths are painted with brushes of different types 所選路徑使用了不同類型的筆刷 +@msg give `params` or `reset`, not both 請提供 `params` 或 `reset`,不能同時提供 +@msg a bristle brush has no options of its own on a path 鬃毛筆刷在路徑上沒有自己的選項 Brush Strokes 筆刷筆畫 Brushes 筆刷 Built-in Libraries 內建資料庫 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index df3f08b55e..33f9b6ba04 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -788,6 +788,7 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::new_brush::open(app, p.get("ids").cloned()), "ui.brushOptions" => crate::dialogs::brush_options::open(app, s("name").as_deref()), + "ui.brushObjectOptions" => crate::dialogs::brush_options::open_object(app), "tool.options" => crate::toolbar::open_options(app, &s("tool").unwrap_or_default()), _ => return None, }; diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 98c13ec06e..147e486227 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -285,6 +285,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.sampleScreenColor" => crate::screen_color::available(app), "ui.newBrush" => app.session.active().is_some(), "ui.brushOptions" => crate::dialogs::brush_options::available(app), + "ui.brushObjectOptions" => crate::dialogs::brush_options::object_available(app), "ui.hyphenation" | "ui.justification" | "ui.tateChuYokoSettings" | "ui.warichuSettings" => { crate::panels::character::text_style(app).is_some() } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fc43b1ed3e..cd38009f9b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -904,6 +904,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), + ( + "ui.brushObjectOptions", + "Options of Selected Object…", + "", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened, and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + ), ( "ui.graphicStyleOptions", "Graphic Style Options…", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 3e7fb53316..acde0e9805 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -15,6 +15,7 @@ const WRAPPED: &[(&str, &str)] = &[ ("layer.delete", "ui.layerDelete"), ("brush.new", "ui.newBrush"), ("brush.options", "ui.brushOptions"), + ("brush.objectOptions", "ui.brushObjectOptions"), ("symbol.options", "ui.symbolOptions"), ("svgFilter.import", "ui.importSvgFilter"), ("text.convertListToText", "type.convertListToText"), diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 0b540a4ba5..c1ff6286a4 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -523,6 +523,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + // The selected brushed paths' own settings: the brush stays as it is. + if menu_item(ui, tl!("Options of Selected Object…"), brush_options::object_available(app), false) + && let Err(e) = app.run("ui.brushObjectOptions", json!({})) + { + app.status(e); + } ui.separator(); // Selects the brushes no stroke paints with, for Delete Brush and Duplicate Brush. if menu_item(ui, tl!("Select All Unused"), app.session.active().is_some(), false) diff --git a/docs/mcp.md b/docs/mcp.md index 494b4f4ef6..a9bfeae56f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3317,7 +3317,7 @@ already walks Image Trace. Short agent entry points: - Brushes: `brush.list`, `brush.get {name}`, `brush.apply {name, ids?}`, `brush.new {type, name?, params?, ids?}`, `brush.setCurrent {name}`, `brush.options {name, params?, newName?}`, `brush.delete {name} | {names}`, `brush.duplicate {name, newName?} | {names}`, `brush.freehand {…path.freehand params, brush?}`, - `object.expandBrush {ids?}`. `brush.freehand` draws the plain path when `brush` is left out or null. It refuses a + `object.expandBrush {ids?}`, `brush.objectOptions {ids?, params?, reset?}`. `brush.freehand` draws the plain path when `brush` is left out or null. It refuses a `brush` that is not a string with "`brush` must be a string", a name that no brush in the document has (an empty name included) with "no brush named ``", and a `style` other than "pencil" or "brush"; the document does not change and no undo step is recorded. The Paintbrush skips a tool brush or current brush that has been deleted and @@ -3347,6 +3347,20 @@ already walks Image Trace. Short agent entry points: words. Corner tiles also take `autoCentered`, `autoBetween`, `autoSliced` and `autoOverlap`. A swatch choice copies its whole art and tile frame into the brush. `original` keeps the current art and clears its swatch label. `side_tile: "none"` fails with "You must choose a side pattern." An unknown swatch name also fails; neither error edits the brush or adds an Undo step. + `brush.objectOptions {ids?, params?, reset?}` (the Brushes panel menu's Options of Selected Object…, from the + [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) + page) changes the brush settings of the selected brushed paths on those paths only; the brush and its other strokes + keep their settings. The fields a path can set are VectorCraft's own choice: calligraphic `angle`, `roundness`, + `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation`, `modes`, + `rotation_relative_to_path` and `colorization`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, + `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. + Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it + gives, and a setting equal to the brush's own value is dropped. `reset: true` clears a path's settings. The command + refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different + types, a bristle brush and a field the type does not take. It records one undo step, and none when nothing changes. + `brush.options` edits still reach the settings a path does not set, `brush.apply`, a brush change in + `stroke.setAdvanced` and removing the brush clear the path's settings, and renaming the brush keeps them. Without + `params` or `reset` the command only returns the first path's settings. The native file saves them on the stroke as `brush_options`. - Pen tilt, bearing and barrel rotation (#764): `path.freehand` and `brush.freehand` take points as `[x, y, pressure, tiltX, tiltY, rotation]` or `{x, y, pressure?, tiltX?, tiltY?, rotation?}`, with `null` for what a point lacks, and a `pointer_gesture` event takes `tiltX`, `tiltY` and `rotation`, which the Paintbrush records. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 082e565bd2..59a0450418 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -433,6 +433,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | +| Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | | Pathfinder Trim, Merge and Crop remove strokes; Merge joins same-fill objects whatever their strokes | done | #1570 (#1572) | From dae1bf749b97cf882666807d63d04250771e00cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:21:48 -0800 Subject: [PATCH 061/138] i18n: drop catalog rows main already has Merging main brought in Georgian and Russian rows for the SVG filter messages that this branch also added, so each catalog held them twice and bundled_catalogs_are_consistent failed. The branch's copies are removed and main's rows stay. --- crates/ui-egui/src/i18n/ka.tsv | 16 ---------------- crates/ui-egui/src/i18n/ru.tsv | 1 - 2 files changed, 17 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c8a882cb4f..1e9af86016 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7484,25 +7484,9 @@ font-technology Variable ცვლადი @msg a 3D effect on a group's fill or stroke draws nothing ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი არაფერს ხატავს @msg a 3D effect on a group's fill or stroke draws nothing to export ჯგუფის შევსებაზე ან კონტურზე 3D ეფექტი ექსპორტისთვის არაფერს ხატავს @msg The 3D object is too complex to export 3D ობიექტი ზედმეტად რთულია ექსპორტისთვის -@msg give one element მიუთითეთ ერთი ელემენტი -@msg the element needs an id, the filter's name ელემენტს სჭირდება id, ფილტრის სახელი -@msg an SVG filter's id is at most {MAX_NAME} characters SVG ფილტრის id მაქსიმუმ {MAX_NAME} სიმბოლოა -@msg <{_1}> isn't an element of an SVG filter <{_1}> არ არის SVG ფილტრის ელემენტი -@msg an SVG filter has no event attributes such as {_1} SVG ფილტრს არ აქვს მოვლენის ატრიბუტები, როგორიცაა {_1} -@msg an SVG filter's images are PNG, JPEG, GIF or WebP data: URLs SVG ფილტრის გამოსახულებები PNG, JPEG, GIF ან WebP data: URL-ებია -@msg the SVG filter isn't valid XML: {e} SVG ფილტრი არ არის სწორი XML: {e} -@msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence-ის numOctaves მაქსიმუმ {MAX_OCTAVES}-ია -@msg {what} is at most {max} {what}: მაქსიმუმ {max} @msg feConvolveMatrix's order feConvolveMatrix-ის order @msg feMorphology's radius feMorphology-ის radius @msg a blur's stdDeviation დაბინდვის stdDeviation -@msg the SVG filter has no primitives SVG ფილტრს არ აქვს პრიმიტივები -@msg an SVG filter has at most {MAX_PRIMITIVES} primitives SVG ფილტრს აქვს მაქსიმუმ {MAX_PRIMITIVES} პრიმიტივი -@msg the SVG filter is too large once its attributes are written out SVG ფილტრი ზედმეტად დიდია მისი ატრიბუტების ჩაწერის შემდეგ -@msg an SVG filter's images have at most {MAX_IMAGE_PIXELS} pixels in all SVG ფილტრის გამოსახულებებს სულ მაქსიმუმ {MAX_IMAGE_PIXELS} პიქსელი აქვს -@msg the SVG filter can't be drawn: check its primitives and their inputs SVG ფილტრის დახატვა შეუძლებელია: შეამოწმეთ მისი პრიმიტივები და მათი შემავალი მონაცემები -@msg an SVG filter's elements nest at most {MAX_DEPTH} deep SVG ფილტრის ელემენტები მაქსიმუმ {MAX_DEPTH} დონის სიღრმეზეა ჩადგმული -@msg an SVG filter is at most {_1} KB SVG ფილტრი მაქსიმუმ {_1} KB-ია @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ობიექტს არ აქვს 3D ეფექტი (ამოწევა და წაკვეთა, ბრუნვა, გაბერვა ან შემობრუნება) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` უნდა იყოს ობიექტი, რომელიც შეიცავს მხოლოდ `mode`-ს, მნიშვნელობით shaded ან wireframe @msg its 3D effect builds no solid მისი 3D ეფექტი სხეულს არ ქმნის diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1f919a390..45c861f013 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5738,7 +5738,6 @@ lighting Light Свет @msg a 3D effect on a group's fill or stroke draws nothing 3D-эффект на заливке или обводке группы ничего не рисует @msg a 3D effect on a group's fill or stroke draws nothing to export 3D-эффект на заливке или обводке группы не рисует ничего для экспорта @msg The 3D object is too complex to export 3D-объект слишком сложен для экспорта -@msg give one element укажите один элемент @msg the element needs an id, the filter's name элементу нужен id, имя фильтра @msg an SVG filter's id is at most {MAX_NAME} characters id фильтра SVG содержит не более {MAX_NAME} символов @msg <{_1}> isn't an element of an SVG filter <{_1}> не является элементом фильтра SVG From eab8931dde675c2099609400656614e5be4b3cd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:23:36 -0800 Subject: [PATCH 062/138] i18n: drop catalog rows main already has Main's Georgian catalog already carries the action step error row, so the copy this branch added is removed. --- crates/ui-egui/src/i18n/ka.tsv | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 938483edf7..9475bb917c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6476,7 +6476,6 @@ font-technology Variable ცვლადი @msg bad trailer არასწორი ტრეილერი @msg balance must be between 0 and 100 balance უნდა იყოს 0-სა და 100-ს შორის @msg batch step {_1} (`{id}`) failed: {e} პაკეტის ნაბიჯი {_1} (`{id}`) ვერ შესრულდა: {e} -@msg action step {_1} (`{id}`) failed: {reason} მოქმედების ნაბიჯი {_1} (`{id}`) ვერ შესრულდა: {reason} @msg brightness must be dark|mediumDark|mediumLight|light brightness უნდა იყოს dark|mediumDark|mediumLight|light @msg can't encode the document: {0} დოკუმენტის კოდირება ვერ ხერხდება: {0} @msg can't parse shortcut `{c}` მალსახმობის `{c}` ანალიზი ვერ ხერხდება From fb287514d566decd1505cac1c9b872777a49861b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:23:45 -0800 Subject: [PATCH 063/138] i18n: drop catalog rows main already has Main's Georgian catalog has a row for `index` must be a whole number and one for the knockout groups warning, so the copies this branch added are removed. Main's knockout row had two spaces after the colon, which neither the program's text nor the message scan matches; it now has one. The Georgian counts in localization-parity.md are recounted. --- crates/ui-egui/src/i18n/ka.tsv | 6 +----- docs/localization-parity.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 745a378df3..fd8ad39fc2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1979,7 +1979,7 @@ @msg each font must be {{name, parts}} თითოეული შრიფტი უნდა იყოს {{name, parts}} @msg feTurbulence's numOctaves is at most {MAX_OCTAVES} feTurbulence-ის numOctaves მაქსიმუმ {MAX_OCTAVES}-ია @msg give fonts: [{{name, parts}}…] მიუთითეთ fonts: [{{name, parts}}…] -@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ნახევრად გამჭვირვალე ელემენტი ერთმანეთს ფარავს, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები სრულად ჩაკვეთს იმას, რასაც ფარავს +@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ნახევრად გამჭვირვალე ელემენტი ერთმანეთს ფარავს, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები სრულად ჩაკვეთს იმას, რასაც ფარავს @msg no pattern `{pat}` პატერნი `{pat}` არ არის @msg numbers out of order in {{}} quantifier {{}} კვანტიფიკატორში რიცხვები არასწორი რიგითაა @msg plugin.remove: {_1}: {e}: nothing was removed plugin.remove: {_1}: {e}: არაფერი წაშლილა @@ -9861,10 +9861,6 @@ font-script Japanese იაპონური Grommets ლუვერები Grommet Inset ლუვერების დაშორება კიდიდან Diameter დიამეტრი - -# Messages of document.activate and of PDF export's knockout groups. -@msg `index` must be a whole number `index` უნდა იყოს მთელი რიცხვი -@msg knockout groups with too many overlapping translucent elements are written as PDF knockout groups: their translucent elements knock out what they cover fully ჩაკვეთილი ჯგუფები, რომლებშიც ზედმეტად ბევრი ერთმანეთზე გადაფარებული ნახევრად გამჭვირვალე ელემენტია, PDF-ის ჩაკვეთილ ჯგუფებად იწერება: მათი ნახევრად გამჭვირვალე ელემენტები მთლიანად ჩაკვეთენ იმას, რასაც ფარავენ Nest Shapes… ფორმების განლაგება… Nest Shapes ფორმების განლაგება Roll რულონი diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 8fb6290d34..202df93a55 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -66,7 +66,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Swedish | `sv` | 8,991 rows, 3,106 of them `@msg` and 48 `@msgplural` (counted 2026-11-14): the untranslated report lists 518 missing messages for it, and 12 menu strings, 1 `tl!` literal and 3 undo labels; one/other plurals | full; native review welcome | | Bulgarian | `bg` | 5,245 rows, 763 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial | full; AI-drafted, native review pending | | Greek | `el` | 5,251 rows, 795 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | full; native review welcome | -| Georgian | `ka` | 7,512 rows, 1,640 of them `@msg` and 48 `@msgplural` (counted 2026-11-14): menus, panels, dialogs and plurals (one count-neutral form); the untranslated report lists 1,927 missing Georgian messages, and 53 messages that no language has a row for | full | +| Georgian | `ka` | 9,758 rows, 3,740 of them `@msg` and 49 `@msgplural` (counted 2026-11-15): menus, panels, dialogs and plurals (one count-neutral form); the untranslated report lists 1 missing Georgian message; reviewed by a native speaker | full | | Turkish | `tr` | 9,175 rows, 3,446 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); 41 messages, 62 menu strings, 26 `tl!` literals, 13 undo labels and the default swatch names still fall back to English | full | | Catalan | `ca` | 5,626 rows, 881 of them `@msg` (counted 2026-10-28): menus, `tl!` literals and messages complete when counted; one/other plurals; every `ca-*` locale resolves here | full; AI-drafted, native review welcome | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 93b934d196..ac1890f2f1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -951,7 +951,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog (`ka`) translates the two messages the report then listed as missing from every language: `document.activate`'s `` `index` must be a whole number `` and PDF export's warning about knockout groups with too many translucent elements (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). See [localization-parity.md](localization-parity.md). + - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. From 87acb57d0dbad837b1cc0549167a1d293f301733 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:17:25 -0800 Subject: [PATCH 064/138] Brushes: Options of Selected Object keeps each path's values the dialog did not change With several brushed paths selected, editing one end of a range in the dialog sent the whole range, so every path took the first path's other end. The dialog now sends only the items and colorization fields that changed, and brush.objectOptions reads a null item of an array as each path's own item, else the brush's. A null mode keeps the mode the path has with its other values, and modes that change nothing are not stored. --- crates/brush/src/lib.rs | 46 +++++++++++++++++-- crates/brush/src/tests.rs | 20 ++++++++ crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 15 +++++- crates/engine/src/tests/brushsym.rs | 23 ++++++++++ crates/ui-egui/src/dialogs/brush_options.rs | 19 +++++++- .../src/dialogs/brush_options/tests.rs | 17 +++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 4 +- 9 files changed, 138 insertions(+), 10 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 7f83931f25..718a552f32 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -865,12 +865,26 @@ impl BrushKind { } } +/// Stroke option value `new` with each `null` item of an array taken from the same place in +/// `current`, an array of the same length: a stroke option that changes some items of a range or a +/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as +/// it is. +pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value { + match (new, current) { + (serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => { + serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect()) + } + _ => new.clone(), + } +} + impl Brush { /// The brush as a stroke whose own settings are `options` draws it: each field of /// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization` /// object changes only the fields it gives), and the values are kept within their ranges - /// ([`Brush::sanitize`]). Fields the type does not take are passed over. An error when a value - /// is of the wrong kind. + /// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there + /// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of + /// the wrong kind. pub fn with_stroke_options(&self, options: &serde_json::Map) -> Result { let keys = self.kind.stroke_option_keys(); let mut values = self.kind.option_values(); @@ -885,8 +899,11 @@ impl Brush { inner.insert(f.clone(), fv.clone()); } } + // Set below, once the values the modes may follow are in. + _ if k == "modes" => {} _ => { - o.insert(k.clone(), v.clone()); + let current = o.get(k).cloned().unwrap_or_default(); + o.insert(k.clone(), keep_items(v, ¤t)); } } } @@ -899,7 +916,28 @@ impl Brush { c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?); } let mut b = self.clone(); - b.kind.set_option_values(values).map_err(|e| e.to_string())?; + b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?; + if let Some(m) = options.get("modes") + && keys.contains(&"modes") + { + // A null item keeps the mode the brush with the other settings has: modes it leaves to + // its values follow the stroke's values, as they are kept within their ranges. Modes + // equal to those are left as the brush has them, so they keep following the values. + b.sanitize(); + let current = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(), + _ => serde_json::Value::Null, + }; + let modes = keep_items(m, ¤t); + if modes != current { + if let Some(o) = values.as_object_mut() { + o.insert("modes".into(), modes); + } + b = self.clone(); + b.kind.set_option_values(values).map_err(|e| e.to_string())?; + } + } b.sanitize(); Ok(b) } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index cb4e560ff5..46779d8e2d 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2098,3 +2098,23 @@ fn stroke_options_are_checked_and_kept_within_their_ranges() { let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]}))); assert!(near(bounds(&odd).height(), 4.0, 1e-6)); } + +#[test] +fn null_stroke_option_items_keep_the_items_the_stroke_has() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A scatter brush at fixed sizes, with no modes of its own: they follow its values. + let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) }; + let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") }; + assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's"); + // A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode. + let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap(); + let BrushKind::Scatter(s) = e.kind else { panic!("scatter") }; + assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]); + // The kept modes follow the values as they are kept within their ranges. + let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap(); + let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]); + // Modes that change nothing are no setting of the stroke's: they keep following its values. + let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap(); + assert!(same.is_empty(), "{same:?}"); +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 2712339b6f..0e2cd79cd6 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -171,7 +171,7 @@ pub fn specs() -> Vec { "Options of Selected Object…", [], None, - "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle, roundness, size, variation, modes; scatter size, spacing, scatter, rotation, modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, or stroke.setAdvanced with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle, roundness, size, variation, modes; scatter size, spacing, scatter, rotation, modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, or stroke.setAdvanced with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", has_doc, brush_object_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 00e286bd98..de2109c065 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -558,7 +558,20 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result let keys = b.kind.stroke_option_keys(); let mut merged: serde_json::Map = own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); - merged.extend(params.clone()); + // A colorization object changes only the fields it gives, and a null item of an + // array keeps the stroke's own item (else the brush's). + for (k, v) in ¶ms { + let next = match (merged.get(k), v) { + (Some(Value::Object(mine)), Value::Object(fields)) if k == "colorization" => { + let mut c = mine.clone(); + c.extend(fields.clone()); + Value::Object(c) + } + (Some(mine), _) => brush::keep_items(v, mine), + (None, _) => v.clone(), + }; + merged.insert(k.clone(), next); + } b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? }; options.get_or_insert_with(|| next.clone()); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index e881c448eb..41db8291e0 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -152,6 +152,29 @@ fn options_of_selected_object_change_one_path_and_leave_the_brush() { assert_eq!(undo_steps(&s), steps); } +#[test] +fn options_of_selected_object_null_items_keep_each_paths_own() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Confetti", "ids": [a.0, b.0]})).unwrap(); + let brush_size = s.execute("brush.get", &json!({"name": "Confetti"})).unwrap()["size"].clone(); + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"size": [50, 80]}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"size": [60, 120]}})).unwrap(); + let steps = undo_steps(&s); + // Only the smallest size changes: each path keeps its own largest size. + let r = s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"size": [40, null]}})).unwrap(); + assert_eq!(r["changed"], json!([a.0, b.0])); + assert_eq!(own_options(&s, a)["size"], json!([40.0, 80.0])); + assert_eq!(own_options(&s, b)["size"], json!([40.0, 120.0])); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for both paths"); + // A path without its own value keeps the brush's item. + let c = line(&mut s); + s.execute("brush.apply", &json!({"name": "Confetti", "ids": [c.0]})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [c.0], "params": {"size": [null, 150]}})).unwrap(); + assert_eq!(own_options(&s, c)["size"], json!([brush_size[0], 150.0]), "brush size {brush_size}"); +} + #[test] fn options_of_selected_object_keys_convert_with_the_document() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 501ed7ec8d..310cd36f6b 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -241,13 +241,28 @@ fn object_params(d: &Dialog, keys: &[&str]) -> Map { } } +/// What of option value `now` changed from `was`, the value it opened with: `None` when nothing +/// did; of a range or a list of modes, the items that changed with `null` for the others, and of a +/// colorization, the fields that changed. The paths keep their own values for the rest. +fn changed_part(was: Option<&Value>, now: Value) -> Option { + match (was, now) { + (Some(w), n) if *w == n => None, + (Some(Value::Array(w)), Value::Array(n)) if w.len() == n.len() => { + Some(Value::Array(w.iter().zip(n).map(|(w, n)| if *w == n { Value::Null } else { n }).collect())) + } + (Some(Value::Object(w)), Value::Object(n)) => Some(Value::Object(n.into_iter().filter(|(f, v)| w.get(f) != Some(v)).collect())), + (_, n) => Some(n), + } +} + /// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the -/// values changed since it opened. The dialog closes when they are set. +/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result { let keys: Vec = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); - let changed: Map = object_params(d, &keys).into_iter().filter(|(k, v)| opened.get(k) != Some(v)).collect(); + let changed: Map = + object_params(d, &keys).into_iter().filter_map(|(k, v)| changed_part(opened.get(&k), v).map(|v| (k, v))).collect(); let r = app.run("brush.objectOptions", json!({ "ids": d.fields.get(TARGETS).cloned().unwrap_or_default(), "params": changed })); if r.is_ok() { app.ui.dialog = None; diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index e997e92805..43e4886aac 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -908,6 +908,23 @@ fn options_of_selected_object_set_one_paths_art_brush_settings() { assert_eq!(own_options(&app, a), json!({"width": 50.0})); } +#[test] +fn options_of_selected_object_change_only_the_values_edited_on_each_path() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Confetti"); + let b = brushed_line(&mut app, 100.0, "Confetti"); + app.run("brush.objectOptions", json!({"ids": [a], "params": {"size": [50, 80]}})).unwrap(); + app.run("brush.objectOptions", json!({"ids": [b], "params": {"size": [60, 120]}})).unwrap(); + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + // The dialog shows the first path's values; only the smallest size is edited. + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("sizeMax", 0.0), 80.0); + set(&mut app, json!({"sizeMin": 40})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a)["size"], json!([40.0, 80.0])); + assert_eq!(own_options(&app, b)["size"], json!([40.0, 120.0]), "the second path keeps its own largest size"); +} + #[test] fn options_of_selected_object_show_what_a_path_can_set_for_each_type() { let mut app = app(); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 3bd80b11d3..98f87430ee 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -920,7 +920,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened, and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", diff --git a/docs/mcp.md b/docs/mcp.md index 816bcb2346..8c54dbd3d9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3424,7 +3424,9 @@ already walks Image Trace. Short agent entry points: `rotation_relative_to_path` and `colorization`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it - gives, and a setting equal to the brush's own value is dropped. `reset: true` clears a path's settings. The command + gives, a `null` item of an array (`size: [40, null]`) keeps each path's own item, else the brush's, and a setting + equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one + end of a range leaves each selected path's other end as it was. `reset: true` clears a path's settings. The command refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different types, a bristle brush and a field the type does not take. It records one undo step, and none when nothing changes. `brush.options` edits still reach the settings a path does not set, `brush.apply`, a brush change in From b4e506b4b308acb5c1254bc88e79e6f6a1df7cf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:43:47 -0800 Subject: [PATCH 065/138] i18n: Greek uses one term for knockout groups MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Page Knockout Group read "Ομάδα αποκοπής σελίδας" and Opacity & Mask Define Knockout Shape ended in "σχήμα αποκοπής", the term the catalog uses for clipping (Clip Group is "Ομάδα αποκοπής"). They now say "Ομάδα διάτρησης σελίδας" and "σχήμα διάτρησης", as Knockout Group and the PDF knockout group message already do. Clipping and cutting rows keep αποκοπή. greek_rows_use_one_term_for_knockout checks the term in every Greek row whose English names a knockout. --- crates/ui-egui/src/i18n/el.tsv | 4 ++-- crates/ui-egui/src/i18n/tests.rs | 21 +++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4e30f47e3f..bc568c19b4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3292,7 +3292,7 @@ theme Appearance Εμφάνιση One Point Perspective Preset 3 Προεπιλογή προοπτικής ενός σημείου 3 One Point Perspective Preset 4 Προεπιλογή προοπτικής ενός σημείου 4 One Point Perspective Preset 5 Προεπιλογή προοπτικής ενός σημείου 5 - Opacity & Mask Define Knockout Shape Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα αποκοπής + Opacity & Mask Define Knockout Shape Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα διάτρησης Opacity Mask Info Πληροφορίες μάσκας αδιαφάνειας Opacity Mask Options Επιλογές μάσκας αδιαφάνειας Opacity: 50% Multiply Αδιαφάνεια: 50% Πολλαπλασιασμός @@ -3370,7 +3370,7 @@ theme Appearance Εμφάνιση Page Σελίδα Page information Πληροφορίες σελίδας Page Isolated Blending Απομονωμένη ανάμειξη σελίδας - Page Knockout Group Ομάδα αποκοπής σελίδας + Page Knockout Group Ομάδα διάτρησης σελίδας Pages Σελίδες Paintbrush Πινέλο ζωγραφικής (Paintbrush Tool) Paragraph Style Στυλ παραγράφου diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b632e5cac3..5db8bc8265 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -423,6 +423,27 @@ fn brazilian_portuguese_spells_relink_and_process_color() { assert!(message(pt, "`{name}` is a process colour: tints apply to global and spot colours").to_lowercase().contains("cor de processo")); } +/// Every Greek row that names a knockout says διάτρηση, never αποκοπή, which stays for clipping +/// and cutting. +#[test] +fn greek_rows_use_one_term_for_knockout() { + let el = Lang::from_code("el").expect("el registered"); + let (entries, _) = parse_entries(el.0.source); + let mut wrong = Vec::new(); + for (_, src, translation) in &entries { + let greek = translation.to_lowercase(); + let knockout_term = greek.contains("διάτρη") || greek.contains("διατρ"); + if src.to_lowercase().contains("knockout") && (greek.contains("αποκοπ") || !knockout_term) { + wrong.push(format!("knockout in {src:?} -> {translation:?}")); + } + } + assert!(wrong.is_empty(), "{} Greek rows use the wrong term:\n{}", wrong.len(), wrong.join("\n")); + assert_eq!(tr(el, "Knockout Group"), "Ομάδα διάτρησης"); + assert_eq!(tr(el, "Page Knockout Group"), "Ομάδα διάτρησης σελίδας"); + assert_eq!(tr(el, "Opacity & Mask Define Knockout Shape"), "Η αδιαφάνεια και η μάσκα καθορίζουν το σχήμα διάτρησης"); + assert_eq!(tr(el, "Clip Group"), "Ομάδα αποκοπής"); +} + #[test] fn font_height_reference_labels_are_in_complete_catalogs() { for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..608777966e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -940,6 +940,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged. - Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged. + - Greek knockout term (2026-11-15): Page Knockout Group and Opacity & Mask Define Knockout Shape say διάτρηση, as Knockout Group does, instead of αποκοπή, which stays for clipping and cutting; a test checks the term in every row that names a knockout; scores and estimates unchanged. - Hindi messages its catalog lacked (2026-11-14): 116 status and error messages that the Hindi catalog did not translate, among them the image export, color profile, swatch exchange, color book, DXF, PDF knockout group, Revolve and 3D messages, have Hindi rows; the translations are VectorCraft's own and await native review; scores and estimates unchanged. - Hindi English words (2026-11-13): 264 rows no longer keep English words in their sentences, repeat a parameter's name in Hindi or garble them, among them "unknown align", which now names the alignment; lists of accepted values such as `(left|right|top|bottom)` stay as their English writes them; two tests check every row; native review remains; scores and estimates unchanged. - Message field names and values (2026-11-13): 49 status and error messages in the Hindi, Bulgarian, Danish, Indonesian, Dutch, Brazilian Portuguese, Swedish and Turkish catalogs keep the field names in brackets, such as `[subpath, anchor]`, and the values an `unknown` message lists, such as `(points, lines)`, as their English writes them; a test checks every catalog; scores and estimates unchanged. From 74370b1cdb3651ef3f9bbd1a7f08152fe56bc4d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:49:11 -0800 Subject: [PATCH 066/138] Brushes: a Paintbrush stroke that changes a path's brush clears the path's own brush settings Extending a path with brush.freehand and another brush set the new brush but kept the settings Options of Selected Object stored for the old one. They are now cleared, as brush.apply clears them. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/draw2/freehand.rs | 6 +++++- crates/engine/src/tests/brushsym.rs | 18 ++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 0e2cd79cd6..c8efc87d1b 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -171,7 +171,7 @@ pub fn specs() -> Vec { "Options of Selected Object…", [], None, - "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle, roundness, size, variation, modes; scatter size, spacing, scatter, rotation, modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, or stroke.setAdvanced with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle, roundness, size, variation, modes; scatter size, spacing, scatter, rotation, modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", has_doc, brush_object_options ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 977f3f921a..817d01ea82 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -174,9 +174,13 @@ fn no_stroke(name: &str) -> EngineError { bad("brush.freehand", format!("cannot apply brush `{name}`: path has no stroke")) } -/// Sets brush `name` on the stroke of object `id` of `d`. +/// Sets brush `name` on the stroke of object `id` of `d`. The stroke's own settings for another +/// brush (Options of Selected Object) are cleared. fn set_brush(d: &mut Document, id: NodeId, name: &str) { if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + if st.brush.as_deref() != Some(name) { + st.brush_options.clear(); + } st.brush = Some(name.to_string()); } } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 41db8291e0..8aa440ea26 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -175,6 +175,24 @@ fn options_of_selected_object_null_items_keep_each_paths_own() { assert_eq!(own_options(&s, c)["size"], json!([brush_size[0], 150.0]), "brush size {brush_size}"); } +#[test] +fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { + let mut s = session(); + let a = line(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0]})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 50}})).unwrap(); + let extend = |s: &mut Session, brush: &str, points: Value| { + s.execute("brush.freehand", &json!({"points": points, "style": "brush", "brush": brush, "extend": {"id": a.0}})).unwrap(); + }; + // Continuing the path with its own brush keeps the settings. + extend(&mut s, "Arrow", json!([[0, 0], [40, 30], [80, 10]])); + assert_eq!(own_options(&s, a), json!({"width": 50.0})); + // Another brush, with a stroke or with only the brush changing, clears them. + extend(&mut s, "Diamonds", json!([[0, 0]])); + assert_eq!(brush_of(&s, a).as_deref(), Some("Diamonds")); + assert_eq!(own_options(&s, a), json!({})); +} + #[test] fn options_of_selected_object_keys_convert_with_the_document() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 8c54dbd3d9..0e67062c1d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3430,7 +3430,8 @@ already walks Image Trace. Short agent entry points: refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different types, a bristle brush and a field the type does not take. It records one undo step, and none when nothing changes. `brush.options` edits still reach the settings a path does not set, `brush.apply`, a brush change in - `stroke.setAdvanced` and removing the brush clear the path's settings, and renaming the brush keeps them. Without + `stroke.setAdvanced`, Global Edit or a `brush.freehand` extend, and removing the brush clear the path's settings, + and renaming the brush keeps them. Without `params` or `reset` the command only returns the first path's settings. The native file saves them on the stroke as `brush_options`. - Pen tilt, bearing and barrel rotation (#764): `path.freehand` and `brush.freehand` take points as `[x, y, pressure, tiltX, tiltY, rotation]` or `{x, y, pressure?, tiltX?, tiltY?, rotation?}`, with `null` for what a From 9226a0bf74976c96be3382103bda1d549318e63a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:14:51 -0800 Subject: [PATCH 067/138] Plug-ins: brush.objectOptions is a command a plug-in may call The plug-in call list places every registered command in ALLOWED or DENIED, and every_command_is_reviewed fails while brush.objectOptions is in neither. It edits the selected paths' brush settings the way brush.options edits a brush, so it joins brush.options in ALLOWED. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 67d0fec2a3..2580048b84 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -118,6 +118,7 @@ pub(super) const ALLOWED: &[&str] = &[ "brush.list", "brush.move", "brush.new", + "brush.objectOptions", "brush.options", "brush.placeArt", "brush.remove", From 828ac640d2ae8d2d2a711b553206849bdcc9d060 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:22:18 -0800 Subject: [PATCH 068/138] Recolor Artwork: Save Changes refuses a color group with a swatch that is not a color The rows hold only a group's colors, so a save would replace or remove its gradient or pattern swatches. Save Changes on such a group is refused when groupAction is set and when the button runs, checked on the document without the preview, which can rewrite the group. --- crates/ui-egui/src/dialogs/recolor.rs | 103 +++++++++++++++++++++++--- docs/mcp.md | 5 +- 2 files changed, 97 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index caf7229bee..dba2c1ac9c 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -527,7 +527,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> /// `delete` removes the selected group and its swatches. Each is an undo step of its own on the /// document, not on the preview, which runs again afterwards. fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Result<(), String> { - check_group_action(d, action)?; + check_group_action(app, d, action)?; let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); // The rows as OK reads them (a group just selected reduces the art again). sync(app, d); @@ -704,17 +704,30 @@ const SAVED_ROWS: &str = "__savedRows"; /// The selected group's colors after Save Changes, which OK gives it again with a new name. const SAVED_COLORS: &str = "__savedColors"; -/// Refuse a `groupAction` other than `save`, `new` or `delete`, and `save` or `delete` with no -/// group selected. -fn check_group_action(d: &Dialog, action: &Value) -> Result<(), String> { - match action.as_str() { - Some("new") => Ok(()), - Some("save" | "delete") if d.fields.get("group").is_some_and(Value::is_string) => Ok(()), - Some("save" | "delete") => Err("missing `group`".into()), +/// Refuse a `groupAction` other than `save`, `new` or `delete`, `save` or `delete` with no group +/// selected, and `save` on a group with a swatch that is not a color (a gradient, pattern or None +/// swatch): the rows hold only the group's colors, so the save would replace or remove it. +fn check_group_action(app: &VectorcraftApp, d: &Dialog, action: &Value) -> Result<(), String> { + let group = d.fields.get("group").and_then(Value::as_str); + match (action.as_str(), group) { + (Some("new"), _) => Ok(()), + (Some("save"), Some(g)) if holds_other_paints(app, g) => { + Err(format!("color group `{g}` holds swatches that are not colors, which Save Changes can't keep")) + } + (Some("save" | "delete"), Some(_)) => Ok(()), + (Some("save" | "delete"), None) => Err("missing `group`".into()), _ => Err(format!("`{GROUP_ACTION}` must be \"save\", \"new\" or \"delete\", not {action}")), } } +/// Whether color group `group` has a swatch that is not a color, in the document as it is without +/// the preview (which can rewrite or rename the group). +fn holds_other_paints(app: &VectorcraftApp, group: &str) -> bool { + let Some(st) = app.session.active() else { return false }; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + doc.swatch_groups.iter().any(|g| g.name == group && g.swatches.iter().any(|w| w.paint.color().is_none())) +} + /// Run the button of the Color Groups list that `groupAction` holds, if any. fn run_group_action(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { match d.fields.remove(GROUP_ACTION) { @@ -730,7 +743,7 @@ pub(super) fn field_set(app: &mut VectorcraftApp, field: &str) -> Result<(), Str let r = match field { "group" => select_group(app, &mut d), GROUP_ACTION => match d.fields.get(GROUP_ACTION).cloned() { - Some(a) => check_group_action(&d, &a), + Some(a) => check_group_action(app, &d, &a), None => Ok(()), }, GROUP_STORAGE if !d.fields.get(GROUP_STORAGE).is_some_and(Value::is_boolean) => Err(format!("`{GROUP_STORAGE}` must be true or false")), @@ -2933,6 +2946,78 @@ mod tests { assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); } + /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and + /// leaves the group as it is: the rows hold only its colors. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#00ff00"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.insert(1, fade_swatch()); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + assert_eq!(new_colors(&app), [json!("rgb 255 0 0"), json!("rgb 0 255 0")]); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.1, "save"), refused); + app.ui.dialog.as_mut().unwrap().fields.insert("groupName".into(), json!("Renamed")); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + // OK first runs a save set together with it, and the dialog stays open. + app.ui.dialog.as_mut().unwrap().fields.insert(GROUP_ACTION.into(), json!("save")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches[1], fade_swatch(), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#00ff00".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + + /// A gradient swatch, for a color group. + fn fade_swatch() -> vectorcraft_color::Swatch { + let paint = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(Default::default()))); + vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } + } + + /// With art, the preview rewrites the group being edited, its other swatch included; Save + /// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was. + #[test] + fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Mixed", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let g = doc.swatch_groups.iter_mut().find(|g| g.name == "Mixed").unwrap(); + g.swatches.push(fade_swatch()); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Mixed"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let undo = undo_len(&app); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!("rgb 0 0 0"); + d.fields.insert("rows".into(), Value::Array(rs)); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert!(app.session.in_interaction(), "the art previews"); + let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.len()); + assert_eq!(previewed, Some(2), "the preview's rewrite of the group leaves out its other swatch"); + let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); + assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); + crate::dialogs::cancel(&mut app); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").unwrap(); + assert_eq!(g.swatches.last(), Some(&fade_swatch()), "the swatch is kept"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + assert_eq!(undo_len(&app), undo, "no step"); + } + /// Save Changes on a group whose global swatches the selected art is linked to: the art takes /// the group's new colors, and the rows are read from the art again, so they list its colors as /// they are now. A color the art had before keeps its row's new color; a color the save gave diff --git a/docs/mcp.md b/docs/mcp.md index 55e3362d35..f92618fae6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4599,8 +4599,9 @@ its row shows, and every other swatch keeps its color. After a `save` with art, Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its colors alike. Until the rows or the Global Adjust change, OK changes the saved group only by the name -in `groupName`. `save` and `delete` with no group selected answer `` missing `group` ``, and any other value is -refused. After a Delete without art, OK saves the rows as a new color group. +in `groupName`. `save` and `delete` with no group selected answer `` missing `group` ``. `save` on a group with a +swatch that is not a color (a gradient, pattern or None swatch) is refused, because the rows hold only the group's +colors. Any other value is refused. After a Delete without art, OK saves the rows as a new color group. ```json {"name":"answer_dialog","arguments":{"set":[{"field":"group","value":"Brights"},{"field":"groupAction","value":"save"}]}} From 71734d417ece963770b96e4c6943b82d58d6646c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:31:14 -0800 Subject: [PATCH 069/138] Recolor Artwork: test that a save without art applies the Global Adjust once --- crates/ui-egui/src/dialogs/recolor.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index dba2c1ac9c..c7205d7910 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -3202,6 +3202,26 @@ mod tests { assert_eq!(sent, saved, "OK renames the group with its saved colors"); } + /// Without art, Save Changes with a Global Adjust gives the group the rows' new colors with the + /// adjustment, and OK gives it the same colors again: the adjustment applies to the rows' new + /// colors, not to the saved group. + #[test] + fn saving_a_group_without_art_with_a_global_adjust_applies_it_once() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("globalAdjust".into(), json!({"brightness": -50.0})); + frame(&mut app, &ctx, 0.0, vec![], 0); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let saved = group_hex(&app, "Plain").unwrap(); + assert!(!saved.contains(&"#ff0000".to_string()), "the save darkened the group: {saved:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); + } + /// With art: a group picked in the list reduces the art to a row per color of the group, which /// become the rows' new colors, and the art previews them; the list draws beside the tabs and /// hides with `groupStorage`. From 628bd5229c56c4725deb48b95610fa2a089b0aa2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:18:05 -0800 Subject: [PATCH 070/138] Brushes: Options of Selected Object keeps the mode each path draws with when a value changes A path without modes of its own takes them from its values, so a changed calligraphic variation or scatter range could change the mode the dialog showed (a Random size became Fixed when its two ends met). brush.objectOptions now keeps each path's drawn mode for every item params does not set, and still sets the modes params give. The params text also says which way the calligraphic angle and the scatter rotation turn, as every_turn_param_says_which_way_it_turns requires. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 43 +++++++++++++++++++ crates/engine/src/tests/brushsym.rs | 32 ++++++++++++++ .../src/dialogs/brush_options/tests.rs | 35 +++++++++++++++ docs/mcp.md | 9 ++-- 5 files changed, 117 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c8efc87d1b..21679f9702 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -171,7 +171,7 @@ pub fn specs() -> Vec { "Options of Selected Object…", [], None, - "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle, roundness, size, variation, modes; scatter size, spacing, scatter, rotation, modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", has_doc, brush_object_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index de2109c065..8ddeb99b29 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -558,6 +558,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result let keys = b.kind.stroke_option_keys(); let mut merged: serde_json::Map = own.iter().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + let was = merged.clone(); // A colorization object changes only the fields it gives, and a null item of an // array keeps the stroke's own item (else the brush's). for (k, v) in ¶ms { @@ -572,6 +573,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result }; merged.insert(k.clone(), next); } + keep_drawn_modes(b, &was, ¶ms, &mut merged); b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? }; options.get_or_insert_with(|| next.clone()); @@ -593,6 +595,47 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result Ok(json!({ "ids": ids_json(&out), "changed": ids_json(&changed), "options": options.unwrap_or_default() })) } +/// The modes brush `b` draws with, for a Calligraphic or a Scatter brush. +fn drawn_modes(b: &Brush) -> Option> { + let modes = match &b.kind { + BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()), + BrushKind::Scatter(s) => serde_json::to_value(s.modes()), + _ => return None, + }; + match modes { + Ok(Value::Array(m)) => Some(m), + _ => None, + } +} + +/// Keep each mode a stroke of brush `b` draws with (with its own settings `was`) that `params` +/// does not set (no `modes`, or a `null` item) and that `merged`, its settings with `params`, +/// would change. A mode the stroke leaves to its values follows them, so without this a changed +/// variation or range would also change the mode. +fn keep_drawn_modes( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + let given = match params.get("modes") { + None | Some(Value::Null) => vec![], + Some(Value::Array(m)) => m.clone(), + // A value of the wrong kind is refused when the settings are checked. + Some(_) => return, + }; + let (Some(before), Some(after)) = + (b.with_stroke_options(was).ok().as_ref().and_then(drawn_modes), b.with_stroke_options(merged).ok().as_ref().and_then(drawn_modes)) + else { + return; + }; + if before == after { + return; + } + let kept = before.into_iter().zip(after).enumerate().map(|(j, (w, a))| if given.get(j).is_some_and(|g| !g.is_null()) { a } else { w }).collect(); + merged.insert("modes".into(), Value::Array(kept)); +} + /// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it /// places them; `brush.replaceArt` reads a group of that name as that tile. const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 8aa440ea26..d99d9ab38b 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -175,6 +175,38 @@ fn options_of_selected_object_null_items_keep_each_paths_own() { assert_eq!(own_options(&s, c)["size"], json!([brush_size[0], 150.0]), "brush size {brush_size}"); } +/// The size mode the first stroke of `id`, painted with Confetti, draws with. +fn confetti_size_mode(s: &Session, id: NodeId) -> vectorcraft_brush::Variation { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Confetti").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Scatter(sc) => sc.modes()[0], + k => panic!("not a scatter brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_the_modes_each_path_draws_with() { + use vectorcraft_brush::Variation; + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + select(&mut s, &[a, b]); + s.execute("brush.apply", &json!({"name": "Confetti"})).unwrap(); + // Confetti's sizes vary at random from 60% to 140%; the second path's follow the pressure. + select(&mut s, &[b]); + s.execute("brush.objectOptions", &json!({"params": {"modes": ["pressure", null, null, null]}})).unwrap(); + assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure)); + // One size with no mode keeps each path's mode. + select(&mut s, &[a, b]); + s.execute("brush.objectOptions", &json!({"params": {"size": [80, 80]}})).unwrap(); + assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Random, Variation::Pressure)); + assert_eq!(own_options(&s, a)["size"], json!([80.0, 80.0])); + // A mode the params give is set on each path. + s.execute("brush.objectOptions", &json!({"params": {"size": [70, 90], "modes": ["fixed", null, null, null]}})).unwrap(); + assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Fixed, Variation::Fixed)); +} + #[test] fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 43e4886aac..037c953db5 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -925,6 +925,41 @@ fn options_of_selected_object_change_only_the_values_edited_on_each_path() { assert_eq!(own_options(&app, b)["size"], json!([40.0, 120.0]), "the second path keeps its own largest size"); } +/// The modes the first stroke of path `id` draws its brush `brush` with. +fn drawn_modes(app: &VectorcraftApp, id: u64, brush: &str) -> Vec { + let lib = vectorcraft_brush::library(&app.session.active().unwrap().doc); + let b = lib.iter().find(|b| b.name == brush).unwrap(); + let own = own_options(app, id); + match b.with_stroke_options(own.as_object().unwrap()).unwrap().kind { + BrushKind::Calligraphic(c) => c.modes().to_vec(), + BrushKind::Scatter(s) => s.modes().to_vec(), + _ => vec![], + } +} + +#[test] +fn options_of_selected_object_keep_the_modes_they_show_when_a_value_changes() { + let mut app = app(); + // Confetti's size varies at random from 60% to 140%; a size of 60% to 60% leaves the mode the + // dialog shows. + let s = brushed_line(&mut app, 50.0, "Confetti"); + select(&mut app, &[s]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("sizeMode"), "random"); + set(&mut app, json!({"sizeMax": 60})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, s)["size"], json!([60.0, 60.0])); + assert_eq!(drawn_modes(&app, s, "Confetti")[0], Variation::Random); + // 6 pt. Flat's angle is Fixed; a variation set without a mode keeps it Fixed. + let c = brushed_line(&mut app, 100.0, "6 pt. Flat"); + select(&mut app, &[c]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("angleMode"), "fixed"); + set(&mut app, json!({"angleVariation": 30})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(drawn_modes(&app, c, "6 pt. Flat")[0], Variation::Fixed); +} + #[test] fn options_of_selected_object_show_what_a_path_can_set_for_each_type() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 0e67062c1d..2b40a47327 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3419,14 +3419,17 @@ already walks Image Trace. Short agent entry points: `brush.objectOptions {ids?, params?, reset?}` (the Brushes panel menu's Options of Selected Object…, from the [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) page) changes the brush settings of the selected brushed paths on those paths only; the brush and its other strokes - keep their settings. The fields a path can set are VectorCraft's own choice: calligraphic `angle`, `roundness`, - `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation`, `modes`, + keep their settings. The fields a path can set are VectorCraft's own choice: calligraphic `angle` (counter-clockwise from + level), `roundness`, `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation` + (counter-clockwise), `modes`, `rotation_relative_to_path` and `colorization`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it gives, a `null` item of an array (`size: [40, null]`) keeps each path's own item, else the brush's, and a setting equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one - end of a range leaves each selected path's other end as it was. `reset: true` clears a path's settings. The command + end of a range leaves each selected path's other end as it was. A mode that `params` does not set (no `modes`, or + a `null` item) stays the one each path draws with, so a changed calligraphic variation or scatter range does not + change it. `reset: true` clears a path's settings. The command refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different types, a bristle brush and a field the type does not take. It records one undo step, and none when nothing changes. `brush.options` edits still reach the settings a path does not set, `brush.apply`, a brush change in From 2b4845b070e431e51399068442a30b1868bc3533 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 13:31:48 -0800 Subject: [PATCH 071/138] Recolor Artwork: Save Changes matches hex rows, and theme picks apply after a group change Save Changes now finds the row for each swatch of the group as recolor.apply does: a row that lists the color exactly comes first, then a row whose "#rrggbb" entry has the same hex. A row listing "#0000ff" used to match no swatch, so the save rewrote the group from the rows in order and changed a swatch the art does not use. Reading the rows again after the save uses the same matching, so such a row keeps its new color. Picking a group in the Color Groups list also forgets the Color Theme Picker picks the rows last took, so the same picks made again give the new group's rows the palette, with or without art. --- crates/ui-egui/src/dialogs/recolor.rs | 105 +++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index c7205d7910..902cbd3a49 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -502,8 +502,10 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.insert(GROUP_LOADED.into(), json!(name)); d.fields.insert("groupName".into(), json!(name)); d.fields.insert("__newGroup".into(), json!(false)); - // The group's colors take the place of colors picked with the Color Theme Picker. + // The group's colors take the place of colors picked with the Color Theme Picker, and the same + // picks made again apply to its rows. d.fields.insert(THEME_PICKS.into(), json!([])); + d.fields.remove(THEME_DONE); d.fields.remove(SAVED_ROWS); d.fields.remove(SAVED_COLORS); if art { @@ -572,7 +574,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res .find(|(n, _)| group.as_deref() == Some(n.as_str())) .map(|g| g.1.iter().map(key).collect()) .unwrap_or_default(); - let row_of = |k: &Value| rs.iter().find(|r| r["from"].as_array().is_some_and(|f| f.contains(k))); + let row_of = |k: &Value| row_listing(&rs, k); if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { colors = own .iter() @@ -628,7 +630,7 @@ fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: for r in &mut rs { let Some(first) = r["from"].as_array().and_then(|f| f.first()).cloned() else { continue }; let from_save = r["from"].as_array().is_some_and(|f| f.iter().any(|c| given.contains(c))); - match old.iter().find(|o| o["from"].as_array().is_some_and(|f| f.contains(&first))).filter(|_| !from_save) { + match row_listing(old, &first).filter(|_| !from_save) { Some(o) => { r["to"] = o["to"].clone(); r["exclude"] = json!(excluded(o)); @@ -1028,6 +1030,23 @@ fn find_entry(k: &Value) -> Option { } } +/// The first of `rows` that lists the color entry `k`, as `recolor.apply` reads entries: rows that +/// list it as an exact color (by key, whatever its case or spacing) come before rows whose +/// "#rrggbb" entry matches it by its hex. +fn row_listing<'a>(rows: &'a [Value], k: &Value) -> Option<&'a Value> { + let want = find_entry(k)?; + let hex = |e: &FindEntry| e.as_ref().map_or_else(Clone::clone, |k| k.color().to_hex()); + let lists = |r: &Value, by_hex: bool| { + r["from"].as_array().is_some_and(|f| { + f.iter().filter_map(find_entry).any(|e| match (&e, &want) { + (Ok(a), Ok(b)) => !by_hex && a == b, + _ => by_hex && hex(&e) == hex(&want), + }) + }) + }; + rows.iter().find(|r| lists(r, false)).or_else(|| rows.iter().find(|r| lists(r, true))) +} + /// While Find is on, on the Assign tab with art and rows selected: what the art previews instead of /// [`apply_params`], as `command.batch` parameters. A first `recolor.apply` gives each current color /// of the rows that aren't selected, and each preserved color, its [`FIND_DIM`] tint, or the nearest lighter one when that is a @@ -2173,6 +2192,19 @@ mod tests { } /// Randomize after a seed past `u64::MAX` keeps the largest seed. + /// A row that lists a color exactly comes before an earlier row whose "#rrggbb" entry matches + /// it, as `recolor.apply` reads them; a hex entry matches a key of the same hex. + #[test] + fn a_row_listing_a_color_exactly_comes_before_a_hex_match() { + let rs = + [json!({"from": ["#0000ff"], "to": "rgb 0 255 0"}), json!({"from": ["RGB 0 0 255"], "to": "rgb 255 0 0"}), json!({"from": ["#ff0000"]})]; + assert_eq!(row_listing(&rs, &json!("rgb 0 0 255")), Some(&rs[1])); + assert_eq!(row_listing(&rs, &json!("rgb 255 0 0")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("#ff0000")), Some(&rs[2])); + assert_eq!(row_listing(&rs, &json!("rgb 0 255 0")), None); + assert_eq!(row_listing(&rs, &json!("cmyk 0 0 0 0")), None); + } + #[test] fn next_seed_holds_at_the_largest() { assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); @@ -2946,6 +2978,32 @@ mod tests { assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); } + /// Without art: after a group is picked in the list, the same Color Theme Picker picks that gave + /// the group before it its colors give the new group's rows the palette of the art picked too. + #[test] + fn theme_picks_apply_again_after_another_group_is_picked() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + square(&mut app, 100.0, "#00ff00"); + app.run("select.set", json!({"ids": []})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "B", "colors": ["#0000ff", "#ffff00", "#ffffff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let picks = json!([{"at": [107, 17]}]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks.clone()); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0")]); + set(&mut app, "group", json!("B")).unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 0 255"), json!("rgb 255 255 0"), json!("rgb 255 255 255")]); + app.ui.dialog.as_mut().unwrap().fields.insert(THEME_PICKS.into(), picks); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(new_colors(&app), [json!("rgb 0 255 0"), json!("rgb 0 255 0"), json!("rgb 0 255 0")], "the picks apply to B's rows"); + } + /// Save Changes on a group with a swatch that is not a color is refused, renamed or not, and /// leaves the group as it is: the rows hold only its colors. #[test] @@ -3142,6 +3200,47 @@ mod tests { assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); } + /// Save Changes where the rows list their current colors as "#rrggbb": a row matches the swatch + /// of the same color, so the swatches keep their order and the one a row lists takes its new + /// color; read again afterwards, a row whose old entry was a hex keeps its new color. + #[test] + fn saving_a_group_matches_rows_that_list_hex_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + let orange = square(&mut app, 100.0, "#ff8000"); + app.run("select.set", json!({"ids": [blue, yellow, orange]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let hex: Vec = from_colors(r).iter().map(|c| c.to_hex()).collect(); + r["to"] = match hex.first().map(String::as_str) { + Some("#0000ff") => json!("rgb 0 128 0"), + Some("#ff8000") => json!("rgb 128 0 128"), + _ => r["from"][0].clone(), + }; + r["from"] = json!(hex); + } + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = order.iter().map(|h| if h == "#0000ff" { "#008000".into() } else { h.clone() }).collect(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "the blue swatch takes the green, the red one keeps its color"); + assert_eq!((fill_hex(&app, red), fill_hex(&app, blue)), ("#ff0000".into(), "#008000".into())); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + let o = rs.iter().find(|r| from_colors(r).iter().any(|c| c.to_hex() == "#ff8000")).unwrap(); + assert!(!excluded(o) && o["to"] == json!("rgb 128 0 128"), "the orange row keeps its new color: {o}"); + } + /// Save Changes with art in the group's colors that is not linked to its swatches: the art is /// left to the preview, and OK leaves the saved group as it is until the rows change. #[test] From f260510ced08cb2d0a5e47f4a37cf2353c2daaaf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 14:06:40 -0800 Subject: [PATCH 072/138] i18n: the SVG variable-data warning names variable kinds in the interface language Opening an SVG whose variable data holds variables that aren't text warns about them with a list of kinds and counts. The sentence was translated, but the list stayed in English and used the file's raw `trait` values (`visibility (2), fileref (1)`), and a missing `trait` and a `trait` written as `unknown` were counted together. - The engine's English warning now names the kinds Visibility, Linked File, Graph Data and Unknown (a variable without a `trait`). Any other `trait` is written as the file writes it, in backticks, with each backtick in it doubled, so a `trait` such as `Visibility` or one holding a comma stays a single entry. - The status bar shows those kinds through new `variable-kind` rows and joins the entries with `variable-list-two`, `variable-list-middle` and `variable-list-end` rows, in every complete-message catalog. A list in any other form is shown as before. - The French row puts the list after a colon instead of inside parentheses, and the Hindi row is reworded so it says that the variables that aren't text were left out. --- crates/engine/src/cmd/variablecmds/library.rs | 25 +++++-- crates/engine/src/tests/variables.rs | 40 ++++++++++- crates/ui-egui/src/i18n.rs | 72 ++++++++++++++++++- crates/ui-egui/src/i18n/ca.tsv | 7 ++ crates/ui-egui/src/i18n/cs.tsv | 7 ++ crates/ui-egui/src/i18n/da.tsv | 7 ++ crates/ui-egui/src/i18n/de.tsv | 7 ++ crates/ui-egui/src/i18n/el.tsv | 7 ++ crates/ui-egui/src/i18n/es.tsv | 7 ++ crates/ui-egui/src/i18n/fi.tsv | 7 ++ crates/ui-egui/src/i18n/fr.tsv | 9 ++- crates/ui-egui/src/i18n/hi.tsv | 9 ++- crates/ui-egui/src/i18n/hu.tsv | 7 ++ crates/ui-egui/src/i18n/it.tsv | 7 ++ crates/ui-egui/src/i18n/ja.tsv | 7 ++ crates/ui-egui/src/i18n/ka.tsv | 7 ++ crates/ui-egui/src/i18n/ko.tsv | 7 ++ crates/ui-egui/src/i18n/nl.tsv | 7 ++ crates/ui-egui/src/i18n/pl.tsv | 7 ++ crates/ui-egui/src/i18n/pt-br.tsv | 7 ++ crates/ui-egui/src/i18n/ru.tsv | 7 ++ crates/ui-egui/src/i18n/sv.tsv | 7 ++ crates/ui-egui/src/i18n/tests.rs | 64 +++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 7 ++ crates/ui-egui/src/i18n/uk.tsv | 7 ++ crates/ui-egui/src/i18n/vi.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 7 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 7 ++ crates/ui-egui/src/panels/variables.rs | 4 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 31 files changed, 372 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index ceab798373..8886c597da 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -619,7 +619,21 @@ pub(crate) fn give_svg_library(doc: &mut Document, lib: Library, found: &HashMap } } doc.variables = vars.into(); - left_out_warning(other.iter().map(|v| v.trait_name.as_deref().unwrap_or_else(|| v.kind.label()))) + left_out_warning(other.iter().map(|v| left_out_kind(v.kind, v.trait_name.as_deref()))) +} + +/// How the warning about variables that aren't text names the kind of one: Visibility, Linked File +/// or Graph Data for a `trait` VectorCraft reads, Unknown for a variable without a `trait`, and any +/// other `trait` as the file writes it, in backticks, each backtick in it doubled, so that a `trait` +/// such as `Unknown` or `a (1), b` reads as one kind the file names. +fn left_out_kind(kind: VariableKind, trait_name: Option<&str>) -> String { + match (kind, trait_name) { + (VariableKind::Visibility, _) => "Visibility".into(), + (VariableKind::Image, _) => "Linked File".into(), + (VariableKind::Graph, _) => "Graph Data".into(), + (_, None) => "Unknown".into(), + (_, Some(t)) => format!("`{}`", t.replace('`', "``")), + } } /// Load Variable Library: replace the document's variables and data sets with a variable library's @@ -668,10 +682,11 @@ pub(super) fn load_library(s: &mut Session, p: &Value) -> Result { Ok(json!({"variables": declared, "deleted": deleted, "deletedDataSets": deleted_sets, "names": names})) } -/// The warning about variables that aren't text and were left out, given the kind of each: every -/// kind once, in the order it first comes, with how many variables have it. `None` without any. -fn left_out_warning<'a>(kinds: impl Iterator) -> Option { - let mut counted: Vec<(&str, usize)> = Vec::new(); +/// The warning about variables that aren't text and were left out, given the kind of each +/// ([`left_out_kind`]): every kind once, in the order it first comes, with how many variables have +/// it. `None` without any. +fn left_out_warning(kinds: impl Iterator) -> Option { + let mut counted: Vec<(String, usize)> = Vec::new(); for t in kinds { match counted.iter_mut().find(|(k, _)| *k == t) { Some((_, n)) => *n += 1, diff --git a/crates/engine/src/tests/variables.rs b/crates/engine/src/tests/variables.rs index 3b9644e550..8600bf6738 100644 --- a/crates/engine/src/tests/variables.rs +++ b/crates/engine/src/tests/variables.rs @@ -3474,12 +3474,12 @@ fn an_svg_without_readable_variable_data_opens_its_art() { // A variable without a `trait` is of unknown kind: the SVG leaves it out like the other kinds // that aren't text. let (o, warnings) = svg_opened(&untraited, "untraited.svg"); - assert!(warnings.contains(&json!("variables that aren't text were left out: unknown (1)")), "{warnings:?}"); + assert!(warnings.contains(&json!("variables that aren't text were left out: Unknown (1)")), "{warnings:?}"); assert!(o.doc().unwrap().doc.variables.variables.is_empty()); // The values of the other kinds aren't read, so one that Load Variable Library would refuse // leaves the text variables and their values as they open. let (o, warnings) = svg_opened(&relative, "relative.svg"); - assert!(warnings.contains(&json!("variables that aren't text were left out: fileref (1)")), "{warnings:?}"); + assert!(warnings.contains(&json!("variables that aren't text were left out: Linked File (1)")), "{warnings:?}"); let vars = &o.doc().unwrap().doc.variables; assert_eq!(vars.variables.iter().map(|v| v.name.as_str()).collect::>(), ["T"]); assert_eq!(vars.dataset("D").map(|d| d.values.clone()), Some([("T".to_string(), vectorcraft_doc::DataValue::Text("kept".into()))].into())); @@ -3492,6 +3492,42 @@ fn an_svg_without_readable_variable_data_opens_its_art() { assert_eq!(vectorcraft_testkit::svg_shapes(&vectorcraft_svg::export(d, &Default::default())), 1, "the art opens"); } +/// The warning about an SVG's variables that aren't text names each kind once, in the order it +/// first comes, with its count: Visibility, Linked File and Graph Data for the traits VectorCraft +/// reads, Unknown for a variable without a `trait`, and any other `trait` as the file writes it, in +/// backticks with each backtick in it doubled, so a `trait` that looks like a kind or a list entry +/// stays one entry of its own. +#[test] +fn svg_variable_data_warning_names_each_kind_left_out() { + let variables = [ + ("V1", Some("visibility")), + ("I1", Some("fileref")), + ("V2", Some("visibility")), + ("T", Some("textcontent")), + ("G1", Some("graphdata")), + ("U1", None), + ("X1", Some("unknown")), + ("X2", Some("a`b (1), c")), + ("X3", Some("Visibility")), + ("I2", Some("fileref")), + ("U2", None), + ]; + let declared: String = variables + .iter() + .map(|(name, t)| match t { + Some(t) => format!(""), + None => format!(""), + }) + .collect(); + let svg = format!( + "{declared}" + ); + let (o, warnings) = svg_opened(&svg, "kinds.svg"); + let warning = "variables that aren't text were left out: Visibility (2), Linked File (2), Graph Data (1), Unknown (2), `unknown` (1), `a``b (1), c` (1), `Visibility` (1)"; + assert!(warnings.contains(&json!(warning)), "{warnings:?}"); + assert_eq!(o.doc().unwrap().doc.variables.variables.iter().map(|v| v.name.as_str()).collect::>(), ["T"]); +} + /// Five variables of three kinds, defined out of every order: `beta` (text, on type named Mike), /// `Alpha` (visibility, on a rectangle named apple), `gamma` (image, bound to nothing), `Delta` /// (visibility, on two rectangles) and `Echo` (text, on type named Bravo). diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 8a59c7e567..92ad797f33 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -713,11 +713,81 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures message_at(lang, v, depth - 1) } }; - let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, nested(v))).collect(); + let left_out = left_out_kinds(lang, s, &caps); + let values: Vec<(&str, String)> = caps + .into_iter() + .map(|(k, v)| match (&left_out, k) { + (Some(kinds), "kinds") => (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 kinds the warning about an SVG's variables that aren't text names (the engine's +/// `left_out_kind` in `crates/engine/src/cmd/variablecmds/library.rs`), each translated by its +/// `variable-kind` row. +const LEFT_OUT_KINDS: [&str; 4] = ["Visibility", "Linked File", "Graph Data", "Unknown"]; + +/// The list of kinds in `lang` when `s` is the warning about an SVG's variables that aren't text +/// and `caps` are its captures. Each entry is a kind of [`LEFT_OUT_KINDS`] or a `trait` the file +/// names, in backticks with each backtick in it doubled, followed by its count in parentheses; the +/// entries are separated by `, `. A kind of [`LEFT_OUT_KINDS`] is shown in `lang`, a `trait` as the +/// warning writes it, and the entries keep their order and counts, joined with the +/// `variable-list-two` row for two, and the `variable-list-middle` and `variable-list-end` rows for +/// more; a missing row leaves its part in English. `None` for any other message, or a list that +/// does not have that form. +fn left_out_kinds(lang: Lang, s: &str, caps: &[(&str, &str)]) -> Option { + let [("kinds", kinds)] = caps else { return None }; + if s.strip_prefix("variables that aren't text were left out: ") != Some(*kinds) { + return None; + } + let catalog = lang.catalog(); + let mut entries = Vec::new(); + let mut rest = *kinds; + loop { + let (name, after) = if let Some(quoted) = rest.strip_prefix('`') { + // The `trait` ends at the first backtick that is not doubled. + let mut at = 0; + let close = loop { + let found = at + quoted[at..].find('`')?; + if quoted[found + 1..].starts_with('`') { + at = found + 2; + } else { + break found; + } + }; + rest.split_at(close + 2) + } else { + let kind = LEFT_OUT_KINDS.iter().find(|k| rest.starts_with(**k))?; + (catalog.contextual("variable-kind", kind).unwrap_or(kind), &rest[kind.len()..]) + }; + let (count, after) = after.strip_prefix(" (")?.split_once(')')?; + if count.is_empty() || !count.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + entries.push(format!("{name} ({count})")); + if after.is_empty() { + break; + } + rest = after.strip_prefix(", ")?; + } + 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)]) + }; + match entries.as_slice() { + [] => None, + [one] => Some(one.clone()), + [a, b] => Some(join("variable-list-two", a, b)), + [first, middle @ .., last] => { + let head = middle.iter().fold(first.clone(), |acc, w| join("variable-list-middle", &acc, w)); + Some(join("variable-list-end", &head, last)) + } + } +} + /// 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 e861e61fec..7f1cee4b47 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6590,6 +6590,13 @@ digits Malayalam Malaiàlam @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} més de {MAX_CSV_ROWS} conjunts de dades: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} més de {MAX_CSV_COLS} variables: Importa conjunts de dades en llegeix com a màxim {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} les variables que no són text s’han omès: {kinds} +variable-kind Visibility Visibilitat +variable-kind Linked File Fitxer enllaçat +variable-kind Graph Data Dades del gràfic +variable-kind Unknown Desconegut +variable-list-two {0}, {1} {0} i {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} i {1} @msg a new document won't read these variables back with their kind: {names} un document nou no tornarà a llegir aquestes variables amb el seu tipus: {names} @msg a new document refuses this file because of these variables: {names} un document nou rebutja aquest fitxer a causa d'aquestes variables: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them la capçalera `{header}` de `{name}` es tornaria a llegir com la variable `{other}`: canvieu el nom d’una de les dues diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1a4d359b93..8349c8619f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5470,6 +5470,13 @@ imageTrace Outline Obrys @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} více než {MAX_CSV_ROWS} sad dat: Importovat sady dat načte nejvýše {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} více než {MAX_CSV_COLS} proměnných: Importovat sady dat načte nejvýše {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} proměnné, které nejsou textové, byly vynechány: {kinds} +variable-kind Visibility Viditelnost +variable-kind Linked File Propojený soubor +variable-kind Graph Data Data grafu +variable-kind Unknown Neznámý +variable-list-two {0}, {1} {0} a {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} a {1} @msg a new document won't read these variables back with their kind: {names} nový dokument tyto proměnné nenačte zpět s jejich druhem: {names} @msg a new document refuses this file because of these variables: {names} nový dokument tento soubor kvůli těmto proměnným odmítne: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them záhlaví `{header}` pro `{name}` by se načetlo jako proměnná `{other}`: jednu z nich přejmenujte diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 723766f020..c7c200f633 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6335,6 +6335,13 @@ mark-style Japanese Japansk @msg {k} has control characters {k} indeholder kontroltegn @msg {k} has control characters or line breaks {k} indeholder kontroltegn eller linjeskift @msg variables that aren't text were left out: {kinds} variabler, der ikke er tekst, blev udeladt: {kinds} +variable-kind Visibility Synlighed +variable-kind Linked File Koblet fil +variable-kind Graph Data Grafdata +variable-kind Unknown Ukendt +variable-list-two {0}, {1} {0} og {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} og {1} @msg a new document won't read these variables back with their kind: {names} et nyt dokument læser ikke disse variabler tilbage med deres type: {names} @msg a new document refuses this file because of these variables: {names} et nyt dokument afviser denne fil på grund af disse variabler: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them overskriften `{header}` for `{name}` ville blive læst som variablen `{other}`: omdøb en af dem diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21a07e09e5..79315fe007 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5076,6 +5076,13 @@ theme Appearance Erscheinungsbild @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mehr als {MAX_CSV_ROWS} Datensätze: „Datensätze importieren“ liest höchstens {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mehr als {MAX_CSV_COLS} Variablen: „Datensätze importieren“ liest höchstens {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} die Variablen, die kein Text sind, wurden ausgelassen: {kinds} +variable-kind Visibility Sichtbarkeit +variable-kind Linked File Verknüpfte Datei +variable-kind Graph Data Diagrammdaten +variable-kind Unknown Unbekannt +variable-list-two {0}, {1} {0} und {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} und {1} @msg a new document won't read these variables back with their kind: {names} ein neues Dokument liest diese Variablen nicht mit ihrer Art zurück: {names} @msg a new document refuses this file because of these variables: {names} ein neues Dokument lehnt diese Datei wegen dieser Variablen ab: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them die Kopfzeile `{header}` für `{name}` würde als die Variable `{other}` gelesen: Benennen Sie eine der beiden um diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ebd167f397..828dafa3e2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5116,6 +5116,13 @@ digits Malayalam Μαλαγιάλαμ @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} περισσότερα από {MAX_CSV_ROWS} σύνολα δεδομένων: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} περισσότερες από {MAX_CSV_COLS} μεταβλητές: η Εισαγωγή συνόλων δεδομένων διαβάζει έως {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} οι μεταβλητές που δεν είναι κειμένου παραλείφθηκαν: {kinds} +variable-kind Visibility Ορατότητα +variable-kind Linked File Συνδεδεμένο αρχείο +variable-kind Graph Data Δεδομένα γραφήματος +variable-kind Unknown Άγνωστο +variable-list-two {0}, {1} {0} και {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} και {1} @msg a new document won't read these variables back with their kind: {names} ένα νέο έγγραφο δεν θα διαβάσει ξανά αυτές τις μεταβλητές με το είδος τους: {names} @msg a new document refuses this file because of these variables: {names} ένα νέο έγγραφο απορρίπτει αυτό το αρχείο λόγω αυτών των μεταβλητών: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them η κεφαλίδα `{header}` για το `{name}` θα διαβαζόταν ως η μεταβλητή `{other}`: μετονομάστε μία από τις δύο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 27d7d4aaf8..1a762697b2 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5166,6 +5166,13 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} más de {MAX_CSV_ROWS} conjuntos de datos: Importar conjuntos de datos lee como máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} más de {MAX_CSV_COLS} variables: Importar conjuntos de datos lee como máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} se omitieron las variables que no son de texto: {kinds} +variable-kind Visibility Visibilidad +variable-kind Linked File Archivo vinculado +variable-kind Graph Data Datos del gráfico +variable-kind Unknown Desconocido +variable-list-two {0}, {1} {0} y {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} y {1} @msg a new document won't read these variables back with their kind: {names} un documento nuevo no volverá a leer estas variables con su tipo: {names} @msg a new document refuses this file because of these variables: {names} un documento nuevo rechaza este archivo por estas variables: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them el encabezado `{header}` de `{name}` se leería como la variable `{other}`: cambie el nombre de una de las dos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3f29fd7f7a..c46aa990b7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5381,6 +5381,13 @@ imageTrace Outline Ääriviiva @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} yli {MAX_CSV_ROWS} tietojoukkoa: Tuo tietojoukot lukee enintään {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} yli {MAX_CSV_COLS} muuttujaa: Tuo tietojoukot lukee enintään {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} muut kuin tekstimuuttujat jätettiin pois: {kinds} +variable-kind Visibility Näkyvyys +variable-kind Linked File Linkitetty tiedosto +variable-kind Graph Data Kaavion tiedot +variable-kind Unknown Tuntematon +variable-list-two {0}, {1} {0} ja {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} ja {1} @msg a new document won't read these variables back with their kind: {names} uusi asiakirja ei lue näitä muuttujia takaisin niiden lajin mukaisina: {names} @msg a new document refuses this file because of these variables: {names} uusi asiakirja hylkää tämän tiedoston näiden muuttujien vuoksi: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them muuttujan `{name}` otsikko `{header}` luettaisiin muuttujaksi `{other}`: nimeä toinen niistä uudelleen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20e94749c5..4e96c03282 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5142,7 +5142,14 @@ axis Both Les deux @msg variables are locked les variables sont verrouillées @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} -@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ({kinds}) ont été ignorées +@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ont été ignorées : {kinds} +variable-kind Visibility Visibilité +variable-kind Linked File Fichier lié +variable-kind Graph Data Données du graphe +variable-kind Unknown Inconnu +variable-list-two {0}, {1} {0} et {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} et {1} @msg a new document won't read these variables back with their kind: {names} un nouveau document ne relira pas ces variables avec leur type : {names} @msg a new document refuses this file because of these variables: {names} un nouveau document refuse ce fichier à cause de ces variables : {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’en-tête `{header}` de `{name}` serait relu comme la variable `{other}` : renommez l’une des deux diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6fe8f254f4..7c1ad7f0e2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8698,7 +8698,14 @@ antiAlias Sharp शार्प @msg variable `{name}` is declared twice वेरिएबल `{name}` दो बार घोषित है @msg variable `{to}` already exists वेरिएबल `{to}` पहले से मौजूद है @msg variables are locked वेरिएबल्स लॉक हैं -@msg variables that aren't text were left out: {kinds} वेरिएबल जो टेक्स्ट नहीं छोड़े गए थे: {kinds} +@msg variables that aren't text were left out: {kinds} जो वेरिएबल टेक्स्ट नहीं हैं, उन्हें छोड़ दिया गया: {kinds} +variable-kind Visibility दृश्यता +variable-kind Linked File लिंक्ड फ़ाइल +variable-kind Graph Data ग्राफ़ डेटा +variable-kind Unknown अज्ञात +variable-list-two {0}, {1} {0} और {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} और {1} @msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version ने {v} लौटाया; यह होस्ट संस्करण {ABI_VERSION} लागू करता है @msg vc_alloc returned 0 (out of memory) vc_alloc ने 0 लौटाया (मेमोरी खत्म) @msg vc_alloc returned a block outside memory vc_alloc ने मेमोरी के बाहर का ब्लॉक लौटाया diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a93411b47..0f70673e7a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5986,6 +5986,13 @@ imageTrace Outline Körvonal @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} több mint {MAX_CSV_ROWS} adatkészlet: az Adatkészletek importálása legfeljebb {MAX_CSV_ROWS} adatkészletet olvas be @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} több mint {MAX_CSV_COLS} változó: az Adatkészletek importálása legfeljebb {MAX_CSV_COLS} változót olvas be @msg variables that aren't text were left out: {kinds} a nem szöveges változók kimaradtak: {kinds} +variable-kind Visibility Láthatóság +variable-kind Linked File Csatolt fájl +variable-kind Graph Data Diagramadatok +variable-kind Unknown Ismeretlen +variable-list-two {0}, {1} {0} és {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} és {1} @msg a new document won't read these variables back with their kind: {names} egy új dokumentum nem a fajtájukkal olvassa vissza ezeket a változókat: {names} @msg a new document refuses this file because of these variables: {names} egy új dokumentum ezen változók miatt elutasítja ezt a fájlt: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them a(z) `{name}` változó `{header}` fejléce a(z) `{other}` változóként olvasódna vissza: nevezze át az egyiket diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 360ec1d5ba..97f0dcfdc7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5205,6 +5205,13 @@ axis Both Entrambi @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} più di {MAX_CSV_ROWS} set di dati: Importa set di dati ne legge al massimo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} più di {MAX_CSV_COLS} variabili: Importa set di dati ne legge al massimo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} le variabili che non sono di testo sono state escluse: {kinds} +variable-kind Visibility Visibilità +variable-kind Linked File File collegato +variable-kind Graph Data Dati grafico +variable-kind Unknown Sconosciuto +variable-list-two {0}, {1} {0} e {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} e {1} @msg a new document won't read these variables back with their kind: {names} un nuovo documento non rileggerà queste variabili con il loro tipo: {names} @msg a new document refuses this file because of these variables: {names} un nuovo documento rifiuta questo file a causa di queste variabili: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them l’intestazione `{header}` di `{name}` verrebbe riletta come la variabile `{other}`: rinomina una delle due diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37089bb835..abded71630 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4566,6 +4566,13 @@ swatch Bright Violet ビビッドバイオレット @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} データセットが {MAX_CSV_ROWS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_ROWS} 個までです @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 変数が {MAX_CSV_COLS} 個を超えています: 「データセットを読み込み」が読み込めるのは {MAX_CSV_COLS} 個までです @msg variables that aren't text were left out: {kinds} テキスト以外の変数は除外されました: {kinds} +variable-kind Visibility 表示状態 +variable-kind Linked File リンクファイル +variable-kind Graph Data グラフデータ +variable-kind Unknown 不明 +variable-list-two {0}, {1} {0}、{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}、{1} @msg a new document won't read these variables back with their kind: {names} 新しいドキュメントでは、これらの変数は元の種類で読み込まれません: {names} @msg a new document refuses this file because of these variables: {names} 新しいドキュメントは、これらの変数のためにこのファイルを拒否します: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` の見出し `{header}` は変数 `{other}` として読み込まれます: どちらかの名前を変更してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25fb4f87ed..4c2cc44b25 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8398,6 +8398,13 @@ imageTrace Outline კონტური @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} {MAX_CSV_ROWS}-ზე მეტი მონაცემთა ნაკრები: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_ROWS}-ს @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} {MAX_CSV_COLS}-ზე მეტი ცვლადი: მონაცემთა ნაკრებების იმპორტი კითხულობს მაქსიმუმ {MAX_CSV_COLS}-ს @msg variables that aren't text were left out: {kinds} ცვლადები, რომლებიც ტექსტი არ არის, გამოტოვებულია: {kinds} +variable-kind Visibility ხილვადობა +variable-kind Linked File დაკავშირებული ფაილი +variable-kind Graph Data დიაგრამის მონაცემები +variable-kind Unknown უცნობი +variable-list-two {0}, {1} {0} და {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} და {1} @msg a new document won't read these variables back with their kind: {names} ახალი დოკუმენტი ამ ცვლადებს მათი ტიპით ვერ წაიკითხავს: {names} @msg a new document refuses this file because of these variables: {names} ახალი დოკუმენტი ამ ფაილს ამ ცვლადების გამო უარყოფს: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`-ის სათაური `{header}` წაიკითხება როგორც ცვლადი `{other}`: გადაარქვით სახელი ერთ-ერთს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0787180a1c..4cfd135e04 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4493,6 +4493,13 @@ theme Appearance 외관 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 데이터 세트가 {MAX_CSV_ROWS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_ROWS}개를 읽습니다 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 변수가 {MAX_CSV_COLS}개보다 많습니다: 데이터 세트 가져오기는 최대 {MAX_CSV_COLS}개를 읽습니다 @msg variables that aren't text were left out: {kinds} 텍스트가 아닌 변수는 제외되었습니다: {kinds} +variable-kind Visibility 가시성 +variable-kind Linked File 연결된 파일 +variable-kind Graph Data 그래프 데이터 +variable-kind Unknown 알 수 없음 +variable-list-two {0}, {1} {0} 및 {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} 및 {1} @msg a new document won't read these variables back with their kind: {names} 새 문서는 이 변수들을 원래 종류로 다시 읽지 않습니다: {names} @msg a new document refuses this file because of these variables: {names} 새 문서는 이 변수들 때문에 이 파일을 거부합니다: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}`의 머리글 `{header}`은(는) 변수 `{other}`(으)로 다시 읽힙니다: 둘 중 하나의 이름을 바꾸십시오 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ab30a3639f..d82d350c56 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8500,6 +8500,13 @@ swatch Bright Violet Felviolet @msg the spine has no segments de as heeft geen segmenten @msg variables are locked variabelen zijn vergrendeld @msg variables that aren't text were left out: {kinds} variabelen die geen tekst zijn, zijn weggelaten: {kinds} +variable-kind Visibility Zichtbaarheid +variable-kind Linked File Gekoppeld bestand +variable-kind Graph Data Diagramgegevens +variable-kind Unknown Onbekend +variable-list-two {0}, {1} {0} en {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} en {1} @msg a new document won't read these variables back with their kind: {names} een nieuw document leest deze variabelen niet terug met hun soort: {names} @msg a new document refuses this file because of these variables: {names} een nieuw document weigert dit bestand vanwege deze variabelen: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them de kop `{header}` voor `{name}` zou worden gelezen als de variabele `{other}`: wijzig de naam van een van beide diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 085935a9bd..0d0bcc7e16 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5296,6 +5296,13 @@ imageTrace Outline Kontur @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} więcej niż {MAX_CSV_ROWS} zestawów danych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} więcej niż {MAX_CSV_COLS} zmiennych: Importuj zestawy danych odczytuje najwyżej {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} pominięto zmienne, które nie są tekstowe: {kinds} +variable-kind Visibility Widoczność +variable-kind Linked File Połączony plik +variable-kind Graph Data Dane wykresu +variable-kind Unknown Nieznany +variable-list-two {0}, {1} {0} i {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} i {1} @msg a new document won't read these variables back with their kind: {names} nowy dokument nie odczyta tych zmiennych z ich rodzajem: {names} @msg a new document refuses this file because of these variables: {names} nowy dokument odrzuca ten plik z powodu tych zmiennych: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them nagłówek `{header}` dla `{name}` zostałby odczytany jako zmienna `{other}`: zmień nazwę jednej z nich diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0289161fe4..a378e3eb32 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4526,6 +4526,13 @@ axis Both Ambos @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mais de {MAX_CSV_ROWS} conjuntos de dados: Importar Conjuntos de Dados lê no máximo {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mais de {MAX_CSV_COLS} variáveis: Importar Conjuntos de Dados lê no máximo {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} as variáveis que não são de texto foram omitidas: {kinds} +variable-kind Visibility Visibilidade +variable-kind Linked File Arquivo Vinculado +variable-kind Graph Data Dados do Gráfico +variable-kind Unknown Desconhecido +variable-list-two {0}, {1} {0} e {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} e {1} @msg a new document won't read these variables back with their kind: {names} um novo documento não lerá essas variáveis de volta com o tipo delas: {names} @msg a new document refuses this file because of these variables: {names} um novo documento recusa este arquivo por causa destas variáveis: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them o cabeçalho `{header}` de `{name}` seria lido como a variável `{other}`: renomeie uma delas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e45ac9423a..da313a3213 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5203,6 +5203,13 @@ axis Both Оба @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} больше {MAX_CSV_ROWS} наборов данных: «Импортировать наборы данных» читает не более {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} больше {MAX_CSV_COLS} переменных: «Импортировать наборы данных» читает не более {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} переменные, которые не являются текстовыми, пропущены: {kinds} +variable-kind Visibility Видимость +variable-kind Linked File Связанный файл +variable-kind Graph Data Данные диаграммы +variable-kind Unknown Неизвестно +variable-list-two {0}, {1} {0} и {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} и {1} @msg a new document won't read these variables back with their kind: {names} новый документ не прочитает эти переменные обратно с их типом: {names} @msg a new document refuses this file because of these variables: {names} новый документ отклоняет этот файл из-за этих переменных: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` будет прочитан как переменная `{other}`: переименуйте одну из них diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 95e7c34b47..70dad9b198 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5058,6 +5058,13 @@ axis Both Båda @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} fler än {MAX_CSV_ROWS} datauppsättningar: Importera datauppsättningar läser högst {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} fler än {MAX_CSV_COLS} variabler: Importera datauppsättningar läser högst {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} variabler som inte är text utelämnades: {kinds} +variable-kind Visibility Synlighet +variable-kind Linked File Länkad fil +variable-kind Graph Data Diagramdata +variable-kind Unknown Okänd +variable-list-two {0}, {1} {0} och {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} och {1} @msg a new document won't read these variables back with their kind: {names} ett nytt dokument läser inte tillbaka dessa variabler med deras typ: {names} @msg a new document refuses this file because of these variables: {names} ett nytt dokument avvisar den här filen på grund av dessa variabler: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them rubriken `{header}` för `{name}` skulle läsas som variabeln `{other}`: byt namn på en av dem diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b632e5cac3..8d7767bb10 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2230,6 +2230,70 @@ fn file_info_control_character_refusals_translate_in_every_complete_catalog() { } } +/// The warning about an SVG's variables that aren't text shows each kind VectorCraft names in the +/// interface language and each `trait` the file names, in backticks, as the warning writes it, the +/// entries in their order with their counts and joined as the language joins a list, in every +/// complete-message language. +#[test] +fn svg_variable_kinds_left_out_translate_in_every_complete_catalog() { + const KINDS: [&str; 4] = ["Visibility", "Linked File", "Graph Data", "Unknown"]; + let warning = |kinds: &str| format!("variables that aren't text were left out: {kinds}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let cat = lang.catalog(); + for ctx in ["variable-list-two", "variable-list-middle", "variable-list-end"] { + assert!(cat.contextual(ctx, "{0}, {1}").is_some(), "{code} has no {ctx} row"); + } + let kind = |k: &str| cat.contextual("variable-kind", k).unwrap_or_else(|| panic!("{code} has no variable-kind row for {k}")); + let template = message(lang, &warning("{kinds}")); + assert!(template.contains("{kinds}"), "{code}: {template}"); + let shown_with = |list: &str| template.replace("{kinds}", list); + let join = |ctx: &str, a: &str, b: &str| cat.contextual(ctx, "{0}, {1}").unwrap_or("{0}, {1}").replace("{0}", a).replace("{1}", b); + for k in KINDS { + // One kind, with its count. + let shown = message(lang, &warning(&format!("{k} (3)"))); + assert_eq!(shown, shown_with(&format!("{} (3)", kind(k))), "{code}"); + assert_ne!(kind(k), k, "{code}: {k} stays English"); + } + // Two entries, one a `trait` that holds a backtick, a list separator and a count. + let shown = message(lang, &warning("Unknown (1), `a``b (1), c` (2)")); + assert_eq!(shown, shown_with(&join("variable-list-two", &format!("{} (1)", kind("Unknown")), "`a``b (1), c` (2)")), "{code}"); + // Every kind, in the engine's order and in reverse, then a `trait` that is a kind's name. + for kinds in [KINDS.to_vec(), KINDS.iter().rev().copied().collect()] { + let list = kinds.iter().enumerate().map(|(i, k)| format!("{k} ({})", i + 1)).collect::>().join(", "); + let shown = message(lang, &warning(&format!("{list}, `Visibility` (12)"))); + let entries: Vec = + kinds.iter().enumerate().map(|(i, k)| format!("{} ({})", kind(k), i + 1)).chain(["`Visibility` (12)".to_string()]).collect(); + let head = entries[1..entries.len() - 1].iter().fold(entries[0].clone(), |acc, e| join("variable-list-middle", &acc, e)); + assert_eq!(shown, shown_with(&join("variable-list-end", &head, &entries[entries.len() - 1])), "{code}"); + } + } + let de = Lang::from_code("de").expect("registered"); + assert_eq!( + message(de, &warning("Visibility (2), Linked File (1), Graph Data (4), Unknown (1)")), + "die Variablen, die kein Text sind, wurden ausgelassen: Sichtbarkeit (2), Verknüpfte Datei (1), Diagrammdaten (4) und Unbekannt (1)" + ); + assert_eq!( + message(de, &warning("Unknown (1), `a``b (1), c` (2)")), + "die Variablen, die kein Text sind, wurden ausgelassen: Unbekannt (1) und `a``b (1), c` (2)" + ); + assert_eq!(message(de, &warning("`Visibility` (1)")), "die Variablen, die kein Text sind, wurden ausgelassen: `Visibility` (1)"); + let fr = Lang::from_code("fr").expect("registered"); + assert_eq!(message(fr, &warning("Visibility (1)")), "les variables qui ne sont pas du texte ont été ignorées : Visibilité (1)"); + let ja = Lang::from_code("ja").expect("registered"); + assert_eq!( + message(ja, &warning("Visibility (1), Linked File (2), Unknown (1)")), + "テキスト以外の変数は除外されました: 表示状態 (1)、リンクファイル (2)、不明 (1)" + ); + // A list not in the warning's form, and a `trait` whose backticks don't close, stay as written. + for kinds in ["fileref (1)", "`abc (1)", "Visibility (x)", "Visibility (1),Linked File (2)"] { + assert_eq!(message(de, &warning(kinds)), format!("die Variablen, die kein Text sind, wurden ausgelassen: {kinds}")); + } + // English shows the warning as the engine wrote it. + let english = warning("Visibility (2), `a``b (1), c` (1)"); + assert_eq!(message(Lang::EN, &english), english); +} + /// Every complete-message catalog has a row for each error that `type.compositeFonts.set`, /// `.export` and `.import`, the composite font checks behind them and the Composite Fonts dialog /// give, and translates them with the font name, the key and the class key kept, and the reason diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d8249b1c79..09f3a10999 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6488,6 +6488,13 @@ theme Appearance Görünüm @msg an image has no pixels and was left out piksel içermeyen bir görüntü dışarıda bırakıldı @msg thumbnail: no page {n} (the file has 1) thumbnail: {n}. sayfa yok (dosyada 1 sayfa var) @msg variables that aren't text were left out: {kinds} metin olmayan değişkenler dışarıda bırakıldı: {kinds} +variable-kind Visibility Görünürlük +variable-kind Linked File Bağlantılı Dosya +variable-kind Graph Data Grafik Verileri +variable-kind Unknown Bilinmiyor +variable-list-two {0}, {1} {0} ve {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} ve {1} @msg a new document won't read these variables back with their kind: {names} yeni bir belge bu değişkenleri türleriyle geri okumaz: {names} @msg a new document refuses this file because of these variables: {names} yeni bir belge bu değişkenler nedeniyle bu dosyayı reddeder: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` için `{header}` başlığı `{other}` değişkeni olarak okunur: birini yeniden adlandırın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8ebb97a5be..313b596a70 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5189,6 +5189,13 @@ axis Both Обидві @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} більше ніж {MAX_CSV_ROWS} наборів даних: «Імпортувати набори даних» читає не більше {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} більше ніж {MAX_CSV_COLS} змінних: «Імпортувати набори даних» читає не більше {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} змінні, що не є текстовими, пропущено: {kinds} +variable-kind Visibility Видимість +variable-kind Linked File Пов’язаний файл +variable-kind Graph Data Дані діаграми +variable-kind Unknown Невідомо +variable-list-two {0}, {1} {0} і {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} і {1} @msg a new document won't read these variables back with their kind: {names} новий документ не прочитає ці змінні назад з їхнім видом: {names} @msg a new document refuses this file because of these variables: {names} новий документ відхиляє цей файл через ці змінні: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them заголовок `{header}` для `{name}` буде прочитано як змінну `{other}`: перейменуйте одну з них diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a9a9cb140a..db144787a8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5737,6 +5737,13 @@ theme Appearance Giao diện @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} hơn {MAX_CSV_ROWS} tập dữ liệu: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} hơn {MAX_CSV_COLS} biến số: Nhập tập dữ liệu chỉ đọc tối đa {MAX_CSV_COLS} @msg variables that aren't text were left out: {kinds} các biến số không phải văn bản đã bị bỏ qua: {kinds} +variable-kind Visibility Hiển thị +variable-kind Linked File Tệp được liên kết +variable-kind Graph Data Dữ liệu biểu đồ +variable-kind Unknown Không xác định +variable-list-two {0}, {1} {0} và {1} +variable-list-middle {0}, {1} {0}, {1} +variable-list-end {0}, {1} {0} và {1} @msg a new document won't read these variables back with their kind: {names} tài liệu mới sẽ không đọc lại các biến số này đúng loại: {names} @msg a new document refuses this file because of these variables: {names} tài liệu mới sẽ từ chối tệp này vì các biến số sau: {names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them tiêu đề `{header}` của `{name}` sẽ được đọc thành biến số `{other}`: hãy đổi tên một trong hai diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3a87e6b84..096a1817b2 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3922,6 +3922,13 @@ digits Malayalam 马拉雅拉姆数字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 数据集超过 {MAX_CSV_ROWS} 个:“导入数据集”最多读取 {MAX_CSV_ROWS} 个 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 变量超过 {MAX_CSV_COLS} 个:“导入数据集”最多读取 {MAX_CSV_COLS} 个 @msg variables that aren't text were left out: {kinds} 已省略非文本变量:{kinds} +variable-kind Visibility 可见性 +variable-kind Linked File 链接文件 +variable-kind Graph Data 图表数据 +variable-kind Unknown 未知 +variable-list-two {0}, {1} {0}和{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}和{1} @msg a new document won't read these variables back with their kind: {names} 新文档不会按原类型读回这些变量:{names} @msg a new document refuses this file because of these variables: {names} 新文档会因这些变量而拒绝此文件:{names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的标题 `{header}` 会被读作变量 `{other}`:请重命名其中一个 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52715f8360..6a120266be 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5189,6 +5189,13 @@ digits Malayalam 馬來亞拉姆數字 @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} 資料集超過 {MAX_CSV_ROWS} 個:「匯入資料集」最多讀取 {MAX_CSV_ROWS} 個 @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} 變數超過 {MAX_CSV_COLS} 個:「匯入資料集」最多讀取 {MAX_CSV_COLS} 個 @msg variables that aren't text were left out: {kinds} 已略過非文字變數:{kinds} +variable-kind Visibility 可見性 +variable-kind Linked File 連結檔案 +variable-kind Graph Data 圖表資料 +variable-kind Unknown 未知 +variable-list-two {0}, {1} {0}和{1} +variable-list-middle {0}, {1} {0}、{1} +variable-list-end {0}, {1} {0}和{1} @msg a new document won't read these variables back with their kind: {names} 新文件不會以原類型讀回這些變數:{names} @msg a new document refuses this file because of these variables: {names} 新文件會因這些變數而拒絕此檔案:{names} @msg the header `{header}` for `{name}` would read back as the variable `{other}`: rename one of them `{name}` 的標題 `{header}` 會被讀作變數 `{other}`:請重新命名其中一個 diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index aab1892ea2..30629f3fd6 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -792,12 +792,12 @@ mod tests { let xml = r#""#; app.run("variable.loadLibrary", json!({"xml": xml})).unwrap(); assert_eq!(app.ui.status, status, "the load gives no warning"); - let warning = "variables that aren't text were left out: other (1)"; + let warning = "variables that aren't text were left out: `other` (1)"; let langs: Vec = Lang::all().filter(|l| l.code() != "en").collect(); assert!(langs.len() >= 23, "{} languages", langs.len()); for l in langs { let shown = message(l, warning); - assert!(!shown.contains("left out") && shown.contains("other") && shown.contains('1'), "{}: {shown}", l.code()); + assert!(!shown.contains("left out") && shown.contains("`other` (1)"), "{}: {shown}", l.code()); } } diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..0d9993a279 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1029,7 +1029,12 @@ data larger than 8 MiB or holding more than 2,000,000 XML nodes is left out (the reads), each with a warning. With `outlineText`, the bound type is written as outlines, so its text variables open unbound (with a warning). `document.open` reads the variable data of an SVG back (unless the SVG reopens from Preserve Editing): its text variables and data sets, no active data set, and each text variable bound to the type -object its `docRef` names; the art stays as the file draws it. Variable data that `variable.loadLibrary` would refuse +object its `docRef` names; the art stays as the file draws it. Variables of other kinds are left out with one warning +that names each kind once, in the order it first comes, with its count: ``variables that aren't text were left out: +Visibility (2), Linked File (1), Unknown (1), `custom` (1)``. Visibility, Linked File and Graph Data are the +`visibility`, `fileref` and `graphdata` traits, Unknown is a variable without a `trait`, and any other `trait` is +written as the file writes it, in backticks, with each backtick in it doubled. The status bar shows the kinds VectorCraft +names in the interface language. Variable data that `variable.loadLibrary` would refuse is left out with the warning "the file's variable data wasn't read", and the art opens. `svgz` takes the same options and writes the SVG gzipped (`.svgz` files also open, place and paste). `run_command document.save {path: "x.svg", svg: {…}}` saves as SVG (or `.svgz`). Colorized grayscale and 1-bit images export in their fill color; linked mode writes a coverage PNG, and Tiny 1.2 writes a colorized PNG. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..7a29ff6fe1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -848,6 +848,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: Import Data Sets… (`dataset.import`) defines the variables a file's header names that the document lacks, unbound. `#Shown` defines a visibility variable, `@Photo` defines an image variable, and a header without a prefix defines a text variable. A header that is a variable's exact name keeps naming it, and any other `%` header (graph data files) is refused. - Variables: Load Variable Library… in the Variables panel menu (`variable.loadLibrary`) replaces the document's variables and data sets with a variable library's, read from its XML file, in one undo step: every data set is deleted, and every variable is deleted with its bindings and values, except a variable the library also declares with the same kind, which stays bound so the library's data sets change its objects (#4136); then the library's other variables are defined, unbound: text, visibility, image (linked file) and graph variables, and variables without a known `trait` as unknown. Its data sets take text values from each value's `p` elements, one paragraph each, visibility values from `true` or `false`, image values from a file's absolute path or `file:` URL, and graph values from a `data` element of series names and rows. - Variables: Save Variable Library… in the Variables panel menu (`variable.saveLibrary`) writes the document's variables of every kind and its data sets as a variable library's XML file, which Load Variable Library reads back with the same variables, kinds, data set names and values. + - Variables: opening an SVG whose variable data holds variables that aren't text warns about them by kind (Visibility, Linked File, Graph Data, or Unknown for a variable without a `trait`) with a count for each, and the status bar shows those kinds and the list in the interface language. Any other `trait` stays as the file writes it, in backticks, so a `trait` such as `Visibility` or one with a comma stays a single entry. This is VectorCraft's own rule. Regression tests: `svg_variable_data_warning_names_each_kind_left_out` in `crates/engine/src/tests/variables.rs`, `svg_variable_kinds_left_out_translate_in_every_complete_catalog` in `crates/ui-egui/src/i18n/tests.rs`. - Variables: Variable Options… in the Variables panel menu, or a double click on a variable, shows the variable's name and kind, and OK changes either or both in one undo step (`variable.rename {name, newName?, kind?}`), as the [Work with variables](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/work-with-variables.html) page describes. VectorCraft's own rule for a kind change: objects that can't hold the new kind are unbound, and the variable's values in every data set are dropped. - JSON-lines control channel with real egui pointer and keyboard injection. - Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both. From 901b00bc7fbe2668d03383dd50e9f6bab13b28c6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 14:51:57 -0800 Subject: [PATCH 073/138] i18n: five messages with literal braces get exact catalog rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `scope` error, the regular expression error `numbers out of order in {} quantifier` and the freeform gradient hint for `paint.editGradient` are translated in every complete-message catalog through a row that doubles its braces. The older rows read the braced example as a placeholder, so they also translated other text with the same start and end; they are removed, Georgian's two duplicates included. Catalan, Danish, Greek, Spanish, Finnish, Hindi, Swedish and Vietnamese gain rows for the last three. literal_brace_messages_have_exact_rows_in_complete_languages checks each row, the displayed text and that no placeholder row remains. --- crates/ui-egui/src/i18n/ca.tsv | 7 ++-- crates/ui-egui/src/i18n/cs.tsv | 10 +++--- crates/ui-egui/src/i18n/da.tsv | 7 ++-- crates/ui-egui/src/i18n/de.tsv | 10 +++--- crates/ui-egui/src/i18n/el.tsv | 7 ++-- crates/ui-egui/src/i18n/es.tsv | 7 ++-- crates/ui-egui/src/i18n/fi.tsv | 7 ++-- crates/ui-egui/src/i18n/fr.tsv | 10 +++--- crates/ui-egui/src/i18n/hi.tsv | 7 ++-- crates/ui-egui/src/i18n/hu.tsv | 10 +++--- crates/ui-egui/src/i18n/it.tsv | 10 +++--- crates/ui-egui/src/i18n/ja.tsv | 10 +++--- crates/ui-egui/src/i18n/ka.tsv | 2 -- crates/ui-egui/src/i18n/ko.tsv | 10 +++--- crates/ui-egui/src/i18n/nl.tsv | 10 +++--- crates/ui-egui/src/i18n/pl.tsv | 10 +++--- crates/ui-egui/src/i18n/pt-br.tsv | 10 +++--- crates/ui-egui/src/i18n/ru.tsv | 10 +++--- crates/ui-egui/src/i18n/sv.tsv | 7 ++-- crates/ui-egui/src/i18n/tests.rs | 55 ++++++++++++++++++++++++++--- crates/ui-egui/src/i18n/tr.tsv | 10 +++--- crates/ui-egui/src/i18n/uk.tsv | 10 +++--- crates/ui-egui/src/i18n/vi.tsv | 7 ++-- crates/ui-egui/src/i18n/zh-hans.tsv | 10 +++--- crates/ui-egui/src/i18n/zh-hant.tsv | 10 +++--- docs/target-app-parity.md | 1 + 26 files changed, 167 insertions(+), 97 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2f9f1d8fdc..1b7675ce3c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4752,7 +4752,7 @@ digits Malayalam Malaiàlam Composite Fonts Tipus de lletra compostos Export Composite Fonts Exporta tipus de lletra compostos Import Composite Fonts Importa tipus de lletra compostos -@msg each font must be {name, parts} cada tipus de lletra ha de ser {name, parts} +@msg each font must be {{name, parts}} cada tipus de lletra ha de ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clau desconeguda `{k}`; un tipus de lletra admet name i parts @msg each font needs a name cada tipus de lletra necessita un nom @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` no pot anomenar un tipus de lletra compost (d’1 a {COMPOSITE_NAME_MAX} caràcters, sense caràcters de control) @@ -4765,7 +4765,10 @@ digits Malayalam Malaiàlam @msg two composite fonts are named `{_1}` dos tipus de lletra compostos es diuen `{_1}` @msg `{_1}` is the name of an installed font `{_1}` és el nom d’un tipus de lletra instal·lat @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, un tipus de lletra compost -@msg give fonts: [{name, parts}…] indiqueu fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indiqueu fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` ha de ser "document", {{artboards: [index, …]}} o {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier nombres desordenats al quantificador {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pintura no és un degradat de forma lliure (apliqueu-ne un amb paint.editGradient {{kind: "freeform"}}) @msg path is empty path és buit @msg fonts must be a list of composite fonts fonts ha de ser una llista de tipus de lletra compostos @msg names must be strings names ha de contenir cadenes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4628b89a1d..b966845e05 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1684,7 +1684,7 @@ digits Malayalam Malajálamské Composite Fonts Složená písma Export Composite Fonts Exportovat složená písma Import Composite Fonts Importovat složená písma -@msg each font must be {name, parts} každé písmo musí být {name, parts} +@msg each font must be {{name, parts}} každé písmo musí být {{name, parts}} @msg unknown key `{k}`; a font takes name and parts neznámý klíč `{k}`; písmo přijímá name a parts @msg each font needs a name každé písmo potřebuje název @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nemůže být názvem složeného písma (1 až {COMPOSITE_NAME_MAX} znaků, bez řídicích znaků) @@ -1697,7 +1697,7 @@ digits Malayalam Malajálamské @msg two composite fonts are named `{_1}` dvě složená písma se jmenují `{_1}` @msg `{_1}` is the name of an installed font `{_1}` je název nainstalovaného písma @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} používá `{font}`, což je složené písmo -@msg give fonts: [{name, parts}…] zadejte fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] zadejte fonts: [{{name, parts}}…] @msg path is empty path je prázdné @msg fonts must be a list of composite fonts fonts musí být seznam složených písem @msg names must be strings names musí být řetězce @@ -8028,7 +8028,7 @@ breakText Glyphs Glyfy @msg `scale` must be a number from 0.001 to 1000 `scale` musí být číslo od 0.001 do 1000 @msg `scale` must be a number in (0, 100] `scale` musí být číslo v rozsahu (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` musí být neprázdné pole -@msg `scope` must be "document", {artboards} or {layers} `scope` musí být "document", {artboards} nebo {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` musí být "document", {{artboards: [index, …]}} nebo {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` musí být "selection" nebo "document", ne {other} @msg `script` must be a string `script` musí být řetězec @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` je neprázdný seznam indexů řad @@ -8922,7 +8922,7 @@ breakText Glyphs Glyfy @msg nothing to print: every artboard picked is blank není co tisknout: každá zvolená pracovní plocha je prázdná @msg nothing to print: the document has no art that prints není co tisknout: dokument nemá žádnou kresbu, která se tiskne @msg nothing to repeat není co opakovat -@msg numbers out of order in {_1} quantifier čísla v kvantifikátoru {_1} jsou ve špatném pořadí +@msg numbers out of order in {{}} quantifier čísla v kvantifikátoru {{}} jsou ve špatném pořadí @msg object is not a path objekt není cesta @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object průhlednost objektu nelze nabrat na zvýrazněné znaky; vypněte Průhlednost ve volbách kapátka nebo vyberte celý objekt @msg object {_1} can't be set as point type objekt {_1} nelze nastavit jako bodový text @@ -9280,7 +9280,7 @@ breakText Glyphs Glyfy @msg the page has no area stránka nemá plochu @msg the page's type in an unread object's box isn't in its page art text stránky v rámečku nepřečteného objektu není v kresbě jeho stránky @msg the paint behind the proxy is not a gradient nátěr za aktivním políčkem není přechod -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) nátěr není volný přechod (použijte ho pomocí paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) nátěr není volný přechod (použijte ho pomocí paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function parametry nebo tělo netvoří jednu funkci @msg the parent must be a layer or sublayer nadřazený prvek musí být vrstva nebo podvrstva @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it vložený filtr SVG {name} se vykresluje jinak než filtr dokumentu s tímto názvem a nehodí se pro něj žádný volný název diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8b822be042..dd9ef25ebb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2206,7 +2206,7 @@ digits Malayalam Malayalam Composite Fonts Sammensatte skrifttyper Export Composite Fonts Eksportér sammensatte skrifttyper Import Composite Fonts Importér sammensatte skrifttyper -@msg each font must be {name, parts} hver skrifttype skal være {name, parts} +@msg each font must be {{name, parts}} hver skrifttype skal være {{name, parts}} @msg unknown key `{k}`; a font takes name and parts ukendt nøgle `{k}`; en skrifttype tager name og parts @msg each font needs a name hver skrifttype skal have et navn @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan ikke være navnet på en sammensat skrifttype (1 til {COMPOSITE_NAME_MAX} tegn, ingen kontroltegn) @@ -2219,7 +2219,10 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` to sammensatte skrifttyper hedder `{_1}` @msg `{_1}` is the name of an installed font `{_1}` er navnet på en installeret skrifttype @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} er sat med `{font}`, en sammensat skrifttype -@msg give fonts: [{name, parts}…] angiv fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] angiv fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` skal være "document", {{artboards: [index, …]}} eller {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier tal i forkert rækkefølge i kvantoren {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) malingen er ikke en friformsgradient (anvend en med paint.editGradient {{kind: "freeform"}}) @msg path is empty path er tom @msg fonts must be a list of composite fonts fonts skal være en liste med sammensatte skrifttyper @msg names must be strings names skal være strenge diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 752a60accd..dc796106d9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3707,7 +3707,7 @@ effect Points Punkte Composite Fonts Zusammengesetzte Schriften Export Composite Fonts Zusammengesetzte Schriften exportieren Import Composite Fonts Zusammengesetzte Schriften importieren -@msg each font must be {name, parts} jede Schrift muss {name, parts} sein +@msg each font must be {{name, parts}} jede Schrift muss {{name, parts}} sein @msg unknown key `{k}`; a font takes name and parts unbekannter Schlüssel `{k}`; eine Schrift nimmt name und parts @msg each font needs a name jede Schrift braucht einen Namen @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kann keine zusammengesetzte Schrift benennen (1 bis {COMPOSITE_NAME_MAX} Zeichen, keine Steuerzeichen) @@ -3720,7 +3720,7 @@ effect Points Punkte @msg two composite fonts are named `{_1}` zwei zusammengesetzte Schriften heißen `{_1}` @msg `{_1}` is the name of an installed font `{_1}` ist der Name einer installierten Schrift @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} ist in `{font}` gesetzt, einer zusammengesetzten Schrift -@msg give fonts: [{name, parts}…] geben Sie fonts an: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] geben Sie fonts an: [{{name, parts}}…] @msg path is empty path ist leer @msg fonts must be a list of composite fonts fonts muss eine Liste zusammengesetzter Schriften sein @msg names must be strings names müssen Zeichenketten sein @@ -7323,7 +7323,7 @@ breakText Glyphs Glyphen @msg `rows` must be lists of numbers or nulls, not {r} `rows` müssen Listen aus Zahlen oder null-Werten sein, nicht {r} @msg `scale` must be a number from 0.001 to 1000 `scale` muss eine Zahl von 0,001 bis 1000 sein @msg `scope.{key}` must be a non-empty array `scope.{key}` muss ein nicht leeres Array sein -@msg `scope` must be "document", {artboards} or {layers} `scope` muss „document“, {artboards} oder {layers} sein +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` muss "document", {{artboards: [index, …]}} oder {{layers: [id, …]}} sein @msg `side` must be "left", "right", "top" or "bottom" `side` muss „left“, „right“, „top“ oder „bottom“ sein @msg `side` places the artboard: leave out x, y, width and height `side` platziert die Zeichenfläche: Lassen Sie x, y, width und height weg @msg `source` is the only path in series group `target` `source` ist der einzige Pfad in der Reihengruppe `target` @@ -7503,7 +7503,7 @@ breakText Glyphs Glyphen @msg not a regular expression kein regulärer Ausdruck @msg not an action set: the text doesn't start with /version and a number kein Aktionssatz: Der Text beginnt nicht mit /version und einer Zahl @msg nothing to repeat nichts zu wiederholen -@msg numbers out of order in {_1} quantifier Zahlen in falscher Reihenfolge im Quantifizierer {_1} +@msg numbers out of order in {{}} quantifier Zahlen in falscher Reihenfolge im Quantifizierer {{}} @msg object {_1} needs a 3D effect Objekt {_1} braucht einen 3D-Effekt @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic Objekt {_1}: Ein hohles „Extrudieren und abgeflachte Kante“ hat keine Deckflächen: Aktivieren Sie „Deckflächen“, um eine Grafik zuzuweisen @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front Objekt {_1}: Bei einer Tiefe von 0 hat das Objekt nur eine Fläche: Weisen Sie seine Grafiken der Vorderseite zu @@ -7571,7 +7571,7 @@ breakText Glyphs Glyphen @msg the guide is hidden or locked die Hilfslinie ist ausgeblendet oder gesperrt @msg the library's file is outside the read roots die Datei der Bibliothek liegt außerhalb der Lesestammordner @msg the method needs an XML value die Methode braucht einen XML-Wert -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) die Farbe ist kein Freiformverlauf (wenden Sie einen mit paint.editGradient {kind} an) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) die Farbe ist kein Freiformverlauf (wenden Sie einen mit paint.editGradient {{kind: "freeform"}} an) @msg the parameters or body do not form one function die Parameter oder der Rumpf bilden keine einzelne Funktion @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it der eingefügte SVG-Filter {name} zeichnet anders als der gleichnamige Filter des Dokuments, und kein freier Name passt zu ihm @msg the pen table holds more than 255 pens die Stifttabelle enthält mehr als 255 Stifte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9b32ea177c..8c49dbdb53 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4255,7 +4255,7 @@ digits Malayalam Μαλαγιάλαμ Composite Fonts Σύνθετες γραμματοσειρές Export Composite Fonts Εξαγωγή σύνθετων γραμματοσειρών Import Composite Fonts Εισαγωγή σύνθετων γραμματοσειρών -@msg each font must be {name, parts} κάθε γραμματοσειρά πρέπει να είναι {name, parts} +@msg each font must be {{name, parts}} κάθε γραμματοσειρά πρέπει να είναι {{name, parts}} @msg unknown key `{k}`; a font takes name and parts άγνωστο κλειδί `{k}`· μια γραμματοσειρά δέχεται name και parts @msg each font needs a name κάθε γραμματοσειρά χρειάζεται όνομα @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) το `{raw}` δεν μπορεί να είναι όνομα σύνθετης γραμματοσειράς (1 έως {COMPOSITE_NAME_MAX} χαρακτήρες, χωρίς χαρακτήρες ελέγχου) @@ -4268,7 +4268,10 @@ digits Malayalam Μαλαγιάλαμ @msg two composite fonts are named `{_1}` δύο σύνθετες γραμματοσειρές ονομάζονται `{_1}` @msg `{_1}` is the name of an installed font το `{_1}` είναι όνομα εγκατεστημένης γραμματοσειράς @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: το {_2} χρησιμοποιεί την `{font}`, που είναι σύνθετη γραμματοσειρά -@msg give fonts: [{name, parts}…] δώστε fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] δώστε fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} το `scope` πρέπει να είναι "document", {{artboards: [index, …]}} ή {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier αριθμοί εκτός σειράς στον ποσοδείκτη {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) το χρώμα δεν είναι ντεγκραντέ ελεύθερης μορφής (εφαρμόστε ένα με paint.editGradient {{kind: "freeform"}}) @msg path is empty το path είναι κενό @msg fonts must be a list of composite fonts το fonts πρέπει να είναι λίστα σύνθετων γραμματοσειρών @msg names must be strings τα names πρέπει να είναι συμβολοσειρές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9c81265e9d..aec1498375 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3756,7 +3756,7 @@ digits Malayalam Malayálam Composite Fonts Fuentes compuestas Export Composite Fonts Exportar fuentes compuestas Import Composite Fonts Importar fuentes compuestas -@msg each font must be {name, parts} cada fuente debe ser {name, parts} +@msg each font must be {{name, parts}} cada fuente debe ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clave desconocida `{k}`; una fuente admite name y parts @msg each font needs a name cada fuente necesita un nombre @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` no puede nombrar una fuente compuesta (de 1 a {COMPOSITE_NAME_MAX} caracteres, sin caracteres de control) @@ -3769,7 +3769,10 @@ digits Malayalam Malayálam @msg two composite fonts are named `{_1}` dos fuentes compuestas se llaman `{_1}` @msg `{_1}` is the name of an installed font `{_1}` es el nombre de una fuente instalada @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, una fuente compuesta -@msg give fonts: [{name, parts}…] indique fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indique fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` debe ser "document", {{artboards: [index, …]}} o {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier números desordenados en el cuantificador {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pintura no es un degradado de forma libre (aplique uno con paint.editGradient {{kind: "freeform"}}) @msg path is empty path está vacío @msg fonts must be a list of composite fonts fonts debe ser una lista de fuentes compuestas @msg names must be strings names debe contener cadenas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 67897bbe68..720994c7e2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1657,7 +1657,7 @@ digits Malayalam Malajalam Composite Fonts Yhdistelmäfontit Export Composite Fonts Vie yhdistelmäfontit Import Composite Fonts Tuo yhdistelmäfontit -@msg each font must be {name, parts} jokaisen fontin on oltava {name, parts} +@msg each font must be {{name, parts}} jokaisen fontin on oltava {{name, parts}} @msg unknown key `{k}`; a font takes name and parts tuntematon avain `{k}`; fontti ottaa name ja parts @msg each font needs a name jokainen fontti tarvitsee nimen @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ei kelpaa yhdistelmäfontin nimeksi (1–{COMPOSITE_NAME_MAX} merkkiä, ei ohjausmerkkejä) @@ -1670,7 +1670,10 @@ digits Malayalam Malajalam @msg two composite fonts are named `{_1}` kahden yhdistelmäfontin nimi on `{_1}` @msg `{_1}` is the name of an installed font `{_1}` on asennetun fontin nimi @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} käyttää fonttia `{font}`, joka on yhdistelmäfontti -@msg give fonts: [{name, parts}…] anna fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] anna fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`-arvon on oltava "document", {{artboards: [index, …]}} tai {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier luvut väärässä järjestyksessä kvanttorissa {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) maali ei ole vapaamuotoinen liukuväri (käytä sellaista komennolla paint.editGradient {{kind: "freeform"}}) @msg path is empty path on tyhjä @msg fonts must be a list of composite fonts fonts on oltava luettelo yhdistelmäfonteista @msg names must be strings names on oltava merkkijonoja diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9c04f43b1b..e34374a651 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3748,7 +3748,7 @@ digits Malayalam Malayalam Composite Fonts Polices composites Export Composite Fonts Exporter des polices composites Import Composite Fonts Importer des polices composites -@msg each font must be {name, parts} chaque police doit être {name, parts} +@msg each font must be {{name, parts}} chaque police doit être {{name, parts}} @msg unknown key `{k}`; a font takes name and parts clé inconnue `{k}` ; une police prend name et parts @msg each font needs a name chaque police doit avoir un nom @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ne peut pas nommer une police composite (1 à {COMPOSITE_NAME_MAX} caractères, sans caractères de contrôle) @@ -3761,7 +3761,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` deux polices composites s’appellent `{_1}` @msg `{_1}` is the name of an installed font `{_1}` est le nom d’une police installée @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}` : {_2} utilise `{font}`, une police composite -@msg give fonts: [{name, parts}…] indiquez fonts : [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indiquez fonts : [{{name, parts}}…] @msg path is empty path est vide @msg fonts must be a list of composite fonts fonts doit être une liste de polices composites @msg names must be strings names doit contenir des chaînes @@ -7893,7 +7893,7 @@ breakText Glyphs Glyphes @msg `scale` must be a number from 0.001 to 1000 `scale` doit être un nombre compris entre 0.001 et 1000 @msg `scale` must be a number in (0, 100] `scale` doit être un nombre dans (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` doit être une liste non vide -@msg `scope` must be "document", {artboards} or {layers} `scope` doit valoir "document", {artboards} ou {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` doit valoir "document", {{artboards: [index, …]}} ou {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` doit valoir "selection" ou "document", pas {other} @msg `script` must be a string `script` doit être une chaîne @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` est une liste non vide d’indices de séries @@ -8783,7 +8783,7 @@ breakText Glyphs Glyphes @msg nothing to print: every artboard picked is blank rien à imprimer : chaque plan de travail choisi est vide @msg nothing to print: the document has no art that prints rien à imprimer : le document n’a aucune illustration imprimable @msg nothing to repeat rien à répéter -@msg numbers out of order in {_1} quantifier nombres dans le désordre dans le quantificateur {_1} +@msg numbers out of order in {{}} quantifier nombres dans le désordre dans le quantificateur {{}} @msg object is not a path l’objet n’est pas un tracé @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object la transparence d’un objet ne peut pas être prélevée sur des caractères en surbrillance ; désactivez Transparence dans les options de la pipette ou sélectionnez l’objet entier @msg object {_1} can't be set as point type l’objet {_1} ne peut pas être converti en texte de point @@ -9140,7 +9140,7 @@ breakText Glyphs Glyphes @msg the page has no area la page n’a pas de surface @msg the page's type in an unread object's box isn't in its page art le texte de la page dans le cadre d’un objet non lu n’est pas dans l’illustration de sa page @msg the paint behind the proxy is not a gradient la peinture derrière l’échantillon n’est pas un dégradé -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) la peinture n’est pas un dégradé de forme libre (appliquez-en un avec paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la peinture n’est pas un dégradé de forme libre (appliquez-en un avec paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function les paramètres ou le corps ne forment pas une seule fonction @msg the parent must be a layer or sublayer le parent doit être un calque ou un sous-calque @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it le filtre SVG collé {name} dessine autrement que le filtre du document qui porte ce nom, et aucun nom libre ne lui convient diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 15582a2dbd..52e5efcc16 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5135,7 +5135,7 @@ antiAlias Sharp शार्प Composite Fonts कंपोज़िट फ़ॉन्ट Export Composite Fonts कंपोज़िट फ़ॉन्ट एक्सपोर्ट करें Import Composite Fonts कंपोज़िट फ़ॉन्ट इम्पोर्ट करें -@msg each font must be {name, parts} हर फ़ॉन्ट {name, parts} होना चाहिए +@msg each font must be {{name, parts}} हर फ़ॉन्ट {{name, parts}} होना चाहिए @msg unknown key `{k}`; a font takes name and parts अज्ञात कुंजी `{k}`; फ़ॉन्ट name और parts लेता है @msg each font needs a name हर फ़ॉन्ट का एक नाम होना चाहिए @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` कंपोज़िट फ़ॉन्ट का नाम नहीं हो सकता (1 से {COMPOSITE_NAME_MAX} अक्षर, कोई नियंत्रण अक्षर नहीं) @@ -5148,7 +5148,10 @@ antiAlias Sharp शार्प @msg two composite fonts are named `{_1}` दो कंपोज़िट फ़ॉन्ट का नाम `{_1}` है @msg `{_1}` is the name of an installed font `{_1}` एक इंस्टॉल किए गए फ़ॉन्ट का नाम है @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} `{font}` में सेट है, जो एक कंपोज़िट फ़ॉन्ट है -@msg give fonts: [{name, parts}…] fonts दें: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts दें: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` को "document", {{artboards: [index, …]}} या {{layers: [id, …]}} होना चाहिए +@msg numbers out of order in {{}} quantifier {{}} क्वांटिफ़ायर में संख्याएँ क्रम में नहीं हैं +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) पेंट फ्रीफॉर्म ग्रेडिएंट नहीं है (paint.editGradient {{kind: "freeform"}} से एक लागू करें) @msg path is empty path खाली है @msg fonts must be a list of composite fonts fonts कंपोज़िट फ़ॉन्ट की सूची होनी चाहिए @msg names must be strings names स्ट्रिंग होने चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8ddb1d34ca..82e664da40 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4432,7 +4432,7 @@ mark-style Japanese Japán Composite Fonts Összetett betűtípusok Export Composite Fonts Összetett betűtípusok exportálása Import Composite Fonts Összetett betűtípusok importálása -@msg each font must be {name, parts} minden betűtípusnak {name, parts} alakúnak kell lennie +@msg each font must be {{name, parts}} minden betűtípusnak {{name, parts}} alakúnak kell lennie @msg unknown key `{k}`; a font takes name and parts ismeretlen kulcs: `{k}`; egy betűtípus name és parts kulcsot fogad @msg each font needs a name minden betűtípusnak kell egy név @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nem lehet összetett betűtípus neve (1–{COMPOSITE_NAME_MAX} karakter, vezérlőkarakterek nélkül) @@ -4445,7 +4445,7 @@ mark-style Japanese Japán @msg two composite fonts are named `{_1}` két összetett betűtípus neve is `{_1}` @msg `{_1}` is the name of an installed font `{_1}` egy telepített betűtípus neve @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: a(z) {_2} a(z) `{font}` összetett betűtípust használja -@msg give fonts: [{name, parts}…] adja meg: fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] adja meg: fonts: [{{name, parts}}…] @msg path is empty a path üres @msg fonts must be a list of composite fonts a fonts értékének összetett betűtípusok listájának kell lennie @msg names must be strings a names elemeinek karakterláncoknak kell lenniük @@ -7899,7 +7899,7 @@ breakText Glyphs Glifák @msg `scale` must be a number from 0.001 to 1000 `scale`: 0.001 és 1000 közötti szám kell @msg `scale` must be a number in (0, 100] `scale`: a (0, 100] tartományba eső szám kell @msg `scope.{key}` must be a non-empty array `scope.{key}`: nem üres tömb kell -@msg `scope` must be "document", {artboards} or {layers} `scope`: "document", {artboards} vagy {layers} kell +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`: "document", {{artboards: [index, …]}} vagy {{layers: [id, …]}} kell @msg `scope` must be "selection" or "document", not {other} `scope`: "selection" vagy "document" kell, ez nem az: {other} @msg `script` must be a string `script`: karakterlánc kell @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`: adatsorindexek nem üres listája @@ -8793,7 +8793,7 @@ breakText Glyphs Glifák @msg nothing to print: every artboard picked is blank nincs mit nyomtatni: minden kiválasztott rajztábla üres @msg nothing to print: the document has no art that prints nincs mit nyomtatni: a dokumentumban nincs nyomtatásra kerülő grafika @msg nothing to repeat nincs mit ismételni -@msg numbers out of order in {_1} quantifier a számok rossz sorrendben vannak ebben a kvantorban: {_1} +@msg numbers out of order in {{}} quantifier a számok rossz sorrendben vannak ebben a kvantorban: {{}} @msg object is not a path az objektum nem útvonal @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object az objektum átlátszósága nem vehető át kiemelt karakterekre; kapcsold ki az Átlátszóság beállítást a Pipetta beállításaiban, vagy jelöld ki a teljes objektumot @msg object {_1} can't be set as point type ez az objektum nem állítható be pontszövegként: {_1} @@ -9151,7 +9151,7 @@ breakText Glyphs Glifák @msg the page has no area az oldalnak nincs területe @msg the page's type in an unread object's box isn't in its page art az oldal egy be nem olvasott objektum keretében lévő szövege nincs benne az oldal grafikájában @msg the paint behind the proxy is not a gradient a mintadoboz mögötti festés nem színátmenet -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) a festés nem szabad formájú színátmenet (alkalmazz egyet a paint.editGradient {kind} paranccsal) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) a festés nem szabad formájú színátmenet (alkalmazz egyet a paint.editGradient {{kind: "freeform"}} paranccsal) @msg the parameters or body do not form one function a paraméterek vagy a törzs nem alkotnak egyetlen függvényt @msg the parent must be a layer or sublayer a szülő réteg vagy alréteg kell legyen @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it a beillesztett SVG-szűrő ({name}) másképp rajzol, mint a dokumentum azonos nevű szűrője, és nem jut neki szabad név diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1c0590ff98..ff07943270 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3802,7 +3802,7 @@ digits Malayalam Malayalam Composite Fonts Font compositi Export Composite Fonts Esporta font compositi Import Composite Fonts Importa font compositi -@msg each font must be {name, parts} ogni font deve essere {name, parts} +@msg each font must be {{name, parts}} ogni font deve essere {{name, parts}} @msg unknown key `{k}`; a font takes name and parts chiave sconosciuta `{k}`; un font accetta name e parts @msg each font needs a name ogni font deve avere un nome @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` non può essere il nome di un font composito (da 1 a {COMPOSITE_NAME_MAX} caratteri, senza caratteri di controllo) @@ -3815,7 +3815,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` due font compositi si chiamano `{_1}` @msg `{_1}` is the name of an installed font `{_1}` è il nome di un font installato @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, un font composito -@msg give fonts: [{name, parts}…] indica fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] indica fonts: [{{name, parts}}…] @msg path is empty path è vuoto @msg fonts must be a list of composite fonts fonts deve essere un elenco di font compositi @msg names must be strings names deve contenere stringhe @@ -7365,7 +7365,7 @@ breakText Glyphs Glifi @msg `rows` must be lists of numbers or nulls, not {r} `rows` deve essere un elenco di liste di numeri o null, non {r} @msg `scale` must be a number from 0.001 to 1000 `scale` deve essere un numero compreso tra 0.001 e 1000 @msg `scope.{key}` must be a non-empty array `scope.{key}` deve essere un array non vuoto -@msg `scope` must be "document", {artboards} or {layers} `scope` deve essere "document", {artboards} o {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` deve essere "document", {{artboards: [index, …]}} o {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` deve essere "left", "right", "top" o "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` posiziona la tavola da disegno: ometti x, y, width e height @msg `source` is the only path in series group `target` `source` è l'unico tracciato nel gruppo in serie `target` @@ -7550,7 +7550,7 @@ breakText Glyphs Glifi @msg not a regular expression non è un'espressione regolare @msg not an action set: the text doesn't start with /version and a number non è un set di azioni: il testo non inizia con /version e un numero @msg nothing to repeat niente da ripetere -@msg numbers out of order in {_1} quantifier numeri non in ordine nel quantificatore {_1} +@msg numbers out of order in {{}} quantifier numeri non in ordine nel quantificatore {{}} @msg object {_1} needs a 3D effect l'oggetto {_1} richiede un effetto 3D @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic oggetto {_1}: un'estrusione e smussatura cava non ha tappi: attiva Tappo per applicare una grafica @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front oggetto {_1}: con una profondità di 0 l'oggetto ha una sola faccia: applica le sue grafiche sulla faccia anteriore @@ -7619,7 +7619,7 @@ breakText Glyphs Glifi @msg the library's file is outside the read roots il file della libreria è fuori dalle cartelle di lettura consentite @msg the line is too long, or the paths it passes too many, to check la linea è troppo lunga, o i tracciati che attraversa sono troppi, per poterla verificare @msg the method needs an XML value il metodo richiede un valore XML -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) la pittura non è una sfumatura a forma libera (applicane una con paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) la pittura non è una sfumatura a forma libera (applicane una con paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function i parametri o il corpo non formano un'unica funzione @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it il filtro SVG incollato {name} disegna in modo diverso dal filtro del documento con quel nome, e non c'è un nome libero adatto @msg the paths are too many or too tangled to find where they cross i tracciati sono troppi o troppo intrecciati per trovare dove si incrociano diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index dedcdb328e..1936aa7254 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4130,7 +4130,7 @@ file-filter Templates テンプレート Composite Fonts 合成フォント Export Composite Fonts 合成フォントを書き出し Import Composite Fonts 合成フォントを読み込み -@msg each font must be {name, parts} 各フォントは {name, parts} の形にしてください +@msg each font must be {{name, parts}} 各フォントは {{name, parts}} の形にしてください @msg unknown key `{k}`; a font takes name and parts `{k}` は不明なキーです。フォントに使えるのは name と parts です @msg each font needs a name 各フォントには名前が必要です @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` は合成フォントの名前にできません (1~{COMPOSITE_NAME_MAX} 文字、制御文字なし) @@ -4143,7 +4143,7 @@ file-filter Templates テンプレート @msg two composite fonts are named `{_1}` `{_1}` という名前の合成フォントが 2 つあります @msg `{_1}` is the name of an installed font `{_1}` はインストール済みのフォントの名前です @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} に合成フォントの `{font}` が設定されています -@msg give fonts: [{name, parts}…] fonts を指定してください: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts を指定してください: [{{name, parts}}…] @msg path is empty path が空です @msg fonts must be a list of composite fonts fonts は合成フォントのリストにしてください @msg names must be strings names は文字列にしてください @@ -6565,7 +6565,7 @@ axis Y Axis Y 軸 @msg `rows` must be lists of numbers or nulls, not {r} `rows` には数値または null のリストを指定してください ({r} は指定できません) @msg `scale` must be a number from 0.001 to 1000 `scale` には 0.001 から 1000 までの数値を指定してください @msg `scope.{key}` must be a non-empty array `scope.{key}` には空でない配列を指定してください -@msg `scope` must be "document", {artboards} or {layers} `scope` には "document"、{artboards}、{layers} のいずれかを指定してください +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` には "document"、{{artboards: [index, …]}}、{{layers: [id, …]}} のいずれかを指定してください @msg `side` must be "left", "right", "top" or "bottom" `side` には "left"、"right"、"top"、"bottom" のいずれかを指定してください @msg `side` places the artboard: leave out x, y, width and height `side` でアートボードを配置します: x、y、width、height は省略してください @msg `source` is the only path in series group `target` `source` は系列グループ `target` の唯一のパスです @@ -6750,7 +6750,7 @@ axis Y Axis Y 軸 @msg not a regular expression 正規表現ではありません @msg not an action set: the text doesn't start with /version and a number アクションセットではありません: テキストが /version と数値で始まっていません @msg nothing to repeat 繰り返す対象がありません -@msg numbers out of order in {_1} quantifier {_1} 量指定子の数値の順序が正しくありません +@msg numbers out of order in {{}} quantifier {{}} 量指定子の数値の順序が正しくありません @msg object {_1} needs a 3D effect オブジェクト {_1} には 3D 効果が必要です @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic オブジェクト {_1}: 中空の「押し出しとベベル」にはキャップがありません: グラフィックをマッピングするには「キャップ」をオンにしてください @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front オブジェクト {_1}: 奥行きが 0 のオブジェクトは面が 1 つです: グラフィックは前面にマッピングしてください @@ -6819,7 +6819,7 @@ axis Y Axis Y 軸 @msg the library's file is outside the read roots ライブラリのファイルが読み取りルートの外にあります @msg the line is too long, or the paths it passes too many, to check 線が長すぎるか、通過するパスが多すぎるため、確認できません @msg the method needs an XML value このメソッドには XML の値が必要です -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) ペイントがフリーフォームグラデーションではありません (paint.editGradient {kind} で適用してください) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) ペイントがフリーフォームグラデーションではありません (paint.editGradient {{kind: "freeform"}} で適用してください) @msg the parameters or body do not form one function パラメーターまたは本体が 1 つの関数になっていません @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it ペーストした SVG フィルター {name} は、ドキュメントにある同名のフィルターと描画結果が異なり、使用できる空き名もありません @msg the paths are too many or too tangled to find where they cross パスが多すぎるか複雑に絡み合っているため、交差する位置を見つけられません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d9d75dd737..da8aec82bb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3605,7 +3605,6 @@ digits Malayalam მალაიალამური Composite Fonts კომპოზიტური შრიფტები Export Composite Fonts კომპოზიტური შრიფტების ექსპორტი Import Composite Fonts კომპოზიტური შრიფტების იმპორტი -@msg each font must be {name, parts} თითოეული შრიფტი უნდა იყოს {name, parts} @msg unknown key `{k}`; a font takes name and parts უცნობი გასაღები `{k}`; შრიფტი იღებს name-სა და parts-ს @msg each font needs a name თითოეულ შრიფტს სახელი სჭირდება @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ვერ იქნება კომპოზიტური შრიფტის სახელი (1-დან {COMPOSITE_NAME_MAX} სიმბოლომდე, მმართველი სიმბოლოების გარეშე) @@ -3618,7 +3617,6 @@ digits Malayalam მალაიალამური @msg two composite fonts are named `{_1}` ორ კომპოზიტურ შრიფტს ჰქვია `{_1}` @msg `{_1}` is the name of an installed font `{_1}` დაინსტალირებული შრიფტის სახელია @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} იყენებს `{font}`-ს, რომელიც კომპოზიტური შრიფტია -@msg give fonts: [{name, parts}…] მიუთითეთ fonts: [{name, parts}…] @msg path is empty path ცარიელია @msg fonts must be a list of composite fonts fonts უნდა იყოს კომპოზიტური შრიფტების სია @msg names must be strings names უნდა იყოს სტრიქონები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 90f4e1f3fd..136c58cff8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4118,7 +4118,7 @@ file-filter Templates 템플릿 Composite Fonts 합성 글꼴 Export Composite Fonts 합성 글꼴 내보내기 Import Composite Fonts 합성 글꼴 가져오기 -@msg each font must be {name, parts} 각 글꼴은 {name, parts} 형식이어야 합니다 +@msg each font must be {{name, parts}} 각 글꼴은 {{name, parts}} 형식이어야 합니다 @msg unknown key `{k}`; a font takes name and parts 알 수 없는 키 `{k}`: 글꼴에는 name과 parts만 쓸 수 있습니다 @msg each font needs a name 각 글꼴에는 이름이 필요합니다 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}`은(는) 합성 글꼴 이름으로 쓸 수 없습니다(1~{COMPOSITE_NAME_MAX}자, 제어 문자 없음) @@ -4131,7 +4131,7 @@ file-filter Templates 템플릿 @msg two composite fonts are named `{_1}` 이름이 `{_1}`인 합성 글꼴이 두 개 있습니다 @msg `{_1}` is the name of an installed font `{_1}`은(는) 설치된 글꼴의 이름입니다 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2}이(가) 합성 글꼴인 `{font}`(으)로 설정되어 있습니다 -@msg give fonts: [{name, parts}…] fonts를 지정하세요: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts를 지정하세요: [{{name, parts}}…] @msg path is empty path가 비어 있습니다 @msg fonts must be a list of composite fonts fonts는 합성 글꼴 목록이어야 합니다 @msg names must be strings names는 문자열이어야 합니다 @@ -7623,7 +7623,7 @@ breakText Glyphs 글리프 @msg `scale` must be a number from 0.001 to 1000 `scale`은(는) 0.001에서 1000 사이의 숫자여야 합니다 @msg `scale` must be a number in (0, 100] `scale`은(는) (0, 100] 범위의 숫자여야 합니다 @msg `scope.{key}` must be a non-empty array `scope.{key}`은(는) 비어 있지 않은 배열이어야 합니다 -@msg `scope` must be "document", {artboards} or {layers} `scope`은(는) "document", {artboards} 또는 {layers}여야 합니다 +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope`은(는) "document", {{artboards: [index, …]}} 또는 {{layers: [id, …]}}여야 합니다 @msg `scope` must be "selection" or "document", not {other} `scope`은(는) "selection" 또는 "document"여야 합니다: {other} @msg `script` must be a string `script`은(는) 문자열이어야 합니다 @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes`은(는) 계열 인덱스가 하나 이상 있는 목록입니다 @@ -8518,7 +8518,7 @@ breakText Glyphs 글리프 @msg nothing to print: every artboard picked is blank 인쇄할 것이 없습니다: 선택한 아트보드가 모두 비어 있습니다 @msg nothing to print: the document has no art that prints 인쇄할 것이 없습니다: 문서에 인쇄되는 아트웍이 없습니다 @msg nothing to repeat 반복할 항목이 없습니다 -@msg numbers out of order in {_1} quantifier {_1} 수량자의 숫자 순서가 잘못되었습니다 +@msg numbers out of order in {{}} quantifier {{}} 수량자의 숫자 순서가 잘못되었습니다 @msg object is not a path 개체가 패스가 아닙니다 @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object 개체 투명도는 강조 표시한 글자에 샘플링할 수 없습니다. 스포이드 옵션에서 투명도를 끄거나 개체 전체를 선택하세요 @msg object {_1} can't be set as point type 개체 {_1}은(는) 포인트 문자로 설정할 수 없습니다 @@ -8880,7 +8880,7 @@ breakText Glyphs 글리프 @msg the page has no area 페이지에 면적이 없습니다 @msg the page's type in an unread object's box isn't in its page art 읽지 않은 개체의 상자에 있는 페이지 문자가 페이지 아트웍에 없습니다 @msg the paint behind the proxy is not a gradient 프록시 뒤의 페인트가 그레이디언트가 아닙니다 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 페인트가 자유 형태 그레이디언트가 아닙니다(paint.editGradient {kind}(으)로 적용하세요) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 페인트가 자유 형태 그레이디언트가 아닙니다(paint.editGradient {{kind: "freeform"}}(으)로 적용하세요) @msg the parameters or body do not form one function 매개변수나 본문이 하나의 함수를 이루지 않습니다 @msg the parent must be a layer or sublayer 상위 항목은 레이어나 하위 레이어여야 합니다 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 붙여넣은 SVG 필터 {name}은(는) 문서에 있는 같은 이름의 필터와 다르게 그려지며, 쓸 수 있는 빈 이름이 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 990e369f0f..b18fcf8688 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2102,7 +2102,7 @@ digits Malayalam Malayalam Composite Fonts Samengestelde lettertypen Export Composite Fonts Samengestelde lettertypen exporteren Import Composite Fonts Samengestelde lettertypen importeren -@msg each font must be {name, parts} elk lettertype moet {name, parts} zijn +@msg each font must be {{name, parts}} elk lettertype moet {{name, parts}} zijn @msg unknown key `{k}`; a font takes name and parts onbekende sleutel `{k}`; een lettertype neemt name en parts @msg each font needs a name elk lettertype heeft een naam nodig @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan geen naam van een samengesteld lettertype zijn (1 tot {COMPOSITE_NAME_MAX} tekens, geen besturingstekens) @@ -2115,7 +2115,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` twee samengestelde lettertypen heten `{_1}` @msg `{_1}` is the name of an installed font `{_1}` is de naam van een geïnstalleerd lettertype @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} gebruikt `{font}`, een samengesteld lettertype -@msg give fonts: [{name, parts}…] geef fonts op: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] geef fonts op: [{{name, parts}}…] @msg path is empty path is leeg @msg fonts must be a list of composite fonts fonts moet een lijst van samengestelde lettertypen zijn @msg names must be strings names moeten tekenreeksen zijn @@ -5942,7 +5942,7 @@ imageTrace Outline Contour @msg `scale` must be a number from 0.001 to 1000 `scale` moet een getal van 0,001 tot 1000 zijn @msg `scale` must be a number in (0, 100] `scale` moet een getal in (0, 100] zijn @msg `scope.{key}` must be a non-empty array `scope.{key}` moet een niet-lege array zijn -@msg `scope` must be "document", {artboards} or {layers} `scope` moet "document", {artboards} of {layers} zijn +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` moet "document", {{artboards: [index, …]}} of {{layers: [id, …]}} zijn @msg `scope` must be "selection" or "document", not {other} `scope` moet "selection" of "document" zijn, niet {other} @msg `script` must be a string `script` moet een string zijn @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` is een niet-lege lijst met reeksindexen @@ -6839,7 +6839,7 @@ imageTrace Outline Contour @msg nothing to print: every artboard picked is blank niets om af te drukken: elk gekozen tekengebied is leeg @msg nothing to print: the document has no art that prints niets om af te drukken: het document heeft geen illustraties die worden afgedrukt @msg nothing to repeat niets om te herhalen -@msg numbers out of order in {_1} quantifier getallen in de verkeerde volgorde in kwantor {_1} +@msg numbers out of order in {{}} quantifier getallen in de verkeerde volgorde in kwantor {{}} @msg object is not a path het object is geen pad @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object objecttransparantie kan niet op gemarkeerde tekens worden overgenomen; schakel Transparantie uit in Opties voor pipet of selecteer het hele object @msg object {_1} can't be set as point type object {_1} kan niet als punttekst worden gezet @@ -7202,7 +7202,7 @@ imageTrace Outline Contour @msg the page has no area de pagina heeft geen oppervlak @msg the page's type in an unread object's box isn't in its page art de tekst van de pagina in het kader van een ongelezen object zit niet in de pagina-illustratie ervan @msg the paint behind the proxy is not a gradient de verf achter de proxy is geen verloop -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) de verf is geen verloop in vrije vorm (pas er een toe met paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) de verf is geen verloop in vrije vorm (pas er een toe met paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function de parameters of de body vormen niet één functie @msg the parent must be a layer or sublayer het bovenliggende item moet een laag of sublaag zijn @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it het geplakte SVG-filter {name} tekent anders dan het filter met die naam in het document, en er is geen vrije naam die past diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 647a0c62bd..7292fb98db 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1596,7 +1596,7 @@ digits Malayalam Malajalam Composite Fonts Fonty złożone Export Composite Fonts Eksportuj fonty złożone Import Composite Fonts Importuj fonty złożone -@msg each font must be {name, parts} każdy font musi mieć postać {name, parts} +@msg each font must be {{name, parts}} każdy font musi mieć postać {{name, parts}} @msg unknown key `{k}`; a font takes name and parts nieznany klucz `{k}`; font przyjmuje name i parts @msg each font needs a name każdy font musi mieć nazwę @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` nie może być nazwą fontu złożonego (od 1 do {COMPOSITE_NAME_MAX} znaków, bez znaków sterujących) @@ -1609,7 +1609,7 @@ digits Malayalam Malajalam @msg two composite fonts are named `{_1}` dwa fonty złożone mają nazwę `{_1}` @msg `{_1}` is the name of an installed font `{_1}` to nazwa zainstalowanego fontu @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} używa `{font}`, który jest fontem złożonym -@msg give fonts: [{name, parts}…] podaj fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] podaj fonts: [{{name, parts}}…] @msg path is empty path jest puste @msg fonts must be a list of composite fonts fonts musi być listą fontów złożonych @msg names must be strings names muszą być ciągami znaków @@ -7600,7 +7600,7 @@ breakText Glyphs Glify @msg `rows` must be lists of numbers or nulls, not {r} `rows` musi zawierać listy liczb lub wartości null, a nie {r} @msg `scale` must be a number from 0.001 to 1000 `scale` musi być liczbą od 0,001 do 1000 @msg `scope.{key}` must be a non-empty array `scope.{key}` musi być niepustą tablicą -@msg `scope` must be "document", {artboards} or {layers} `scope` musi mieć wartość "document", {artboards} lub {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` musi mieć wartość "document", {{artboards: [index, …]}} lub {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` musi mieć wartość "left", "right", "top" lub "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` wyznacza położenie obszaru kompozycji: pomiń x, y, width i height @msg `source` is the only path in series group `target` `source` jest jedyną ścieżką w grupie serii `target` @@ -7786,7 +7786,7 @@ breakText Glyphs Glify @msg not a regular expression to nie jest wyrażenie regularne @msg not an action set: the text doesn't start with /version and a number to nie jest zestaw operacji: tekst nie zaczyna się od /version i liczby @msg nothing to repeat brak elementu do powtórzenia -@msg numbers out of order in {_1} quantifier liczby w niewłaściwej kolejności w kwantyfikatorze {_1} +@msg numbers out of order in {{}} quantifier liczby w niewłaściwej kolejności w kwantyfikatorze {{}} @msg object {_1} needs a 3D effect obiekt {_1} wymaga efektu 3D @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic obiekt {_1}: puste w środku Wyciągnięcie i fazowanie nie ma zakończeń: włącz opcję Zakończenie, aby odwzorować grafikę @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front obiekt {_1}: przy głębokości 0 obiekt ma jedną ścianę: odwzoruj jego grafiki na przodzie @@ -7859,7 +7859,7 @@ breakText Glyphs Glify @msg the library's file is outside the read roots plik biblioteki znajduje się poza katalogami głównymi odczytu @msg the line is too long, or the paths it passes too many, to check linia jest zbyt długa albo mija zbyt wiele ścieżek, aby ją sprawdzić @msg the method needs an XML value metoda wymaga wartości XML -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) malowanie obiektu nie jest gradientem dowolnym (zastosuj go poleceniem paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) malowanie obiektu nie jest gradientem dowolnym (zastosuj go poleceniem paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function parametry lub treść nie tworzą jednej funkcji @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it wklejony filtr SVG {name} rysuje inaczej niż filtr dokumentu o tej nazwie, a nie znaleziono dla niego wolnej nazwy @msg the paths are too many or too tangled to find where they cross ścieżek jest zbyt wiele lub są zbyt splątane, aby znaleźć miejsca ich przecięć diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2c0817772d..83d225de9f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5333,7 +5333,7 @@ axis Both Ambos Composite Fonts Fontes compostas Export Composite Fonts Exportar fontes compostas Import Composite Fonts Importar fontes compostas -@msg each font must be {name, parts} cada fonte deve ser {name, parts} +@msg each font must be {{name, parts}} cada fonte deve ser {{name, parts}} @msg unknown key `{k}`; a font takes name and parts chave desconhecida `{k}`; uma fonte aceita name e parts @msg each font needs a name cada fonte precisa de um nome @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` não pode nomear uma fonte composta (de 1 a {COMPOSITE_NAME_MAX} caracteres, sem caracteres de controle) @@ -5346,7 +5346,7 @@ axis Both Ambos @msg two composite fonts are named `{_1}` duas fontes compostas se chamam `{_1}` @msg `{_1}` is the name of an installed font `{_1}` é o nome de uma fonte instalada @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} usa `{font}`, uma fonte composta -@msg give fonts: [{name, parts}…] informe fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] informe fonts: [{{name, parts}}…] @msg path is empty path está vazio @msg fonts must be a list of composite fonts fonts deve ser uma lista de fontes compostas @msg names must be strings names deve conter strings @@ -8090,7 +8090,7 @@ swatch Yellow Green Verde-amarelado @msg `scale` must be a number from 0.001 to 1000 `scale` deve ser um número de 0.001 a 1000 @msg `scale` must be a number in (0, 100] `scale` deve ser um número em (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` deve ser uma matriz não vazia -@msg `scope` must be "document", {artboards} or {layers} `scope` deve ser "document", {artboards} ou {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` deve ser "document", {{artboards: [index, …]}} ou {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` deve ser "selection" ou "document", não {other} @msg `script` must be a string `script` deve ser uma string @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` é uma lista não vazia de índices de séries @@ -8983,7 +8983,7 @@ swatch Yellow Green Verde-amarelado @msg nothing to print: every artboard picked is blank nada para imprimir: todas as pranchetas escolhidas estão em branco @msg nothing to print: the document has no art that prints nada para imprimir: o documento não tem arte imprimível @msg nothing to repeat nada para repetir -@msg numbers out of order in {_1} quantifier números fora de ordem no quantificador {_1} +@msg numbers out of order in {{}} quantifier números fora de ordem no quantificador {{}} @msg object is not a path o objeto não é um caminho @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object a transparência do objeto não pode ser aplicada aos caracteres destacados; desative Transparência nas Opções do Conta-gotas ou selecione o objeto inteiro @msg object {_1} can't be set as point type o objeto {_1} não pode ser definido como texto de ponto @@ -9341,7 +9341,7 @@ swatch Yellow Green Verde-amarelado @msg the page has no area a página não tem área @msg the page's type in an unread object's box isn't in its page art o texto da página na caixa de um objeto não lido não está na arte da página @msg the paint behind the proxy is not a gradient a pintura por trás do proxy não é um gradiente -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) a pintura não é um gradiente de forma livre (aplique um com paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) a pintura não é um gradiente de forma livre (aplique um com paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function os parâmetros ou o corpo não formam uma única função @msg the parent must be a layer or sublayer o pai deve ser uma camada ou subcamada @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it o filtro SVG colado {name} desenha de modo diferente do filtro do documento com esse nome, e nenhum nome livre serve para ele diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 28db02bb34..3328e5400c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3788,7 +3788,7 @@ digits Malayalam Малаялам Composite Fonts Составные шрифты Export Composite Fonts Экспорт составных шрифтов Import Composite Fonts Импорт составных шрифтов -@msg each font must be {name, parts} каждый шрифт должен иметь вид {name, parts} +@msg each font must be {{name, parts}} каждый шрифт должен иметь вид {{name, parts}} @msg unknown key `{k}`; a font takes name and parts неизвестный ключ `{k}`; шрифт принимает name и parts @msg each font needs a name у каждого шрифта должно быть имя @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не может быть именем составного шрифта (от 1 до {COMPOSITE_NAME_MAX} символов, без управляющих символов) @@ -3801,7 +3801,7 @@ digits Malayalam Малаялам @msg two composite fonts are named `{_1}` два составных шрифта называются `{_1}` @msg `{_1}` is the name of an installed font `{_1}` является именем установленного шрифта @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} использует `{font}`, а это составной шрифт -@msg give fonts: [{name, parts}…] укажите fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] укажите fonts: [{{name, parts}}…] @msg path is empty path пуст @msg fonts must be a list of composite fonts fonts должен быть списком составных шрифтов @msg names must be strings names должны быть строками @@ -8013,7 +8013,7 @@ shape Open Открытый @msg `scale` must be a number from 0.001 to 1000 `scale` должно быть числом от 0.001 до 1000 @msg `scale` must be a number in (0, 100] `scale` должно быть числом в диапазоне (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` должно быть непустым массивом -@msg `scope` must be "document", {artboards} or {layers} `scope` должно быть "document", {artboards} или {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` должно быть "document", {{artboards: [index, …]}} или {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` должно быть "selection" или "document", а не {other} @msg `script` must be a string `script` должно быть строкой @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` — непустой список индексов рядов @@ -8904,7 +8904,7 @@ shape Open Открытый @msg nothing to print: every artboard picked is blank нечего печатать: все выбранные монтажные области пусты @msg nothing to print: the document has no art that prints нечего печатать: в документе нет печатаемой графики @msg nothing to repeat нечего повторять -@msg numbers out of order in {_1} quantifier числа в квантификаторе {_1} идут в неверном порядке +@msg numbers out of order in {{}} quantifier числа в квантификаторе {{}} идут в неверном порядке @msg object is not a path объект не является контуром @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object прозрачность объекта нельзя перенести на выделенные символы; отключите «Прозрачность» в окне «Параметры пипетки» или выделите объект целиком @msg object {_1} can't be set as point type объект {_1} нельзя преобразовать в текст из точки @@ -9263,7 +9263,7 @@ shape Open Открытый @msg the page has no area у страницы нет площади @msg the page's type in an unread object's box isn't in its page art текста страницы в рамке непрочитанного объекта нет в графике этой страницы @msg the paint behind the proxy is not a gradient краска за индикатором не является градиентом -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) краска не является произвольным градиентом (примените его через paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) краска не является произвольным градиентом (примените его через paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function параметры или тело не образуют одну функцию @msg the parent must be a layer or sublayer родитель должен быть слоем или подслоем @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it вставленный фильтр SVG {name} рисует иначе, чем фильтр документа с тем же именем, и свободного имени для него не нашлось diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2f19e59397..0d4df77335 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3678,7 +3678,7 @@ digits Malayalam Malayalam Composite Fonts Sammansatta typsnitt Export Composite Fonts Exportera sammansatta typsnitt Import Composite Fonts Importera sammansatta typsnitt -@msg each font must be {name, parts} varje typsnitt måste vara {name, parts} +@msg each font must be {{name, parts}} varje typsnitt måste vara {{name, parts}} @msg unknown key `{k}`; a font takes name and parts okänd nyckel `{k}`; ett typsnitt tar name och parts @msg each font needs a name varje typsnitt behöver ett namn @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan inte vara namnet på ett sammansatt typsnitt (1 till {COMPOSITE_NAME_MAX} tecken, inga styrtecken) @@ -3691,7 +3691,10 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` två sammansatta typsnitt heter `{_1}` @msg `{_1}` is the name of an installed font `{_1}` är namnet på ett installerat typsnitt @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} använder `{font}`, ett sammansatt typsnitt -@msg give fonts: [{name, parts}…] ange fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] ange fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` måste vara "document", {{artboards: [index, …]}} eller {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier talen står i fel ordning i kvantifieraren {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) färgen är inte en fri gradient (använd en med paint.editGradient {{kind: "freeform"}}) @msg path is empty path är tom @msg fonts must be a list of composite fonts fonts måste vara en lista med sammansatta typsnitt @msg names must be strings names måste vara strängar diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0659a076a5..312377e675 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2237,7 +2237,7 @@ fn file_info_control_character_refusals_translate_in_every_complete_catalog() { #[test] fn composite_font_errors_translate_in_complete_languages() { const SOURCES: &[&str] = &[ - "each font must be {name, parts}", + "each font must be {{name, parts}}", "unknown key `{k}`; a font takes name and parts", "each font needs a name", "`{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters)", @@ -2250,7 +2250,7 @@ fn composite_font_errors_translate_in_complete_languages() { "two composite fonts are named `{_1}`", "`{_1}` is the name of an installed font", "`{_1}`: {_2} is set in `{font}`, a composite font", - "give fonts: [{name, parts}…]", + "give fonts: [{{name, parts}}…]", "path is empty", "fonts must be a list of composite fonts", "names must be strings", @@ -2500,6 +2500,53 @@ fn literal_brace_rows_match_only_their_message() { assert_eq!(message(de(), "plug-in output: expected value at line 1 column 1"), "Plug-in-Ausgabe: expected value at line 1 column 1"); } +/// Every complete-message catalog translates the messages that print braces as text through an +/// exact row with doubled braces, keeps each literal example whole, and has no row with a +/// placeholder in their place: such a row also translates other text with the same start and end. +#[test] +fn literal_brace_messages_have_exact_rows_in_complete_languages() { + // A row's source, the message as shown, and the text its translation keeps. + let cases: &[(&str, &str, &[&str])] = &[ + ("each font must be {{name, parts}}", "each font must be {name, parts}", &["{name, parts}"]), + ("give fonts: [{{name, parts}}…]", "give fonts: [{name, parts}…]", &["fonts", "[{name, parts}…]"]), + ( + r#"`scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}}"#, + r#"`scope` must be "document", {artboards: [index, …]} or {layers: [id, …]}"#, + &["`scope`", r#""document""#, "{artboards: [index, …]}", "{layers: [id, …]}"], + ), + ("numbers out of order in {{}} quantifier", "numbers out of order in {} quantifier", &["{}"]), + ( + r#"the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}})"#, + r#"the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})"#, + &["paint.editGradient", r#"{kind: "freeform"}"#], + ), + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + let rows: Vec<(&str, &str)> = entries.iter().filter(|(ctx, _, _)| ctx == "@msg").map(|(_, src, tr)| (src.as_str(), tr.as_str())).collect(); + for (source, shown, kept) in cases { + let Some((_, tr)) = rows.iter().find(|(src, _)| src == source) else { panic!("{code} has no row for {source:?}") }; + let out = message(lang, shown); + assert_eq!(out, fill_once(tr, &[]), "{code}: {shown}"); + assert_ne!(out, *shown, "{code} leaves {shown:?} in English"); + for k in *kept { + assert!(out.contains(k), "{code}: {k} in {out}"); + } + // The text before the first brace and after the last one, which an older row with a + // placeholder in place of the braced example also starts and ends with. + let head = source.find('{').map_or("", |at| &source[..at]); + let tail = source.rfind('}').map_or("", |at| &source[at + 1..]); + let broad: Vec<&str> = rows + .iter() + .map(|(src, _)| *src) + .filter(|src| src != source && src.contains('{') && src.starts_with(head) && src.ends_with(tail)) + .collect(); + assert!(broad.is_empty(), "{code} keeps placeholder rows in place of {source:?}: {broad:?}"); + } + } +} + /// `plugin.run` of an importer, an exporter or a live effect names the command that runs it with /// the JSON that picks it, and every complete-message catalog translates that error with the /// plug-in's id and the JSON kept. @@ -4641,9 +4688,9 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[ ("dataBase64 is not base64", &["dataBase64"]), ("decimals must be {_1}–{_2} (got {_3})", &["decimals"]), ("detect must be true or false", &["detect"]), - ("each font must be {name, parts}", &["name", "parts"]), + ("each font must be {{name, parts}}", &["name", "parts"]), ("fonts must be a list of composite fonts", &["fonts"]), - ("give fonts: [{name, parts}…]", &["fonts", "name", "parts"]), + ("give fonts: [{{name, parts}}…]", &["fonts", "name", "parts"]), ("give one of path, data or dataBase64", &["path", "data", "dataBase64"]), ("give origin: [x, y], or reset: true", &["origin", "reset"]), ("global must be true or false", &["global"]), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7639c326cb..e5c1b89f0b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3534,7 +3534,7 @@ digits Malayalam Malayalam Composite Fonts Bileşik Fontlar Export Composite Fonts Bileşik Fontları Dışa Aktar Import Composite Fonts Bileşik Fontları İçe Aktar -@msg each font must be {name, parts} her font {name, parts} biçiminde olmalı +@msg each font must be {{name, parts}} her font {{name, parts}} biçiminde olmalı @msg unknown key `{k}`; a font takes name and parts bilinmeyen anahtar `{k}`; bir font name ve parts alır @msg each font needs a name her fontun bir adı olmalı @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` bir bileşik fontun adı olamaz (1 ile {COMPOSITE_NAME_MAX} karakter arası, denetim karakteri olmadan) @@ -3547,7 +3547,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` iki bileşik fontun adı `{_1}` @msg `{_1}` is the name of an installed font `{_1}` yüklü bir fontun adı @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2}, bir bileşik font olan `{font}` ile ayarlı -@msg give fonts: [{name, parts}…] fonts verin: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] fonts verin: [{{name, parts}}…] @msg path is empty path boş @msg fonts must be a list of composite fonts fonts bir bileşik font listesi olmalı @msg names must be strings names dizeler olmalı @@ -6948,7 +6948,7 @@ axis Y Axis Y ekseni @msg `rows` must be lists of numbers or nulls, not {r} `rows`, sayı veya null listeleri olmalıdır, {r} değil @msg `scale` must be a number from 0.001 to 1000 `scale` 0.001 ile 1000 arasında bir sayı olmalıdır @msg `scope.{key}` must be a non-empty array `scope.{key}` boş olmayan bir dizi olmalıdır -@msg `scope` must be "document", {artboards} or {layers} `scope` "document", {artboards} veya {layers} olmalıdır +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` "document", {{artboards: [index, …]}} veya {{layers: [id, …]}} olmalıdır @msg `side` must be "left", "right", "top" or "bottom" `side` "left", "right", "top" veya "bottom" olmalıdır @msg `side` places the artboard: leave out x, y, width and height `side` çalışma yüzeyini yerleştirir: x, y, width ve height değerlerini vermeyin @msg `source` is the only path in series group `target` `source`, `target` seri grubundaki tek yoldur @@ -7133,7 +7133,7 @@ axis Y Axis Y ekseni @msg not a regular expression bir düzenli ifade değil @msg not an action set: the text doesn't start with /version and a number bir eylem seti değil: metin /version ve bir sayıyla başlamıyor @msg nothing to repeat yinelenecek bir şey yok -@msg numbers out of order in {_1} quantifier {_1} niceleyicisinde sayılar sırasız +@msg numbers out of order in {{}} quantifier {{}} niceleyicisinde sayılar sırasız @msg object {_1} needs a 3D effect {_1} nesnesinde bir 3D efekti olmalıdır @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Kalıp Çıkarma ve Eğim efektinin kapakları yoktur: bir grafik eşlemek için Kapak seçeneğini açın @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front nesne {_1}: derinlik 0 olduğunda nesnenin tek yüzü vardır: grafiklerini ön yüze eşleyin @@ -7204,7 +7204,7 @@ axis Y Axis Y ekseni @msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında @msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla @msg the method needs an XML value yöntem için bir XML değeri gerekir -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) boya bir serbest biçimli degrade değil (paint.editGradient {kind} ile bir tane uygulayın) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) boya bir serbest biçimli degrade değil (paint.editGradient {{kind: "freeform"}} ile bir tane uygulayın) @msg the parameters or body do not form one function parametreler veya gövde tek bir işlev oluşturmuyor @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it yapıştırılan {name} SVG filtresi belgedeki aynı adlı filtreden farklı çiziyor ve ona uyan boş bir ad yok @msg the paths are too many or too tangled to find where they cross yollar, kesiştikleri yerler bulunamayacak kadar çok veya karışık diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b95631a14b..0c56ea16ee 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3795,7 +3795,7 @@ effect Points Точки Composite Fonts Складені шрифти Export Composite Fonts Експорт складених шрифтів Import Composite Fonts Імпорт складених шрифтів -@msg each font must be {name, parts} кожен шрифт має бути у вигляді {name, parts} +@msg each font must be {{name, parts}} кожен шрифт має бути у вигляді {{name, parts}} @msg unknown key `{k}`; a font takes name and parts невідомий ключ `{k}`; шрифт приймає name і parts @msg each font needs a name кожен шрифт повинен мати назву @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` не може бути назвою складеного шрифту (від 1 до {COMPOSITE_NAME_MAX} символів, без керівних символів) @@ -3808,7 +3808,7 @@ effect Points Точки @msg two composite fonts are named `{_1}` два складені шрифти мають назву `{_1}` @msg `{_1}` is the name of an installed font `{_1}` є назвою встановленого шрифту @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} використовує `{font}`, а це складений шрифт -@msg give fonts: [{name, parts}…] вкажіть fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] вкажіть fonts: [{{name, parts}}…] @msg path is empty path порожній @msg fonts must be a list of composite fonts fonts має бути списком складених шрифтів @msg names must be strings names мають бути рядками @@ -7630,7 +7630,7 @@ breakText Glyphs Гліфи @msg `scale` must be a number from 0.001 to 1000 `scale` має бути числом від 0.001 до 1000 @msg `scale` must be a number in (0, 100] `scale` має бути числом у діапазоні (0, 100] @msg `scope.{key}` must be a non-empty array `scope.{key}` має бути непорожнім масивом -@msg `scope` must be "document", {artboards} or {layers} `scope` має бути "document", {artboards} або {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` має бути "document", {{artboards: [index, …]}} або {{layers: [id, …]}} @msg `scope` must be "selection" or "document", not {other} `scope` має бути "selection" або "document", а не {other} @msg `script` must be a string `script` має бути рядком @msg `seriesIndexes` is a non-empty list of series indexes `seriesIndexes` — це непорожній список індексів рядів @@ -8519,7 +8519,7 @@ breakText Glyphs Гліфи @msg nothing to print: every artboard picked is blank немає чого друкувати: усі вибрані монтажні області порожні @msg nothing to print: the document has no art that prints немає чого друкувати: документ не містить графіки, яка друкується @msg nothing to repeat немає чого повторювати -@msg numbers out of order in {_1} quantifier числа в неправильному порядку у квантифікаторі {_1} +@msg numbers out of order in {{}} quantifier числа в неправильному порядку у квантифікаторі {{}} @msg object is not a path об’єкт не є контуром @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object прозорість об’єкта не можна перенести на виділені символи; вимкніть «Прозорість» у параметрах піпетки або виділіть увесь об’єкт @msg object {_1} can't be set as point type об’єкт {_1} не можна зробити текстом із точки @@ -8874,7 +8874,7 @@ breakText Glyphs Гліфи @msg the page has no area сторінка не має площі @msg the page's type in an unread object's box isn't in its page art тексту сторінки в рамці непрочитаного об’єкта немає в графіці цієї сторінки @msg the paint behind the proxy is not a gradient фарба за індикатором не є градієнтом -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) фарба не є довільним градієнтом (застосуйте його за допомогою paint.editGradient {kind}) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) фарба не є довільним градієнтом (застосуйте його за допомогою paint.editGradient {{kind: "freeform"}}) @msg the parameters or body do not form one function параметри або тіло не утворюють одну функцію @msg the parent must be a layer or sublayer батьківським елементом має бути шар або підшар @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it вставлений фільтр SVG {name} малює інакше, ніж фільтр документа з таким іменем, а вільного імені для нього немає diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3cc07d98cc..f4dc052bd3 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4149,7 +4149,7 @@ mark-style Japanese Kiểu Nhật Composite Fonts Phông chữ tổ hợp Export Composite Fonts Xuất phông chữ tổ hợp Import Composite Fonts Nhập phông chữ tổ hợp -@msg each font must be {name, parts} mỗi phông chữ phải là {name, parts} +@msg each font must be {{name, parts}} mỗi phông chữ phải là {{name, parts}} @msg unknown key `{k}`; a font takes name and parts khóa không xác định `{k}`; một phông chữ nhận name và parts @msg each font needs a name mỗi phông chữ cần có tên @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` không thể là tên phông chữ tổ hợp (từ 1 đến {COMPOSITE_NAME_MAX} ký tự, không có ký tự điều khiển) @@ -4162,7 +4162,10 @@ mark-style Japanese Kiểu Nhật @msg two composite fonts are named `{_1}` có hai phông chữ tổ hợp cùng tên `{_1}` @msg `{_1}` is the name of an installed font `{_1}` là tên của một phông chữ đã cài đặt @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} dùng `{font}`, một phông chữ tổ hợp -@msg give fonts: [{name, parts}…] hãy cung cấp fonts: [{name, parts}…] +@msg give fonts: [{{name, parts}}…] hãy cung cấp fonts: [{{name, parts}}…] +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` phải là "document", {{artboards: [index, …]}} hoặc {{layers: [id, …]}} +@msg numbers out of order in {{}} quantifier các số không theo thứ tự trong lượng từ {{}} +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) màu tô không phải là chuyển sắc dạng tự do (hãy áp dụng một chuyển sắc bằng paint.editGradient {{kind: "freeform"}}) @msg path is empty path trống @msg fonts must be a list of composite fonts fonts phải là danh sách phông chữ tổ hợp @msg names must be strings names phải là chuỗi diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f96d93d9ea..adfe6dd1d6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3615,7 +3615,7 @@ digits Malayalam 马拉雅拉姆数字 Composite Fonts 复合字体 Export Composite Fonts 导出复合字体 Import Composite Fonts 导入复合字体 -@msg each font must be {name, parts} 每个字体都必须是 {name, parts} +@msg each font must be {{name, parts}} 每个字体都必须是 {{name, parts}} @msg unknown key `{k}`; a font takes name and parts 未知键 `{k}`;字体可用的键为 name 和 parts @msg each font needs a name 每个字体都需要名称 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` 不能用作复合字体的名称(1 到 {COMPOSITE_NAME_MAX} 个字符,不含控制字符) @@ -3628,7 +3628,7 @@ digits Malayalam 马拉雅拉姆数字 @msg two composite fonts are named `{_1}` 有两个复合字体都名为 `{_1}` @msg `{_1}` is the name of an installed font `{_1}` 是已安装字体的名称 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`:{_2} 使用了复合字体 `{font}` -@msg give fonts: [{name, parts}…] 请指定 fonts:[{name, parts}…] +@msg give fonts: [{{name, parts}}…] 请指定 fonts:[{{name, parts}}…] @msg path is empty path 为空 @msg fonts must be a list of composite fonts fonts 必须是复合字体列表 @msg names must be strings names 必须是字符串 @@ -7581,7 +7581,7 @@ breakText Glyphs 字形 @msg `rows` must be lists of numbers or nulls, not {r} `rows` 必须是由数字或 null 组成的列表,不能是 {r} @msg `scale` must be a number from 0.001 to 1000 `scale` 必须是 0.001 到 1000 之间的数字 @msg `scope.{key}` must be a non-empty array `scope.{key}` 必须是非空数组 -@msg `scope` must be "document", {artboards} or {layers} `scope` 必须是 "document"、{artboards} 或 {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` 必须是 "document"、{{artboards: [index, …]}} 或 {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` 必须是 "left"、"right"、"top" 或 "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` 决定画板的位置:请不要给出 x、y、width 和 height @msg `source` is the only path in series group `target` `source` 是系列组 `target` 中唯一的路径 @@ -7767,7 +7767,7 @@ breakText Glyphs 字形 @msg not a regular expression 不是正则表达式 @msg not an action set: the text doesn't start with /version and a number 不是动作组:文本不是以 /version 和一个数字开头 @msg nothing to repeat 没有可重复的内容 -@msg numbers out of order in {_1} quantifier 量词 {_1} 中的数字顺序颠倒 +@msg numbers out of order in {{}} quantifier 量词 {{}} 中的数字顺序颠倒 @msg object {_1} needs a 3D effect 对象 {_1} 需要有 3D 效果 @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic 对象 {_1}:空心的突出与斜角没有端面:请打开“端点”后再贴图 @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front 对象 {_1}:深度为 0 时对象只有一个面:请将图形贴到正面 @@ -7840,7 +7840,7 @@ breakText Glyphs 字形 @msg the library's file is outside the read roots 库文件位于可读取的根目录之外 @msg the line is too long, or the paths it passes too many, to check 线条过长,或它经过的路径过多,无法检查 @msg the method needs an XML value 此方法需要 XML 值 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 该上色不是自由渐变 (请用 paint.editGradient {kind} 应用一个) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 该上色不是自由渐变 (请用 paint.editGradient {{kind: "freeform"}} 应用一个) @msg the parameters or body do not form one function 参数或函数体不能构成一个函数 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 粘贴的 SVG 滤镜 {name} 与文档中同名滤镜的绘制结果不同,且没有可用的空闲名称 @msg the paths are too many or too tangled to find where they cross 路径过多或过于交错,无法找出它们的交叉位置 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6a962013ca..34f60488a7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4880,7 +4880,7 @@ digits Malayalam 馬來亞拉姆數字 Composite Fonts 複合字體 Export Composite Fonts 匯出複合字體 Import Composite Fonts 匯入複合字體 -@msg each font must be {name, parts} 每個字體都必須是 {name, parts} +@msg each font must be {{name, parts}} 每個字體都必須是 {{name, parts}} @msg unknown key `{k}`; a font takes name and parts 未知的鍵 `{k}`;字體可用的鍵為 name 和 parts @msg each font needs a name 每個字體都需要名稱 @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` 不能作為複合字體的名稱(1 到 {COMPOSITE_NAME_MAX} 個字元,不含控制字元) @@ -4893,7 +4893,7 @@ digits Malayalam 馬來亞拉姆數字 @msg two composite fonts are named `{_1}` 有兩個複合字體都名為 `{_1}` @msg `{_1}` is the name of an installed font `{_1}` 是已安裝字體的名稱 @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`:{_2} 使用了複合字體 `{font}` -@msg give fonts: [{name, parts}…] 請指定 fonts:[{name, parts}…] +@msg give fonts: [{{name, parts}}…] 請指定 fonts:[{{name, parts}}…] @msg path is empty path 為空 @msg fonts must be a list of composite fonts fonts 必須是複合字體清單 @msg names must be strings names 必須是字串 @@ -7509,7 +7509,7 @@ breakText Glyphs 字符 @msg `rows` must be lists of numbers or nulls, not {r} `rows` 必須是由數字或 null 組成的清單,而非 {r} @msg `scale` must be a number from 0.001 to 1000 `scale` 必須是 0.001 到 1000 之間的數字 @msg `scope.{key}` must be a non-empty array `scope.{key}` 必須是非空陣列 -@msg `scope` must be "document", {artboards} or {layers} `scope` 必須是 "document"、{artboards} 或 {layers} +@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` 必須是 "document"、{{artboards: [index, …]}} 或 {{layers: [id, …]}} @msg `side` must be "left", "right", "top" or "bottom" `side` 必須是 "left"、"right"、"top" 或 "bottom" @msg `side` places the artboard: leave out x, y, width and height `side` 會決定工作區域的位置:請不要提供 x、y、width 和 height @msg `source` is the only path in series group `target` `source` 是系列群組 `target` 中唯一的路徑 @@ -7695,7 +7695,7 @@ breakText Glyphs 字符 @msg not a regular expression 不是正規表示式 @msg not an action set: the text doesn't start with /version and a number 不是動作組:文字的開頭不是 /version 和一個數字 @msg nothing to repeat 沒有可重複的內容 -@msg numbers out of order in {_1} quantifier {_1} 量詞中的數字順序錯誤 +@msg numbers out of order in {{}} quantifier {{}} 量詞中的數字順序錯誤 @msg object {_1} needs a 3D effect 物件 {_1} 需要 3D 效果 @msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic 物件 {_1}:空心的「突出與斜角」沒有端面:請開啟「端點」才能對應圖形 @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front 物件 {_1}:深度為 0 時物件只有一個面:請將圖形對應到正面 @@ -7768,7 +7768,7 @@ breakText Glyphs 字符 @msg the library's file is outside the read roots 資料庫的檔案位於讀取根目錄之外 @msg the line is too long, or the paths it passes too many, to check 線條過長,或經過的路徑過多,無法檢查 @msg the method needs an XML value 此方法需要 XML 值 -@msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) 此上色不是任意形狀漸層 (請以 paint.editGradient {kind} 套用) +@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) 此上色不是任意形狀漸層 (請以 paint.editGradient {{kind: "freeform"}} 套用) @msg the parameters or body do not form one function 參數或主體無法構成一個函式 @msg the pasted SVG filter {name} draws differently from the document's filter of that name, and no free name fits it 貼上的 SVG 濾鏡 {name} 的繪製結果與文件中同名的濾鏡不同,而且找不到可用的名稱 @msg the paths are too many or too tangled to find where they cross 路徑過多或過於糾結,無法找出交叉處 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 21b0074bbd..2427ec2f90 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -964,6 +964,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). + - Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). - The Turkish catalog (`crates/ui-egui/src/i18n/tr.tsv`) has an `@msg` row for all but 41 of the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,446 `@msg` rows in all. The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - The Hungarian catalog (`crates/ui-egui/src/i18n/hu.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,444 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Hungarian messages: the composite font, justification order and connect end errors that open #7211, #7116 and #7330 translate, and two messages that no catalog has a row for. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. From f684b53263aba09dcbc769e7ef7bd7d2fa5cfdd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 15:03:49 -0800 Subject: [PATCH 074/138] i18n: French rows keep the no-break space before punctuation --- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 83409c96af..db4077f29e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5146,7 +5146,7 @@ axis Both Les deux @msg variables are locked les variables sont verrouillées @msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} plus de {MAX_CSV_ROWS} jeux de données : Importer des jeux de données en lit au plus {MAX_CSV_ROWS} @msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} plus de {MAX_CSV_COLS} variables : Importer des jeux de données en lit au plus {MAX_CSV_COLS} -@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ont été ignorées : {kinds} +@msg variables that aren't text were left out: {kinds} les variables qui ne sont pas du texte ont été ignorées : {kinds} variable-kind Visibility Visibilité variable-kind Linked File Fichier lié variable-kind Graph Data Données du graphe diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 14a59e7add..815210e260 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2279,7 +2279,7 @@ fn svg_variable_kinds_left_out_translate_in_every_complete_catalog() { ); assert_eq!(message(de, &warning("`Visibility` (1)")), "die Variablen, die kein Text sind, wurden ausgelassen: `Visibility` (1)"); let fr = Lang::from_code("fr").expect("registered"); - assert_eq!(message(fr, &warning("Visibility (1)")), "les variables qui ne sont pas du texte ont été ignorées : Visibilité (1)"); + assert_eq!(message(fr, &warning("Visibility (1)")), "les variables qui ne sont pas du texte ont été ignorées\u{a0}: Visibilité (1)"); let ja = Lang::from_code("ja").expect("registered"); assert_eq!( message(ja, &warning("Visibility (1), Linked File (2), Unknown (1)")), From 356740101dda6e088b552bc5d53696b14dbeb6ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 15:09:25 -0800 Subject: [PATCH 075/138] i18n: French rows keep the no-break space before punctuation --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e34374a651..5a51bbd6fd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3761,7 +3761,7 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` deux polices composites s’appellent `{_1}` @msg `{_1}` is the name of an installed font `{_1}` est le nom d’une police installée @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}` : {_2} utilise `{font}`, une police composite -@msg give fonts: [{{name, parts}}…] indiquez fonts : [{{name, parts}}…] +@msg give fonts: [{{name, parts}}…] indiquez fonts : [{{name, parts}}…] @msg path is empty path est vide @msg fonts must be a list of composite fonts fonts doit être une liste de polices composites @msg names must be strings names doit contenir des chaînes From 592dcec59cb591a876c67f1d4b95e4e859039021 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 15:59:51 -0800 Subject: [PATCH 076/138] MCP: regenerate the UI command catalog for Options of Selected Object The catalog's params text for ui.brushObjectOptions now matches the desktop table, which says that changing one end of a range or one colorization field leaves each path's other values as they are. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index be0028cc72..59bfe792bb 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -919,7 +919,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened, and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", From be12c9ed368e728a70835c732d0f1fb9ea1fd5d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:52:41 -0800 Subject: [PATCH 077/138] Brushes: Options of Selected Object keeps a path's null modes and largest width, and its document - A calligraphic path's `modes: null` (modes that follow its values) stays when another value changes, instead of falling back to the brush's modes. - An art `width` without a `width_max` keeps the largest width of each path whose width follows the pen, so editing Width no longer moves the other end. - OK changes nothing when another document has become the active one since the dialog opened, as Delete Brush does. --- crates/brush/src/lib.rs | 10 ++++-- crates/brush/src/tests.rs | 17 +++++++++ crates/engine/src/cmd/brushsym/brushes.rs | 25 +++++++++++++ crates/engine/src/tests/brushsym.rs | 35 +++++++++++++++++++ crates/ui-egui/src/dialogs/brush_options.rs | 21 ++++++++--- .../src/dialogs/brush_options/tests.rs | 20 +++++++++++ docs/mcp.md | 4 ++- 7 files changed, 124 insertions(+), 8 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 718a552f32..7129279b31 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -804,10 +804,16 @@ impl BrushKind { } } - /// The values of [`Self::stroke_option_keys`], as a JSON object. + /// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the + /// values are a `null` `modes`, so a stroke that sets them so keeps that setting. fn option_values(&self) -> serde_json::Value { let v = match self { - BrushKind::Calligraphic(c) => serde_json::to_value(c), + BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| { + if let Some(o) = v.as_object_mut() { + o.entry("modes").or_insert(serde_json::Value::Null); + } + v + }), BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions { size: s.size, spacing: s.spacing, diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 46779d8e2d..437ec4028f 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2118,3 +2118,20 @@ fn null_stroke_option_items_keep_the_items_the_stroke_has() { let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap(); assert!(same.is_empty(), "{same:?}"); } + +#[test] +fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() { + let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default(); + // A brush whose modes are its own, and a stroke whose modes follow its values instead. + let mut b = calli(0.0, 100.0, 3.0); + if let BrushKind::Calligraphic(c) = &mut b.kind { + c.modes = Some([Variation::Pressure; 3]); + } + let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap(); + assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0})); + let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") }; + assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give"); + // A brush whose modes follow its values: a null `modes` is the brush's own and is left out. + let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap(); + assert!(plain.is_empty(), "{plain:?}"); +} diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 8ddeb99b29..5f7687fb47 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -574,6 +574,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result merged.insert(k.clone(), next); } keep_drawn_modes(b, &was, ¶ms, &mut merged); + keep_largest_width(b, &was, ¶ms, &mut merged); b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? }; options.get_or_insert_with(|| next.clone()); @@ -636,6 +637,30 @@ fn keep_drawn_modes( merged.insert("modes".into(), Value::Array(kept)); } +/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when +/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is +/// the width, so without this a changed width would also change the largest width. +fn keep_largest_width( + b: &Brush, + was: &serde_json::Map, + params: &serde_json::Map, + merged: &mut serde_json::Map, +) { + if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + return; + } + let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some(a), + _ => None, + }; + let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; + let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); + // Only a width that followed the pen has a largest width, and only one that still does uses it. + if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { + merged.insert("width_max".into(), json!(before.width)); + } +} + /// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it /// places them; `brush.replaceArt` reads a group of that name as that tile. const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"]; diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 02bf2b4a6f..957f6ea6a4 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -207,6 +207,41 @@ fn options_of_selected_object_keep_the_modes_each_path_draws_with() { assert_eq!((confetti_size_mode(&s, a), confetti_size_mode(&s, b)), (Variation::Fixed, Variation::Fixed)); } +/// The widths (%) the first stroke of `id`, painted with Arrow, draws with at the lightest and the +/// heaviest pressure. +fn arrow_width_range(s: &Session, id: NodeId) -> (f64, f64) { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Arrow").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Art(a) => a.width_range(), + k => panic!("not an art brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_changes() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Arrow", "ids": [a.0, b.0]})).unwrap(); + // Both widths follow the pressure; the first path's largest width is its width, the second + // path's is its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100, "width_mode": "pressure"}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"width": 100, "width_mode": "pressure", "width_max": 150}})).unwrap(); + assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((100.0, 100.0), (100.0, 150.0))); + // The width the path has already changes nothing. + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"width": 100}})).unwrap()["changed"], json!([])); + assert_eq!(own_options(&s, a), json!({"width_mode": "pressure"})); + assert_eq!(undo_steps(&s), steps); + // A new smallest width leaves each path's largest width as it was. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 50}})).unwrap(); + assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((50.0, 100.0), (50.0, 150.0))); + // A largest width the params give is set on each path. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"width": 40, "width_max": 120}})).unwrap(); + assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); +} + #[test] fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 310cd36f6b..eafe697a0f 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -20,9 +20,10 @@ //! //! The panel menu's Options of Selected Object opens the dialog on the brush of the first selected //! brushed path, with that path's own settings ([`open_object`]), with `__object`, `__targets` (the -//! brushed paths) and `__opened` (the values it opened with). It has no name, and of the Art and -//! Pattern brush options only those a path can set for itself. OK runs `brush.objectOptions` with -//! the values changed since it opened: the paths change and the brush stays as it is. +//! brushed paths), `__opened` (the values it opened with) and `__doc` (the uid of the document). It +//! has no name, and of the Art and Pattern brush options only those a path can set for itself. OK +//! runs `brush.objectOptions` with the values changed since it opened: the paths change and the +//! brush stays as it is. OK after another document has become the active one changes nothing. use egui::{Color32, Sense, Stroke, pos2, vec2}; use serde_json::{Map, Value, json}; @@ -55,6 +56,9 @@ const TARGETS: &str = "__targets"; /// The field of such a dialog holding the `brush.objectOptions` params it opened with. const OPENED: &str = "__opened"; +/// The field of such a dialog holding the uid of the document it opened in. +const DOC: &str = "__doc"; + /// Calligraphic values: (field, label, suffix, decimals), in [`Calligraphic::RANGES`] order. const CALLI: [(&str, &str, &str, usize); 3] = [("angle", "Angle:", "°", 0), ("roundness", "Roundness:", "%", 0), ("size", "Size:", " pt", 1)]; @@ -216,7 +220,8 @@ pub fn open_object(app: &mut VectorcraftApp) -> Result { let r = app.run("brush.objectOptions", json!({}))?; let targets = r["ids"].clone(); let first = targets.get(0).and_then(Value::as_u64).map(NodeId).ok_or("no path painted with a brush is selected")?; - let lib = vectorcraft_brush::library(&app.session.active().ok_or("no document open")?.doc); + let st = app.session.active().ok_or("no document open")?; + let (lib, doc) = (vectorcraft_brush::library(&st.doc), st.uid); let b = stroke_brush(app, &lib, first).ok_or("no path painted with a brush is selected")?; let own: Map = serde_json::from_value(r["options"].clone()).unwrap_or_default(); let edited = b.with_stroke_options(&own)?; @@ -225,6 +230,7 @@ pub fn open_object(app: &mut VectorcraftApp) -> Result { f.insert("__brush".into(), json!(b.name)); f.insert(OBJECT.into(), json!(true)); f.insert(TARGETS.into(), targets); + f.insert(DOC.into(), json!(doc)); let mut d = Dialog { kind: KIND.into(), fields: f }; let opened = object_params(&d, b.kind.stroke_option_keys()); d.fields.insert(OPENED.into(), Value::Object(opened)); @@ -256,8 +262,13 @@ fn changed_part(was: Option<&Value>, now: Value) -> Option { } /// OK of Options of Selected Object: `brush.objectOptions` on the paths it opened for, with the -/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. +/// values changed since it opened ([`changed_part`]). The dialog closes when they are set. When +/// another document has become the active one, it closes as Cancel does and changes nothing. fn confirm_object(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|doc| doc.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } let keys: Vec = d.fields.get("__keys").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); let opened = d.fields.get(OPENED).and_then(Value::as_object).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 037c953db5..fd6721ca69 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -999,3 +999,23 @@ fn options_of_selected_object_show_what_a_path_can_set_for_each_type() { app.run("select.none", json!({})).unwrap(); assert!(!object_available(&app)); } + +#[test] +fn options_of_selected_object_change_nothing_after_another_document_became_active() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Arrow"); + select(&mut app, &[a]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"width": 50})); + // A second document with a brushed path of the same id becomes the active one. + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = brushed_line(&mut app, 50.0, "Arrow"); + assert_eq!(other, a); + // OK closes the dialog as Cancel does. + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(own_options(&app, other), json!({}), "the second document's path keeps the brush's settings"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(own_options(&app, a), json!({}), "the first document's path keeps the brush's settings"); +} diff --git a/docs/mcp.md b/docs/mcp.md index bee403373d..509ca8f849 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3468,7 +3468,9 @@ already walks Image Trace. Short agent entry points: equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one end of a range leaves each selected path's other end as it was. A mode that `params` does not set (no `modes`, or a `null` item) stays the one each path draws with, so a changed calligraphic variation or scatter range does not - change it. `reset: true` clears a path's settings. The command + change it. An art `width` without a `width_max` keeps the largest width of each path whose width follows the pen, + and a calligraphic path's `modes: null` (modes that follow its values) stays when another value changes. The dialog + changes nothing when another document has become the active one. `reset: true` clears a path's settings. The command refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different types, a bristle brush and a field the type does not take. It records one undo step, and none when nothing changes. `brush.options` edits still reach the settings a path does not set, `brush.apply`, a brush change in From 4e38d4f7075b8475edb438d570bdd4376908fe6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:35:07 -0800 Subject: [PATCH 078/138] Command Palette: a plural or verb form finds the command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A query word in an English plural or verb form now meets the base word of a result's English name or menu path: "rounded corners" lists Round Corners… first, "scaling" finds Scale…, "rasterizes" finds Rasterize… and "added anchor points" finds Add Anchor Points. The index stores up to two stem forms per English word, and a query word's stem forms are looked up exactly: - 's is dropped, and sses becomes ss. - es after s, x, z, ch or sh is dropped, and the word with only its s dropped is a second form. - A final s is dropped in words of more than 3 letters, except after ss, us or is. - ies becomes y or ie in words of more than 5 letters. - ing (more than 5 letters) and ed (more than 4) are dropped. A doubled b, d, g, m, n, p, r or t left before them gives the single and the doubled letter, the single one only when at least 3 letters are left; otherwise the rest with an e added is the second form. - series and species are left as they are. A result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale" now lists a name with Scaling above one with Scalers. A partly typed word that is not itself a word of any result ("scal") does not meet a stem form. The grades of the other matches keep their order and their sums, so results matched without a stem keep their order. Names shown in other languages and ids are not stemmed, and the words as written stay in the index, so every result found before is still found. --- crates/ui-egui/src/palette.rs | 6 +- crates/ui-egui/src/palette/search.rs | 290 +++++++++++++++++++++++---- docs/target-app-parity.md | 1 + 3 files changed, 258 insertions(+), 39 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 544929a0e7..73183340d7 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1761,10 +1761,12 @@ mod tests { assert_eq!(panels.len(), crate::state::all_panels().count()); // Many results hold "layers" in their menu path; the panel, named Layers, is shown first, and "color guide" shows the Color Guide panel first too. for (query, want) in [("layers", "panel:layers"), ("color guide", "panel:colorGuide"), ("Layers ", "panel:layers")] { - let all = entries.iter().filter(|e| query.to_lowercase().split_whitespace().all(|w| e.haystack.contains(w))).count(); + let all: Vec<&str> = + entries.iter().filter(|e| query.to_lowercase().split_whitespace().all(|w| e.haystack.contains(w))).map(|e| e.id.as_str()).collect(); let shown: Vec<&str> = matching(&entries, &query.to_lowercase()).into_iter().map(|e| e.id.as_str()).collect(); assert_eq!(shown.first(), Some(&want), "{query}: {shown:?}"); - assert_eq!(shown.len(), all, "{query}"); + // English plural and verb forms can find more results than the text alone. + assert!(all.iter().all(|id| shown.contains(id)), "{query}"); } let layers = entries.iter().find(|e| e.id == "panel:layers").unwrap(); assert_eq!(layers.shown, "Window › Show Panel › Layers"); diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index a2bc113d4a..0165432b2a 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -10,19 +10,26 @@ use crate::menus; /// and the exact tiers read the whole query. const INDEX_CHARS: usize = 200; -/// The field of a result a word comes from, best first. +/// The field of a result a word comes from, best first, and the fields of the English stem forms +/// ([`stems`]) of the words of the label and the menu path. const LABEL: u8 = 0; const PATH: u8 = 1; const ID: u8 = 2; +const LABEL_STEMMED: u8 = 3; +const PATH_STEMMED: u8 = 4; /// A word's grade in a result, best first: a whole word of the label, a word of the label it -/// starts, a word of the menu path it is or starts, a word of the id it is or starts, or text -/// inside a word of any field ([`super::matching`]'s substring rule). -const LABEL_WORD: u8 = 1; -const LABEL_PREFIX: u8 = 2; -const PATH_WORD: u8 = 3; -const ID_WORD: u8 = 4; -const SUBSTRING: u8 = 5; +/// shares an English stem form with ("outlines" and Outline), a word of the label it starts, a +/// word of the menu path it is, shares a stem form with or starts, a word of the id it is or +/// starts, or text inside a word of any field ([`super::matching`]'s substring rule). The grades +/// without a stem are twice the values they had before stems were added, so results matched +/// without a stem keep their order by the sum of the grades. +const LABEL_WORD: u8 = 2; +const LABEL_STEM: u8 = 3; +const LABEL_PREFIX: u8 = 4; +const PATH_WORD: u8 = 6; +const ID_WORD: u8 = 8; +const SUBSTRING: u8 = 10; const NONE: u8 = u8::MAX; /// How a whole query matches a result, best first: it is the result's id, it is a label, a label @@ -34,7 +41,7 @@ const INITIALS: u8 = 3; const NO_PHRASE: u8 = 4; /// One result in the list of a term: the result's place in the catalog and the field the term is -/// a word of. +/// a word or a word's stem form of. #[derive(Clone, Copy)] struct Posting { entry: u16, @@ -73,6 +80,70 @@ fn initials_of(label: &str) -> String { .collect() } +/// The English stem forms of the lowercased `word`, at most two, and none for a word that is not +/// plain English letters. `'s` is dropped; `sses` becomes `ss`; `es` after `s`, `x`, `z`, `ch` or +/// `sh` is dropped, and with only its `s` dropped the word is a second form (`boxes`, `box` and +/// `boxe`; `rasterizes`, `rasteriz` and `rasterize`); in a word of more than 5 letters, `ies` +/// becomes `y` or `ie` (`copies`, `copy` and `copie`; `movies`, `movy` and `movie`); `ing` (more +/// than 5 letters) and `ed` (more than 4) are dropped, and when a doubled `b`, `d`, `g`, `m`, `n`, +/// `p`, `r` or `t` is left before them, the rest with that letter made single and the rest as it +/// is are the forms (`cutting`, `cut` and `cutt`), the single one only when it keeps at least 3 +/// letters (`added`, `add` alone); otherwise the rest and the rest followed by `e` are the forms +/// (`scaling`, `scal` and `scale`); a final `s` is dropped from a word of more than 3 letters that +/// does not end in `ss`, `us` or `is`. `series` and `species` have none. +fn stems(word: &str) -> Vec { + let one = |rest: &str| if rest.is_empty() { vec![] } else { vec![rest.to_string()] }; + if !word.bytes().all(|b| b.is_ascii_lowercase() || b == b'\'') || matches!(word, "series" | "species") { + return vec![]; + } + let n = word.len(); + if let Some(rest) = word.strip_suffix("'s") { + return one(rest); + } + if let Some(rest) = word.strip_suffix("sses") { + return vec![format!("{rest}ss")]; + } + if let Some(rest) = word.strip_suffix("es") + && ["s", "x", "z", "ch", "sh"].iter().any(|end| rest.ends_with(end)) + { + return vec![rest.to_string(), format!("{rest}e")]; + } + if n > 5 + && let Some(rest) = word.strip_suffix("ies") + { + return vec![format!("{rest}y"), format!("{rest}ie")]; + } + let verb = if n > 5 { word.strip_suffix("ing") } else { None }.or_else(|| if n > 4 { word.strip_suffix("ed") } else { None }); + if let Some(rest) = verb { + if let [.., a, b] = rest.as_bytes() + && a == b + && b"bdgmnprt".contains(a) + { + let single = rest.get(..rest.len() - 1).unwrap_or_default(); + if single.len() < 3 { + return vec![rest.to_string()]; + } + return vec![single.to_string(), rest.to_string()]; + } + return vec![rest.to_string(), format!("{rest}e")]; + } + if n > 3 && word.ends_with('s') && !["ss", "us", "is"].iter().any(|end| word.ends_with(end)) { + return one(word.get(..n - 1).unwrap_or_default()); + } + vec![] +} + +/// Adds each word of `text` to `found` for result `entry` in `field`, and with `stemmed`, each +/// word's English stem forms in that field. +fn add_words(found: &mut Vec<(String, u16, u8)>, text: &str, entry: u16, field: u8, stemmed: Option) { + for w in words(text) { + found.push((w.to_string(), entry, field)); + if let Some(stemmed) = stemmed { + found.extend(stems(w).into_iter().map(|s| (s, entry, stemmed))); + } + } +} + /// A name's last `›`-separated part (the label) and the parts before it (the menu path). fn split_name(name: &str) -> (&str, &str) { match name.rsplit_once(" › ") { @@ -99,9 +170,10 @@ fn ids(e: &Entry) -> impl Iterator { impl Index { /// The index of `entries`, whose menu homes and menu items read `homes` in the UI language. The - /// words of a result's menu home and of its menu item's label count as menu path words. A - /// catalog with more results than a posting can name gets an empty index, and queries match by - /// the substring rule alone. + /// words of a result's menu home and of its menu item's label count as menu path words. The + /// words of the English names, menu home and menu item label also add their English stem forms + /// ([`stems`]); words in the UI language do not. A catalog with more results than a posting can + /// name gets an empty index, and queries match by the substring rule alone. pub(crate) fn build(entries: &[Entry], homes: &[Option]) -> Index { if entries.len() > usize::from(u16::MAX) { return Index::default(); @@ -114,10 +186,13 @@ impl Index { let id = ids(e).next().unwrap_or_default(); let start = initials_text.len(); let mut seen_initials: Vec = vec![]; - for name in names(e) { + // The first two names are English, so their words also give stem forms; the shown name + // may be in another language, and its words are indexed as they are. + for (n, name) in names(e).enumerate() { + let english = n < 2; let (label, path) = split_name(without_id(name, id)); - found.extend(words(label).map(|w| (w.to_string(), entry, LABEL))); - found.extend(words(path).map(|w| (w.to_string(), entry, PATH))); + add_words(&mut found, label, entry, LABEL, english.then_some(LABEL_STEMMED)); + add_words(&mut found, path, entry, PATH, english.then_some(PATH_STEMMED)); let ini = initials_of(label); if ini.chars().count() >= 2 && !seen_initials.contains(&ini) { if !seen_initials.is_empty() { @@ -127,8 +202,11 @@ impl Index { seen_initials.push(ini); } } - for home in [e.home.as_deref(), Some(e.menu_item), homes.get(i).and_then(Option::as_deref)].into_iter().flatten() { - found.extend(words(&home.to_lowercase()).map(|w| (w.to_string(), entry, PATH))); + for home in [e.home.as_deref(), Some(e.menu_item)].into_iter().flatten() { + add_words(&mut found, &home.to_lowercase(), entry, PATH, Some(PATH_STEMMED)); + } + if let Some(home) = homes.get(i).and_then(Option::as_deref) { + add_words(&mut found, &home.to_lowercase(), entry, PATH, None); } for id in ids(e) { found.extend(words(id).map(|w| (w.to_string(), entry, ID))); @@ -183,10 +261,33 @@ impl Index { self.term_text.get(offset..offset + len as usize).unwrap_or_default() } - /// The best grade (1 to 4) `word` gets in each result, [`NONE`] where it is no word and starts - /// no word of the result. The words it starts are found by a binary search of the sorted words. + /// The postings of the word at place `t` in `terms`. + fn postings_of(&self, t: usize) -> &[Posting] { + let Some(&(begin, len)) = self.spans.get(t) else { return &[] }; + let (begin, len) = (begin as usize, len as usize); + self.postings.get(begin..begin + len).unwrap_or_default() + } + + /// The place of the word `text` in `terms`, found by a binary search. + fn find(&self, text: &str) -> Option { + self.terms.binary_search_by(|t| self.text(t).cmp(text)).ok() + } + + /// The best grade ([`LABEL_WORD`] to [`ID_WORD`]) `word` gets in each result, [`NONE`] where it + /// is no word, shares no English stem form with a word of the label or menu path, and starts no + /// word of the result. The words it starts are found by a binary search of the sorted words; a + /// stem form matches only a word or stem form equal to it. fn grades(&self, word: &str, n: usize) -> Vec { let mut out = vec![NONE; n]; + let mut mark = |postings: &[Posting], grade: &dyn Fn(u8) -> Option| { + for p in postings { + if let Some(grade) = grade(p.field) + && let Some(g) = out.get_mut(usize::from(p.entry)) + { + *g = (*g).min(grade); + } + } + }; let start = self.terms.partition_point(|t| self.text(t) < word); for (t, at) in self.terms.iter().enumerate().skip(start) { let term = self.text(at); @@ -194,19 +295,37 @@ impl Index { break; } let whole = term == word; - let Some(&(begin, len)) = self.spans.get(t) else { continue }; - let (begin, len) = (begin as usize, len as usize); - for p in self.postings.get(begin..begin + len).unwrap_or_default() { - let grade = match p.field { - LABEL if whole => LABEL_WORD, - LABEL => LABEL_PREFIX, - PATH => PATH_WORD, - _ => ID_WORD, - }; - if let Some(g) = out.get_mut(usize::from(p.entry)) { - *g = (*g).min(grade); - } - } + // A stem form is not a word of the result, so a query word that only starts it does + // not match. + mark(self.postings_of(t), &|field| match field { + LABEL if whole => Some(LABEL_WORD), + LABEL => Some(LABEL_PREFIX), + PATH => Some(PATH_WORD), + ID => Some(ID_WORD), + _ => None, + }); + } + // The word meets a stem form of a word of the result ("scale" and Scaling) when it is itself + // a word of some result, so a partly typed word ("scal") that only equals a stem form does + // not lift Scaling above Scale. + if let Some(t) = self.find(word) + && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH | ID)) + { + mark(self.postings_of(t), &|field| match field { + LABEL_STEMMED => Some(LABEL_STEM), + PATH_STEMMED => Some(PATH_WORD), + _ => None, + }); + } + // A stem form of the word meets a word of the result or a stem form of one ("outlines" + // and Outline, "rotated" and Rotating). Ids are not stemmed. + for form in stems(word) { + let Some(t) = self.find(&form) else { continue }; + mark(self.postings_of(t), &|field| match field { + LABEL | LABEL_STEMMED => Some(LABEL_STEM), + PATH | PATH_STEMMED => Some(PATH_WORD), + _ => None, + }); } out } @@ -267,10 +386,11 @@ type RankKey = (u8, u8, u32, u8, usize); /// The results of `entries` that the lowercased `query` matches, best first, as places in /// `entries`. A result matches when every word of the query is text in one of its names or ids /// (the rule the palette always had, so nothing it found is lost), when every word of the query is -/// or starts a word of its label, menu path or id, or when the query is the initials of a label -/// ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), then by -/// the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the label's -/// length and the catalog order. An empty query lists every result in catalog order. +/// or starts a word of its label, menu path or id or shares an English stem form with a word of its +/// label or menu path ("rounded corners" for Round Corners…), or when the query is the initials of +/// a label ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), +/// then by the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the +/// label's length and the catalog order. An empty query lists every result in catalog order. pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { let query = normalize(query); if query.is_empty() { @@ -412,8 +532,13 @@ mod tests { for (query, better, worse) in [ // A whole word of the label, then a word of the label it starts. ("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two")), + // A whole word of the label, then a word of the label it shares a stem form with. + ("scale zz", entry("Zz Scale", "a.one"), entry("Zz Scaling", "b.two")), + // A word of the label it shares a stem form with, then a word of the label it starts. + // The id makes "scale" a word of the catalog. + ("scale zz", entry("Zz Scaling", "a.one"), entry("Zz Scalers", "scale.two")), // A word of the label it starts, then a word of the menu path. - ("fill zz", entry("Zz Filling", "a.one"), entry("Fill › Zz Other", "b.two")), + ("fill zz", entry("Zz Fillet", "a.one"), entry("Fill › Zz Other", "b.two")), // A word of the menu path, then a word of the id. ("zap zz", entry("Zap › Zz One", "a.one"), entry("Zz Two", "zap.two")), // A word of the id, then text inside a word. @@ -426,6 +551,26 @@ mod tests { } } + /// A partly typed word that equals only a stem form ("scal" of Scaling, "spac" of Spacing) is a + /// word the query starts in both results, so the shorter label stays first. + #[test] + fn a_partly_typed_word_does_not_lift_a_verb_form() { + for (query, base, form) in [("scal zz", "Zz Scale", "Zz Scaling"), ("spac zz", "Zz Space", "Zz Spacing"), ("ad zz", "Zz Add", "Zz Added")] { + let c = synthetic(vec![entry(form, "a.one"), entry(base, "b.two")]); + assert_eq!(ranked(&c, query), ["b.two", "a.one"], "{query}"); + } + } + + /// Results that no stem form matches keep the order they had before stems were added: two + /// results whose grades summed the same still tie on the sum, and the shorter label comes + /// first. + #[test] + fn results_matched_without_a_stem_keep_their_order() { + // Two label prefixes and a menu path word, against a label word and two menu path words. + let c = synthetic(vec![entry("Bet › Gam › Alp Zzzzzzzzzz", "b.two"), entry("Gam › Alpx Betx", "a.one")]); + assert_eq!(ranked(&c, "alp bet gam"), ["a.one", "b.two"]); + } + /// For each pair of adjacent whole-query tiers, a result in the better tier ranks above one in /// the worse. #[test] @@ -476,6 +621,77 @@ mod tests { } } + /// Do `a` and `b` share a form, each taken as it is or as one of its stem forms? + fn meet(a: &str, b: &str) -> bool { + let forms = |w: &str| std::iter::once(w.to_string()).chain(stems(w)).collect::>(); + let b = forms(b); + forms(a).iter().any(|f| b.contains(f)) + } + + /// English plurals and verb forms meet their base word, and words that only look alike do not. + #[test] + fn plurals_and_verb_forms_meet_their_base_word() { + for (a, b) in [ + ("outlines", "outline"), + ("rounded", "round"), + ("paths", "path"), + ("cutting", "cut"), + ("scaling", "scale"), + ("rotated", "rotate"), + ("spacing", "space"), + ("tracing", "trace"), + ("curved", "curve"), + ("filled", "fill"), + ("missing", "missing"), + ("boxes", "box"), + ("brushes", "brush"), + ("glasses", "glass"), + ("copies", "copy"), + ("movies", "movie"), + ("artist's", "artist"), + ("rotated", "rotating"), + ("added", "add"), + ("rasterizes", "rasterize"), + ("sizes", "size"), + ] { + assert!(meet(a, b), "{a} meets {b}"); + } + for (a, b) in [("series", "sery"), ("missing", "mis"), ("press", "pres"), ("bus", "bu"), ("axis", "axi"), ("cutting", "cu"), ("added", "ad")] + { + assert!(!meet(a, b), "{a} does not meet {b}"); + } + for w in ["outlines", "scaling", "cutting", "copies", "s", "'s", "ed", "ing", "übers", "群組", "series"] { + assert!(stems(w).len() <= 2, "{w}"); + assert!(stems(w).iter().all(|s| !s.is_empty() && s != w), "{w}: {:?}", stems(w)); + } + assert!(stems("übers").is_empty() && stems("series").is_empty() && stems("species").is_empty()); + } + + /// A query word in a plural or verb form finds a result whose label or menu path holds the base + /// word, below one that holds the word itself, and the words of a name shown in another language + /// are not stemmed. + #[test] + fn a_plural_or_verb_form_finds_the_result() { + let c = synthetic(vec![entry("Zz Rotate", "a.one"), entry("Spacing › Zz Other", "b.two"), entry("Zz Rotated", "c.three")]); + assert_eq!(ranked(&c, "rotating"), ["a.one", "c.three"]); + assert_eq!(ranked(&c, "rotated"), ["c.three", "a.one"]); + assert_eq!(ranked(&c, "spaces other"), ["b.two"], "through the menu path"); + let shown = Entry { shown: "Zz Trees".into(), haystack: "zz one\nzz one\nzz trees\na.one".into(), ..entry("Zz One", "a.one") }; + let c = synthetic(vec![shown, entry("Zz Trees", "b.two")]); + assert_eq!(ranked(&c, "treed zz"), ["b.two"], "only the English name is stemmed"); + let en = catalog(Lang::EN, false); + assert!(place(&en, "outlines", "type.createOutlines").is_some_and(|p| p < 3)); + assert_eq!(ranked(&en, "rounded corners").first().map(String::as_str), Some("effect:stylize.roundCorners")); + for (q, id) in [ + ("scaling", "object.scale"), + ("rotated", "object.rotate"), + ("rasterizes", "object.rasterize"), + ("added anchor points", "object.path.addAnchorPoints"), + ] { + assert!(place(&en, q, id).is_some(), "{q} finds {id}"); + } + } + /// The application menu of the native Mac menu bar holds the items [`menu_homes`] puts there, /// under the same submenus. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4422fb11d7..6547938d04 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1305,6 +1305,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). + A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. A result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale" now lists a name with "Scaling" above one with "Scalers". A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `results_matched_without_a_stem_keep_their_order`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. 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 these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From aba7657b25a9ea346313a3f0a3f8899f285610d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:27:47 -0800 Subject: [PATCH 079/138] Command Palette: state that a whole-query tier ranks before a stem form The search orders results by how the whole query matches before the word grades, so "scale" lists Scalers, whose name starts with the query, above Scaling. The progress line now says the stem rule applies among results in the same whole-query tier, and a test pins both orders. The test of Effect menu results reads the results and the Effect menu items within one plug-in revision, so a live-effect plug-in that another test installs between the two reads no longer fails it. --- crates/ui-egui/src/palette.rs | 12 ++++++++++-- crates/ui-egui/src/palette/search.rs | 12 ++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 73183340d7..66925f3ce7 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1803,8 +1803,16 @@ mod tests { /// does, and changes nothing until the dialog is confirmed. #[test] fn an_effect_is_a_result_whose_pick_runs_its_menu_item() { - let entries = build(Lang::EN); - let effects = crate::shortcut_editor::effect_items(); + // Both reads see the same plug-in revision: another test may install or remove a live + // effect plug-in between them. + let (entries, effects) = loop { + let revision = menus::plugin_revision(); + let entries = build(Lang::EN); + let effects = crate::shortcut_editor::effect_items(); + if menus::plugin_revision() == revision { + break (entries, effects); + } + }; for e in effects.iter() { let key = format!("effect:{}", e.effect); assert_eq!(entries.iter().filter(|r| r.id == key).count(), 1, "{key}"); diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 0165432b2a..e20d75e610 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -561,6 +561,18 @@ mod tests { } } + /// How the whole query matches comes before the word grades, so a stem form ranks above a word + /// the query starts only among results in the same whole-query tier: "scale" lists Scale, then + /// Scalers, which starts with the query, then Scaling, and "scale zz" lists Zz Scaling above Zz + /// Scalers. + #[test] + fn a_whole_query_tier_comes_before_a_stem_form() { + let c = synthetic(vec![entry("Scaling", "c.three"), entry("Scalers", "b.two"), entry("Scale", "a.one")]); + assert_eq!(ranked(&c, "scale"), ["a.one", "b.two", "c.three"]); + let c = synthetic(vec![entry("Zz Scalers", "b.two"), entry("Zz Scaling", "a.one"), entry("Zz Scale", "c.three")]); + assert_eq!(ranked(&c, "scale zz"), ["c.three", "a.one", "b.two"]); + } + /// Results that no stem form matches keep the order they had before stems were added: two /// results whose grades summed the same still tie on the sum, and the shorter label comes /// first. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6547938d04..9ea906ce7d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1305,7 +1305,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). - A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. A result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale" now lists a name with "Scaling" above one with "Scalers". A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `results_matched_without_a_stem_keep_their_order`). + A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. 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 these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From ea5ab864299c30800c5b90e516070f339e2e668f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:35:25 -0800 Subject: [PATCH 080/138] Path Eraser: path.eraseSegments refuses a width outside 0.001 to 1000 pt path.eraseSegments checked only that `width` was a positive number, so a width such as 1e300 erased every selected path and a width such as 1e-300 sampled the path too coarsely to find the band. It now refuses a width outside 0.001 to 1000 pt with "`width` must be from 0.001 to 1000" before reading the document; nothing changes and no undo step is recorded. Left out or null, the width is still 8 pt. The range is VectorCraft's own: it holds every width the Path Eraser tool sends across the view zoom and UI Scaling limits, and its top matches the Eraser's largest Size. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/cut.rs | 8 ++++---- crates/engine/src/tests/draw2.rs | 24 ++++++++++++++++++++++++ crates/ui-egui/src/i18n/tests.rs | 7 ++++--- docs/mcp.md | 4 ++++ docs/target-app-parity.md | 1 + 6 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 050e477295..49c7b525a3 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8; from 0.001 to 1000)} erase the parts of selected paths under the drag → {ids}. A width outside 0.001 to 1000 is refused with an error, and nothing changes", has_selection, erase_segments ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index bb75329765..ac0fc846c1 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -518,13 +518,13 @@ fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec)>) Ok(ids_json(&ids)) } +/// The Path Eraser's band width, in points (VectorCraft's own range). +const PATH_ERASER_WIDTHS: (f64, f64) = (0.001, 1000.0); + pub(super) fn erase_segments(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseSegments"; let pts = points_param(p, "points", C)?; - let w = number_or(p, "width", 8.0, C)?; - if !(w.is_finite() && w > 0.0) { - return Err(bad(C, "width must be positive")); - } + let w = ranged(p, "width", 8.0, PATH_ERASER_WIDTHS, C)?; let st = s.doc()?; let mut plan = vec![]; for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, w)) { diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 8674750c19..8cc1bfe3ad 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3059,6 +3059,30 @@ fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() { } } +/// `path.eraseSegments` refuses a `width` outside 0.001 to 1000 pt, and nothing changes. The ends of +/// the range and null still erase. +#[test] +fn path_eraser_width_outside_its_range_is_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let drag = json!({"points": [[150, 90], [150, 110]]}); + for x in [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, "path.eraseSegments", &with(&drag, json!({"width": x})), "`width` must be from 0.001 to 1000"); + assert_eq!(s.doc().unwrap().selection, sel, "width {x} changed the selection"); + } + for x in [json!(0.001), json!(1000), json!(null)] { + let before = s.doc().unwrap().doc.clone(); + let undo = undo_steps(&s); + s.execute("path.eraseSegments", &with(&drag, json!({"width": x}))).unwrap_or_else(|e| panic!("width {x}: {e}")); + assert!(s.doc().unwrap().doc != before, "width {x} erased nothing"); + assert_eq!(undo_steps(&s), undo + 1, "width {x}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + } +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 33a6584e3b..5738e4c0ee 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2851,9 +2851,9 @@ fn three_d_refusals_are_translated_in_every_complete_catalog() { assert!(missing.is_empty(), "{} 3D messages have no @msg row:\n{}", missing.len(), missing.join("\n")); } -/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`) and the Scissors' (`path.split` -/// `t`) show in every complete-message language with the key and the range numbers as given; the -/// error the command returns stays English. +/// The Eraser's range refusals (`path.eraseRegion` `angle` and `roundness`), the Path Eraser's +/// (`path.eraseSegments` `width`) and the Scissors' (`path.split` `t`) show in every complete-message +/// language with the key and the range numbers as given; the error the command returns stays English. #[test] fn eraser_and_scissors_range_refusals_translate_with_their_values() { use serde_json::json; @@ -2863,6 +2863,7 @@ fn eraser_and_scissors_range_refusals_translate_with_their_values() { let refusals = [ ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "angle": 200}), "`angle`", ["-180", "180"]), ("path.eraseRegion", json!({"points": [[10, 10], [60, 10]], "roundness": 0}), "`roundness`", ["1", "100"]), + ("path.eraseSegments", json!({"points": [[30, 0], [30, 70]], "width": 2000}), "`width`", ["0.001", "1000"]), ("path.split", json!({"id": id, "segment": 0, "t": 1.5}), "`t`", ["0", "1"]), ]; for (cmd, p, key, numbers) in &refusals { diff --git a/docs/mcp.md b/docs/mcp.md index 74ea95519a..3f3c701269 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5959,6 +5959,10 @@ with `` `t` must be from 0 to 1 ``, with `segment` or with `anchor`. The documen recorded. Left out or null, `angle` is 0° and `roundness` is 100%; left out, `t` is 0.5. The Eraser's ranges are VectorCraft's own values. +`path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with +`` `width` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is recorded. +Left out or null, `width` is 8 pt. The range is VectorCraft's own value. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc4082ad68..26bdf4e546 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1204,6 +1204,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. + `path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with an error and leaves the document unchanged; left out or null, the width is 8 pt. The help page gives the Path Eraser no width option, so the range is VectorCraft's own value. Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. From f7ee7183b33f5569c1b0b9573a4630d510d3824c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:40:53 -0800 Subject: [PATCH 081/138] i18n: drop the Danish and French rows the merge of main doubled The merge of main brought Danish rows for the five literal-brace messages, so the branch's own Danish rows became duplicates, and it brought back the French placeholder rows for "each font must be" and "give fonts" next to their exact rows. Each message now has one row. --- crates/ui-egui/src/i18n/da.tsv | 5 ----- crates/ui-egui/src/i18n/fr.tsv | 2 -- 2 files changed, 7 deletions(-) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index bb1bc084b4..e199db224c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4259,7 +4259,6 @@ digits Malayalam Malayalam Composite Fonts Sammensatte skrifttyper Export Composite Fonts Eksportér sammensatte skrifttyper Import Composite Fonts Importér sammensatte skrifttyper -@msg each font must be {{name, parts}} hver skrifttype skal være {{name, parts}} @msg unknown key `{k}`; a font takes name and parts ukendt nøgle `{k}`; en skrifttype tager name og parts @msg each font needs a name hver skrifttype skal have et navn @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` kan ikke være navnet på en sammensat skrifttype (1 til {COMPOSITE_NAME_MAX} tegn, ingen kontroltegn) @@ -4272,10 +4271,6 @@ digits Malayalam Malayalam @msg two composite fonts are named `{_1}` to sammensatte skrifttyper hedder `{_1}` @msg `{_1}` is the name of an installed font `{_1}` er navnet på en installeret skrifttype @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}`: {_2} er sat med `{font}`, en sammensat skrifttype -@msg give fonts: [{{name, parts}}…] angiv fonts: [{{name, parts}}…] -@msg `scope` must be "document", {{artboards: [index, …]}} or {{layers: [id, …]}} `scope` skal være "document", {{artboards: [index, …]}} eller {{layers: [id, …]}} -@msg numbers out of order in {{}} quantifier tal i forkert rækkefølge i kvantoren {{}} -@msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) malingen er ikke en friformsgradient (anvend en med paint.editGradient {{kind: "freeform"}}) @msg path is empty path er tom @msg fonts must be a list of composite fonts fonts skal være en liste med sammensatte skrifttyper @msg names must be strings names skal være strenge diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 47fdf88fb0..9dc8f9ffd6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3782,7 +3782,6 @@ digits Malayalam Malayalam Export Composite Fonts Exporter des polices composites Import Composite Fonts Importer des polices composites @msg each font must be {{name, parts}} chaque police doit être {{name, parts}} -@msg each font must be {name, parts} chaque police doit être {name, parts} @msg unknown key `{k}`; a font takes name and parts clé inconnue `{k}` ; une police prend name et parts @msg each font needs a name chaque police doit avoir un nom @msg `{raw}` can't name a composite font (1 to {COMPOSITE_NAME_MAX} characters, no control characters) `{raw}` ne peut pas nommer une police composite (1 à {COMPOSITE_NAME_MAX} caractères, sans caractères de contrôle) @@ -3796,7 +3795,6 @@ digits Malayalam Malayalam @msg `{_1}` is the name of an installed font `{_1}` est le nom d’une police installée @msg `{_1}`: {_2} is set in `{font}`, a composite font `{_1}` : {_2} utilise `{font}`, une police composite @msg give fonts: [{{name, parts}}…] indiquez fonts : [{{name, parts}}…] -@msg give fonts: [{name, parts}…] indiquez fonts : [{name, parts}…] @msg path is empty path est vide @msg fonts must be a list of composite fonts fonts doit être une liste de polices composites @msg names must be strings names doit contenir des chaînes From 934c99974238e515387ce630e4f91dc4fbce19fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:14:42 -0800 Subject: [PATCH 082/138] =?UTF-8?q?Scripts:=20File=20=E2=80=BA=20Scripts?= =?UTF-8?q?=20shows=20a=20Loading=20scripts=20row=20until=20the=20folder?= =?UTF-8?q?=20is=20first=20read?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before the first read of the Scripts folder ended, File › Scripts showed only Check Script… and Other Script…, the same as an empty folder. The menu now shows a disabled "Loading scripts…" row above them until the first listing arrives, and "The Scripts folder is still being read" once that read has taken 2 seconds. A first read that cannot start, or ends without a listing, shows "The Scripts folder cannot be read", and the next read tries again. Later reads keep the last listing in the menu while they run. The menu revision changes when the row appears, turns slow and goes away, so the macOS menu bar rebuilds with it. Both labels have rows in every catalog, and docs/mcp.md describes the row next to the other Scripts-folder notes. --- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 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/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.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/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/scripts_menu.rs | 113 +++++++++++++++-- crates/ui-egui/src/tests/scripts_menu.rs | 149 +++++++++++++++++++++-- docs/mcp.md | 4 + 31 files changed, 300 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..d35b91a08e 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2439,6 +2439,8 @@ font-technology Variable Променливи Other Library… Друга библиотека… Some scripts were not listed Някои скриптове не са изброени The Scripts folder cannot be read Папката Scripts не може да бъде прочетена + Loading scripts… Зареждане на скриптовете… + The Scripts folder is still being read Папката Scripts все още се чете Other Script… Друг скрипт… Out of Gamut Warning Предупреждение за излизане извън цветовата гама Out of Web Color Warning Предупреждение за цвят извън уеб палитрата diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..d60f6ae1ee 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -64,6 +64,8 @@ Check Script Provjeri skriptu Some scripts were not listed Neke skripte nisu navedene The Scripts folder cannot be read Folder Scripts se ne može pročitati + Loading scripts… Učitavanje skripti… + The Scripts folder is still being read Folder Scripts se još čita Other Script… Druga skripta… Document Setup… Postavke dokumenta… Switch Units Promijeni jedinice diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..b29c29b36f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5680,6 +5680,8 @@ digits Malayalam Malaiàlam @msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts Some scripts were not listed Alguns scripts no s'han llistat The Scripts folder cannot be read No es pot llegir la carpeta Scripts + Loading scripts… S’estan carregant els scripts… + The Scripts folder is still being read Encara s’està llegint la carpeta Scripts @msg the script's run is no longer available l'execució de l'script ja no està disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped una ordre fallida ha canviat passos de desfer que no s'han pogut restaurar, així que l'script s'ha aturat @msg a recovery copy could not be written, so the script was not run no s'ha pogut escriure una còpia de recuperació, per tant l'script no s'ha executat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..4fa0ce6e95 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4771,6 +4771,8 @@ imageTrace Outline Obrys @msg the script is no longer in the Scripts folder skript už není ve složce Scripts Some scripts were not listed Některé skripty nebyly uvedeny The Scripts folder cannot be read Složku Scripts nelze přečíst + Loading scripts… Načítání skriptů… + The Scripts folder is still being read Složka Scripts se stále načítá @msg the script's run is no longer available běh skriptu již není k dispozici @msg a failed command changed undo steps that could not be put back, so the script was stopped neúspěšný příkaz změnil kroky zpět, které nebylo možné obnovit, proto byl skript zastaven @msg a recovery copy could not be written, so the script was not run záložní kopii se nepodařilo zapsat, proto skript nebyl spuštěn diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..e1ce575482 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -742,6 +742,8 @@ liquify-list-end {0}, {1} {0} og {1} Check Script Kontrollér script Some scripts were not listed Nogle scripter blev ikke vist The Scripts folder cannot be read Mappen Scripts kan ikke læses + Loading scripts… Indlæser scripter… + The Scripts folder is still being read Mappen Scripts læses stadig Other Script… Andet script… Document Setup… Dokumentopsætning… Switch Units Skift enheder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..0a34804d8b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4370,6 +4370,8 @@ theme Appearance Erscheinungsbild @msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ Some scripts were not listed Einige Skripte wurden nicht aufgeführt The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden + Loading scripts… Skripte werden geladen… + The Scripts folder is still being read Der Ordner „Scripts“ wird noch gelesen @msg the script's run is no longer available der Lauf des Skripts ist nicht mehr verfügbar @msg a failed command changed undo steps that could not be put back, so the script was stopped ein fehlgeschlagener Befehl hat Rückgängig-Schritte geändert, die nicht wiederhergestellt werden konnten, daher wurde das Skript angehalten @msg a recovery copy could not be written, so the script was not run eine Wiederherstellungskopie konnte nicht geschrieben werden, daher wurde das Skript nicht ausgeführt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..af3eed6628 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2442,6 +2442,8 @@ axis Both Και τα δύο @msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts + Loading scripts… Φόρτωση σεναρίων… + The Scripts folder is still being read Ο φάκελος Scripts διαβάζεται ακόμα @msg the script's run is no longer available η εκτέλεση του σεναρίου δεν είναι πλέον διαθέσιμη @msg a failed command changed undo steps that could not be put back, so the script was stopped μια εντολή που απέτυχε άλλαξε βήματα αναίρεσης που δεν ήταν δυνατό να επαναφερθούν, οπότε το σενάριο σταμάτησε @msg a recovery copy could not be written, so the script was not run δεν ήταν δυνατή η εγγραφή αντιγράφου ανάκτησης, οπότε το σενάριο δεν εκτελέστηκε diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..a75119f35d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4452,6 +4452,8 @@ axis Both Ambos @msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts Some scripts were not listed Algunos scripts no se han incluido en la lista The Scripts folder cannot be read No se puede leer la carpeta Scripts + Loading scripts… Cargando scripts… + The Scripts folder is still being read Aún se está leyendo la carpeta Scripts @msg the script's run is no longer available la ejecución del script ya no está disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando fallido cambió pasos de deshacer que no se pudieron restaurar, así que el script se detuvo @msg a recovery copy could not be written, so the script was not run no se pudo escribir una copia de recuperación, así que el script no se ejecutó diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..9170b1ab74 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4685,6 +4685,8 @@ imageTrace Outline Ääriviiva @msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu The Scripts folder cannot be read Scripts-kansiota ei voi lukea + Loading scripts… Ladataan komentosarjoja… + The Scripts folder is still being read Scripts-kansiota luetaan vielä @msg the script's run is no longer available komentosarjan suoritus ei ole enää käytettävissä @msg a failed command changed undo steps that could not be put back, so the script was stopped epäonnistunut komento muutti kumoamisvaiheita, joita ei voitu palauttaa, joten komentosarja pysäytettiin @msg a recovery copy could not be written, so the script was not run palautuskopiota ei voitu kirjoittaa, joten komentosarjaa ei suoritettu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..da22b7b27b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4437,6 +4437,8 @@ axis Both Les deux @msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts Some scripts were not listed Certains scripts ne sont pas répertoriés The Scripts folder cannot be read Impossible de lire le dossier Scripts + Loading scripts… Chargement des scripts… + The Scripts folder is still being read Le dossier Scripts est encore en cours de lecture @msg the script's run is no longer available l’exécution du script n’est plus disponible @msg a failed command changed undo steps that could not be put back, so the script was stopped une commande en échec a modifié des étapes d’annulation qui n’ont pas pu être rétablies, le script a donc été arrêté @msg a recovery copy could not be written, so the script was not run une copie de récupération n’a pas pu être écrite, le script n’a donc pas été exécuté diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..78e23ca57f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3922,6 +3922,8 @@ Thai થાઈ The Print Tiling tool placed the pages. પ્રિન્ટ ટાઇલિંગ ટૂલે પૃષ્ઠો ગોઠવ્યાં. The Scripts folder cannot be read સ્ક્રિપ્ટ્સ ફોલ્ડર વાંચી શકાતું નથી + Loading scripts… સ્ક્રિપ્ટ લોડ થઈ રહી છે… + The Scripts folder is still being read સ્ક્રિપ્ટ્સ ફોલ્ડર હજી વંચાઈ રહ્યું છે The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. જ્યારે VECTORCRAFT_TITLEBAR એન્વાયર્નમેન્ટ વેરિએબલ સેટ હોય ત્યારે તે ટાઇટલ બાર પસંદ કરે છે. The active document changed while the screen color sampler was open સ્ક્રીન રંગ સેમ્પલર ખુલ્લું હતું ત્યારે સક્રિય દસ્તાવેજ બદલાયો The art keeps its own colors. આર્ટમાં પોતાના રંગો રહે છે. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..3b53947a27 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6799,6 +6799,8 @@ antiAlias Sharp शार्प @msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता + Loading scripts… स्क्रिप्ट लोड हो रही हैं… + The Scripts folder is still being read Scripts फ़ोल्डर अभी भी पढ़ा जा रहा है @msg the script's run is no longer available स्क्रिप्ट का रन अब उपलब्ध नहीं है @msg a failed command changed undo steps that could not be put back, so the script was stopped एक विफल कमांड ने पूर्ववत चरण बदल दिए जिन्हें वापस नहीं रखा जा सका, इसलिए स्क्रिप्ट रोक दी गई @msg a recovery copy could not be written, so the script was not run रिकवरी प्रति नहीं लिखी जा सकी, इसलिए स्क्रिप्ट नहीं चलाई गई diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..8589ce0630 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5273,6 +5273,8 @@ imageTrace Outline Körvonal @msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában Some scripts were not listed Néhány szkript nem szerepel a listában The Scripts folder cannot be read A Scripts mappa nem olvasható + Loading scripts… Szkriptek betöltése… + The Scripts folder is still being read A Scripts mappa olvasása még tart @msg the script's run is no longer available a parancsfájl futása már nem érhető el @msg a failed command changed undo steps that could not be put back, so the script was stopped egy sikertelen parancs olyan visszavonási lépéseket módosított, amelyeket nem lehetett visszaállítani, ezért a parancsfájl leállt @msg a recovery copy could not be written, so the script was not run a helyreállítási másolatot nem sikerült kiírni, ezért a parancsfájl nem futott le diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..339a2ba4c3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -57,6 +57,8 @@ Check Script Periksa skrip Some scripts were not listed Beberapa skrip tidak dicantumkan The Scripts folder cannot be read Folder Scripts tidak dapat dibaca + Loading scripts… Memuat skrip… + The Scripts folder is still being read Folder Scripts masih dibaca Other Script… Skrip lain… Document Setup… Pengaturan dokumen… Switch Units Ganti satuan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..f7343889a7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4504,6 +4504,8 @@ axis Both Entrambi @msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts Some scripts were not listed Alcuni script non sono stati elencati The Scripts folder cannot be read Impossibile leggere la cartella Scripts + Loading scripts… Caricamento degli script… + The Scripts folder is still being read La cartella Scripts è ancora in lettura @msg the script's run is no longer available l'esecuzione dello script non è più disponibile @msg a failed command changed undo steps that could not be put back, so the script was stopped un comando non riuscito ha modificato passaggi di annullamento che non è stato possibile ripristinare, quindi lo script è stato interrotto @msg a recovery copy could not be written, so the script was not run non è stato possibile scrivere una copia di recupero, quindi lo script non è stato eseguito diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..c1e0d86d80 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5272,6 +5272,8 @@ swatch Bright Violet ビビッドバイオレット @msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません Some scripts were not listed 一部のスクリプトは一覧に表示されていません The Scripts folder cannot be read Scripts フォルダーを読み込めません + Loading scripts… スクリプトを読み込み中… + The Scripts folder is still being read Scripts フォルダーをまだ読み込んでいます @msg the script's run is no longer available スクリプトの実行は利用できなくなりました @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗したコマンドが元に戻せない取り消し手順を変更したため、スクリプトを停止しました @msg a recovery copy could not be written, so the script was not run 復元用のコピーを書き込めなかったため、スクリプトは実行されませんでした diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..32b0afd8da 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7769,6 +7769,8 @@ imageTrace Outline კონტური @msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია + Loading scripts… სკრიპტების ჩატვირთვა… + The Scripts folder is still being read Scripts საქაღალდე ჯერ კიდევ იკითხება @msg the script's run is no longer available სკრიპტის გაშვება აღარ არის ხელმისაწვდომი @msg a failed command changed undo steps that could not be put back, so the script was stopped წარუმატებელმა ბრძანებამ დაბრუნების ნაბიჯები შეცვალა და მათი პირვანდელ მდგომარეობაში მოყვანა ვერ მოხერხდა, ამიტომ სკრიპტი შეჩერდა @msg a recovery copy could not be written, so the script was not run აღდგენის ასლის ჩაწერა ვერ მოხერხდა, ამიტომ სკრიპტი არ გაეშვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..fb53f5613a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5199,6 +5199,8 @@ theme Appearance 외관 @msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 + Loading scripts… 스크립트 불러오는 중… + The Scripts folder is still being read Scripts 폴더를 아직 읽는 중입니다 @msg the script's run is no longer available 스크립트 실행을 더 이상 사용할 수 없습니다 @msg a failed command changed undo steps that could not be put back, so the script was stopped 실패한 명령이 되돌릴 수 없는 실행 취소 단계를 변경하여 스크립트를 중지했습니다 @msg a recovery copy could not be written, so the script was not run 복구 사본을 쓸 수 없어 스크립트를 실행하지 않았습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..c857796331 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -611,6 +611,8 @@ liquify-list-end {0}, {1} {0} en {1} Check Script Script controleren Some scripts were not listed Sommige scripts zijn niet weergegeven The Scripts folder cannot be read De map Scripts kan niet worden gelezen + Loading scripts… Scripts laden… + The Scripts folder is still being read De map Scripts wordt nog gelezen Other Script… Ander script… Document Setup… Documentinstellingen… Switch Units Eenheden wisselen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..dcdc79366c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4595,6 +4595,8 @@ imageTrace Outline Kontur @msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts Some scripts were not listed Niektóre skrypty nie zostały wyświetlone The Scripts folder cannot be read Nie można odczytać folderu Scripts + Loading scripts… Wczytywanie skryptów… + The Scripts folder is still being read Folder Scripts jest nadal odczytywany @msg the script's run is no longer available uruchomienie skryptu nie jest już dostępne @msg a failed command changed undo steps that could not be put back, so the script was stopped nieudane polecenie zmieniło kroki cofania, których nie udało się przywrócić, więc skrypt został zatrzymany @msg a recovery copy could not be written, so the script was not run nie udało się zapisać kopii odzyskiwania, więc skrypt nie został uruchomiony diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..60f2b31227 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5501,6 +5501,8 @@ axis Both Ambos @msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts Some scripts were not listed Alguns scripts não foram listados The Scripts folder cannot be read Não é possível ler a pasta Scripts + Loading scripts… Carregando scripts… + The Scripts folder is still being read A pasta Scripts ainda está sendo lida @msg the script's run is no longer available a execução do script não está mais disponível @msg a failed command changed undo steps that could not be put back, so the script was stopped um comando que falhou alterou etapas de desfazer que não puderam ser restauradas, então o script foi interrompido @msg a recovery copy could not be written, so the script was not run não foi possível gravar uma cópia de recuperação, portanto o script não foi executado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..efd96b0cf5 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4489,6 +4489,8 @@ axis Both Оба @msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts Some scripts were not listed Некоторые сценарии не показаны The Scripts folder cannot be read Не удалось прочитать папку Scripts + Loading scripts… Загрузка сценариев… + The Scripts folder is still being read Папка Scripts ещё читается @msg the script's run is no longer available выполнение скрипта больше недоступно @msg a failed command changed undo steps that could not be put back, so the script was stopped неудавшаяся команда изменила шаги отмены, которые не удалось восстановить, поэтому скрипт остановлен @msg a recovery copy could not be written, so the script was not run не удалось записать копию для восстановления, поэтому скрипт не выполнен diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..a97010982f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4358,6 +4358,8 @@ axis Both Båda @msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts Some scripts were not listed Vissa skript visas inte i listan The Scripts folder cannot be read Mappen Scripts kan inte läsas + Loading scripts… Läser in skript… + The Scripts folder is still being read Mappen Scripts läses fortfarande @msg the script's run is no longer available skriptets körning är inte längre tillgänglig @msg a failed command changed undo steps that could not be put back, so the script was stopped ett misslyckat kommando ändrade ångrasteg som inte kunde återställas, så skriptet stoppades @msg a recovery copy could not be written, so the script was not run en återställningskopia kunde inte skrivas, så skriptet kördes inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..8a5faa0a9b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4214,6 +4214,8 @@ axis Both Her İkisi @msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil Some scripts were not listed Bazı komut dosyaları listelenmedi The Scripts folder cannot be read Scripts klasörü okunamıyor + Loading scripts… Betikler yükleniyor… + The Scripts folder is still being read Scripts klasörü hâlâ okunuyor @msg the script's run is no longer available betiğin çalıştırması artık kullanılamıyor @msg a failed command changed undo steps that could not be put back, so the script was stopped başarısız bir komut geri yüklenemeyen geri alma adımlarını değiştirdi, bu yüzden betik durduruldu @msg a recovery copy could not be written, so the script was not run kurtarma kopyası yazılamadı, bu nedenle betik çalıştırılmadı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..1c950c387f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4488,6 +4488,8 @@ axis Both Обидві @msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts Some scripts were not listed Деякі сценарії не показано The Scripts folder cannot be read Не вдалося прочитати папку Scripts + Loading scripts… Завантаження сценаріїв… + The Scripts folder is still being read Папка Scripts ще читається @msg the script's run is no longer available виконання скрипта більше не доступне @msg a failed command changed undo steps that could not be put back, so the script was stopped невдала команда змінила кроки скасування, які не вдалося відновити, тому скрипт зупинено @msg a recovery copy could not be written, so the script was not run не вдалося записати копію для відновлення, тому скрипт не виконано diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..03648b4e7b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4929,6 +4929,8 @@ theme Appearance Giao diện @msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts Some scripts were not listed Một số tập lệnh không được liệt kê The Scripts folder cannot be read Không thể đọc thư mục Scripts + Loading scripts… Đang tải tập lệnh… + The Scripts folder is still being read Thư mục Scripts vẫn đang được đọc @msg the script's run is no longer available lần chạy tập lệnh không còn khả dụng @msg a failed command changed undo steps that could not be put back, so the script was stopped một lệnh thất bại đã thay đổi các bước hoàn tác không thể khôi phục, nên tập lệnh đã bị dừng @msg a recovery copy could not be written, so the script was not run không thể ghi bản sao khôi phục nên tập lệnh không được chạy diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..faca08b290 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4950,6 +4950,8 @@ imageTrace Outline 轮廓 @msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 Some scripts were not listed 部分脚本未列出 The Scripts folder cannot be read 无法读取 Scripts 文件夹 + Loading scripts… 正在载入脚本… + The Scripts folder is still being read 仍在读取 Scripts 文件夹 @msg the script's run is no longer available 脚本运行已不可用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失败的命令更改了无法恢复的撤销步骤,因此脚本已停止 @msg a recovery copy could not be written, so the script was not run 无法写入恢复副本,因此未运行脚本 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..835636937a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2582,6 +2582,8 @@ file-filter Templates 範本 @msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 Some scripts were not listed 部分指令碼未列出 The Scripts folder cannot be read 無法讀取 Scripts 資料夾 + Loading scripts… 正在載入指令碼… + The Scripts folder is still being read 仍在讀取 Scripts 資料夾 @msg the script's run is no longer available 指令碼執行已無法使用 @msg a failed command changed undo steps that could not be put back, so the script was stopped 失敗的命令變更了無法還原的復原步驟,因此指令碼已停止 @msg a recovery copy could not be written, so the script was not run 無法寫入復原副本,因此未執行指令碼 diff --git a/crates/ui-egui/src/scripts_menu.rs b/crates/ui-egui/src/scripts_menu.rs index c951aac8cb..1afaf11d34 100644 --- a/crates/ui-egui/src/scripts_menu.rs +++ b/crates/ui-egui/src/scripts_menu.rs @@ -7,6 +7,10 @@ //! active one, and each time the File menu of the window's menu bar opens ([`refresh`]). The menus show the last finished //! listing ([`items`]), so a script added to the folder is listed without a restart. //! +//! Until the first read ends the menu shows [`LOADING`], and [`SLOW`] once that read has taken +//! [`SLOW_SECS`]; a first read that cannot start or ends without a listing shows [`UNREADABLE`], +//! and the next read tries again. +//! //! `ui.runInstalledScript {path}` runs a listed script (`script.run`) without the warning Other //! Script… shows: the file was put in the folder to be run from the menu. The path is one a //! listing gave; a file that is no longer a plain script under the folder is not run. @@ -28,8 +32,14 @@ pub const COMMAND: &str = "ui.runInstalledScript"; pub const TRUNCATED: &str = "Some scripts were not listed"; /// The menu's note when the folder is there and cannot be read. pub const UNREADABLE: &str = "The Scripts folder cannot be read"; +/// The menu's note while the first read is under way. +pub const LOADING: &str = "Loading scripts…"; +/// The menu's note once the first read has taken [`SLOW_SECS`]. +pub const SLOW: &str = "The Scripts folder is still being read"; /// The notes, for the catalogs ([`crate::menus::menu_strings`]). -pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE]; +pub const LABELS: &[&str] = &[TRUNCATED, UNREADABLE, LOADING, SLOW]; +/// How long the first read runs before the menu shows [`SLOW`]. +pub const SLOW_SECS: f64 = 2.0; #[derive(Default)] struct State { @@ -45,6 +55,43 @@ struct State { started: bool, /// The window was the active one at the last [`poll`]. focused: bool, + /// A listing has been taken in. + loaded: bool, + /// When the first read started ([`crate::clock::now_secs`]), while it is under way. + first_read: Option, + /// The first read has taken [`SLOW_SECS`]. + slow: bool, + /// No listing yet, and the last read could not start or ended without one. + failed: bool, +} + +impl State { + /// The note in place of a listing before the first one. + fn first_read_note(&self) -> Option<&'static str> { + if self.loaded { + return None; + } + if self.reading.is_some() { + return Some(if self.slow { SLOW } else { LOADING }); + } + self.failed.then_some(UNREADABLE) + } + + /// No listing yet, and the read under way ended without one or could not start. + fn first_read_failed(&mut self) { + if !self.loaded { + (self.first_read, self.slow, self.failed) = (None, false, true); + self.revision += 1; + } + } + + /// Show [`SLOW`] once the first read has run [`SLOW_SECS`] by `now`. + fn mark_slow(&mut self, now: f64) { + if !self.loaded && !self.slow && self.reading.is_some() && self.first_read.is_some_and(|t| now - t >= SLOW_SECS) { + self.slow = true; + self.revision += 1; + } + } } /// The listing the menus show. One per process in the app; one per thread in unit tests, which run @@ -92,7 +139,8 @@ pub(crate) fn intern(s: &str) -> Option<&'static str> { Some(v) } -/// Changes whenever the menus' listing changes (the macOS menu bar follows it). +/// Changes whenever the menus' listing or the note before the first listing changes (the macOS +/// menu bar follows it). pub fn revision() -> u64 { state().revision } @@ -108,18 +156,28 @@ pub fn refresh(app: &VectorcraftApp, ctx: Option<&egui::Context>) { return; } let (tx, rx) = std::sync::mpsc::channel(); - let ctx = ctx.cloned(); + let worker_ctx = ctx.cloned(); let spawned = std::thread::Builder::new().name("vectorcraft-scripts".into()).spawn(move || { // The app's own folder, read for the person at the keyboard. let listing = vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&root)); if tx.send(listing).is_ok() - && let Some(ctx) = ctx + && let Some(ctx) = worker_ctx { ctx.request_repaint(); } }); - if spawned.is_ok() { - state.reading = Some(rx); + if spawned.is_err() { + state.first_read_failed(); + return; + } + state.reading = Some(rx); + if !state.loaded && state.first_read.is_none() { + // The menus show the loading note, and a frame comes when it is due to change to SLOW. + state.first_read = Some(crate::clock::now_secs()); + state.revision += 1; + if let Some(ctx) = ctx { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SLOW_SECS)); + } } } @@ -137,6 +195,7 @@ pub fn poll(app: &VectorcraftApp, ctx: &egui::Context) { refresh(app, Some(ctx)); } take(false); + state().mark_slow(crate::clock::now_secs()); let again = { let mut state = state(); let again = state.pending && state.reading.is_none(); @@ -157,14 +216,22 @@ fn take(wait: bool) { let listing = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; match listing { Ok(listing) => { - if *state.listing != listing { + let changed = *state.listing != listing; + if changed { state.listing = Arc::new(listing); + } + // The first listing also takes the place of the loading note. + if changed || !state.loaded { state.revision += 1; } + (state.loaded, state.first_read, state.slow, state.failed) = (true, None, false, false); state.reading = None; } Err(TryRecvError::Empty) => {} - Err(TryRecvError::Disconnected) => state.reading = None, + Err(TryRecvError::Disconnected) => { + state.reading = None; + state.first_read_failed(); + } } } @@ -174,6 +241,27 @@ pub(crate) fn wait() { take(true); } +/// The read under way ends without a listing, as when its thread stops early. +#[cfg(test)] +pub(crate) fn lose_read() { + let mut state = state(); + if state.reading.is_some() { + state.reading = Some(std::sync::mpsc::channel::().1); + } +} + +/// When the first read started, while it is under way. +#[cfg(test)] +pub(crate) fn first_read_started() -> Option { + state().first_read +} + +/// What [`poll`] does about a slow first read, at `now` ([`crate::clock::now_secs`]). +#[cfg(test)] +pub(crate) fn check_slow(now: f64) { + state().mark_slow(now); +} + /// Wait for the read under way to end and leave its listing to be taken in, so the read is under /// way until the next [`poll`]. #[cfg(test)] @@ -188,7 +276,8 @@ pub(crate) fn end_untaken() { } /// File › Scripts' items: the listed scripts and subfolders, a note when some may be missing or -/// the folder cannot be read, then Check Script… and Other Script…. +/// the folder cannot be read, or one before the first listing, then Check Script… and Other +/// Script…. pub fn items() -> Vec { // A row whose name is past [`MAX_NAMES`] is left out (`dropped`). fn level(entries: &[Entry], dropped: &mut bool) -> Vec { @@ -208,7 +297,10 @@ pub fn items() -> Vec { } items } - let listing = state().listing.clone(); + let (listing, note) = { + let state = state(); + (state.listing.clone(), state.first_read_note()) + }; let mut dropped = false; let mut items = level(&listing.entries, &mut dropped); if listing.truncated || dropped { @@ -217,6 +309,7 @@ pub fn items() -> Vec { if listing.unreadable { items.push(Item::Header(UNREADABLE)); } + items.extend(note.map(Item::Header)); if !items.is_empty() { items.push(Item::Sep); } diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 7cfa5fe2b5..93f0117eb8 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -80,19 +80,22 @@ fn finish(app: &mut VectorcraftApp) { const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); vc.run('shape.rectangle', {x:20,y:0,width:10,height:10});"; +/// The items File › Scripts always ends with. +const FIXED: &str = "Check Script…, Other Script…"; + #[test] fn the_folders_scripts_are_listed_above_check_script_and_other_script() { let dir = folder("listed"); let app = app(&dir); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "before the first listing"); + assert_eq!(shape(&scripts()), FIXED, "before the first read"); read(&app); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…", "an empty folder"); + assert_eq!(shape(&scripts()), FIXED, "an empty folder"); let draw = write(&dir, "Draw Two.jsx", DRAW); write(&dir, "Export/All Artboards.js", ""); write(&dir, "notes.txt", ""); read(&app); let items = scripts(); - assert_eq!(shape(&items), "Draw Two, Export/[All Artboards], -, Check Script…, Other Script…"); + assert_eq!(shape(&items), format!("Draw Two, Export/[All Artboards], -, {FIXED}")); assert!(matches!(&items[0], Item::Cmd(_, scripts_menu::COMMAND, p) if *p == json!({ "path": draw })), "{:?}", items[0]); // A script added to the folder is listed by the next read, with no restart. write(&dir, "Added.js", ""); @@ -201,7 +204,7 @@ fn a_script_that_left_the_folder_is_not_run_and_the_folder_is_read_again() { assert_eq!(e, "the script is no longer in the Scripts folder"); assert!(!app.session.script_running()); scripts_menu::wait(); - assert_eq!(shape(&scripts()), "kept, -, Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), format!("kept, -, {FIXED}")); // A file outside the folder is not one of its scripts, and a call needs a path. let outside = dir.join("outside.js"); std::fs::write(&outside, DRAW).unwrap(); @@ -246,12 +249,12 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() { read(&app); let items = scripts(); assert_eq!(items.len(), vectorcraft_engine::script::folder::MAX_SCRIPTS + 4); - assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + assert_eq!(shape(&items[items.len() - 4..]), format!("({}), -, {FIXED}", scripts_menu::TRUNCATED)); // A file where the folder should be. std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); std::fs::write(dir.join("Scripts"), "").unwrap(); read(&app); - assert_eq!(shape(&scripts()), format!("({}), -, Check Script…, Other Script…", scripts_menu::UNREADABLE)); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); let _ = std::fs::remove_dir_all(dir); } @@ -284,7 +287,7 @@ fn names_past_the_session_limit_are_left_out_with_the_note() { let app = app(&dir); write(&dir, "Kept.js", ""); read(&app); - assert_eq!(shape(&scripts()), "Kept, -, Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), format!("Kept, -, {FIXED}")); // Names other listings showed fill what one session keeps. for n in 0..scripts_menu::MAX_NAMES { if scripts_menu::intern(&format!("renamed {n}")).is_none() { @@ -294,7 +297,7 @@ fn names_past_the_session_limit_are_left_out_with_the_note() { write(&dir, "New.js", ""); write(&dir, "Folder/Inside.js", ""); read(&app); - assert_eq!(shape(&scripts()), format!("Kept, ({}), -, Check Script…, Other Script…", scripts_menu::TRUNCATED)); + assert_eq!(shape(&scripts()), format!("Kept, ({}), -, {FIXED}", scripts_menu::TRUNCATED)); let _ = std::fs::remove_dir_all(dir); } @@ -305,7 +308,8 @@ fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { let path = write(&dir, "Export/All Artboards.js", ""); let before = scripts_menu::revision(); read(&app); - assert_eq!(scripts_menu::revision(), before + 1); + // The loading note showed, then the listing took its place. + assert_eq!(scripts_menu::revision(), before + 2); let bar = native_menu::from_tree(&app, &menus::menu_tree()); let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); let scripts = file.children.iter().find_map(|n| match n { @@ -321,10 +325,10 @@ fn the_macos_menu_bar_lists_the_same_scripts_and_follows_a_new_listing() { assert!(script.enabled && script.shortcut.is_none()); // A read that finds the same scripts changes nothing the menu bar would rebuild for. read(&app); - assert_eq!(scripts_menu::revision(), before + 1); + assert_eq!(scripts_menu::revision(), before + 2); write(&dir, "More.jsx", ""); read(&app); - assert_eq!(scripts_menu::revision(), before + 2); + assert_eq!(scripts_menu::revision(), before + 3); let _ = std::fs::remove_dir_all(dir); } @@ -424,9 +428,130 @@ fn a_read_asked_for_during_another_runs_when_that_one_ends() { fn an_app_without_a_scripts_folder_keeps_the_two_fixed_items() { let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); read(&app); - assert_eq!(shape(&scripts()), "Check Script…, Other Script…"); + assert_eq!(shape(&scripts()), FIXED, "no loading note: there is no folder to read"); let e = menus::run_ui_command(&mut app, scripts_menu::COMMAND, &json!({ "path": "draw.js" })).unwrap().unwrap_err(); assert_eq!(e, "the script is no longer in the Scripts folder"); assert_eq!(menus::UI_COMMANDS.iter().filter(|c| c.0 == scripts_menu::COMMAND).count(), 1); let _: Value = app.run("script.listInstalled", json!({})).unwrap(); } + +/// File › Scripts in the macOS menu bar as text, as [`shape`] gives the in-window menu. +fn native_shape(app: &VectorcraftApp) -> String { + fn one(nodes: &[Node]) -> String { + let node = |n: &Node| match n { + Node::Item(it) if it.command.is_none() => format!("({})", it.label), + Node::Item(it) => it.label.clone(), + Node::Header(label) => format!("({label})"), + Node::Submenu { label, children } => format!("{label}/[{}]", one(children)), + Node::Separator => "-".to_string(), + Node::Standard(s) => format!("{s:?}"), + }; + nodes.iter().map(node).collect::>().join(", ") + } + let bar = native_menu::from_tree(app, &menus::menu_tree()); + let file = bar.menus.iter().find(|m| m.title == "File").unwrap(); + let scripts = file.children.iter().find_map(|n| match n { + Node::Submenu { label, children } if label == "Scripts" => Some(children), + _ => None, + }); + one(scripts.unwrap()) +} + +#[test] +fn the_first_read_shows_a_loading_note_until_its_listing_comes() { + let dir = folder("loading"); + let app = app(&dir); + write(&dir, "first.js", ""); + let before = scripts_menu::revision(); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + let loading = format!("({}), -, {FIXED}", scripts_menu::LOADING); + assert_eq!(shape(&scripts()), loading); + assert_eq!(native_shape(&app), loading, "the macOS menu bar shows the same note"); + assert_eq!(scripts_menu::revision(), before + 1, "the macOS menu bar rebuilds for the note"); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(native_shape(&app), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::revision(), before + 2); + // A later read keeps the listing, with no note, while it is under way. + write(&dir, "second.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::revision(), before + 2); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, second, -, {FIXED}")); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn an_empty_or_unreadable_first_listing_takes_the_place_of_the_loading_note() { + let dir = folder("loading-empty"); + let app = app(&dir); + let before = scripts_menu::revision(); + read(&app); + assert_eq!(shape(&scripts()), FIXED); + assert_eq!(scripts_menu::revision(), before + 2, "the note went, though the listing is the empty one it started from"); + let _ = std::fs::remove_dir_all(dir); + // A thread of its own has a menu that has not listed yet. + let dir = folder("loading-unreadable"); + std::fs::remove_dir_all(dir.join("Scripts")).unwrap(); + std::fs::write(dir.join("Scripts"), "").unwrap(); + let there = dir.clone(); + std::thread::spawn(move || { + let app = self::app(&there); + read(&app); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + }) + .join() + .unwrap(); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_slow_first_read_says_so_until_its_listing_comes() { + let dir = folder("slow"); + let app = app(&dir); + write(&dir, "first.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + let started = scripts_menu::first_read_started().unwrap(); + let before = scripts_menu::revision(); + scripts_menu::check_slow(started + scripts_menu::SLOW_SECS / 2.0); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + assert_eq!(scripts_menu::revision(), before); + scripts_menu::check_slow(started + scripts_menu::SLOW_SECS); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::SLOW)); + assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::SLOW)); + assert_eq!(scripts_menu::revision(), before + 1); + // Asking again while it reads starts no second read. + scripts_menu::refresh(&app, None); + scripts_menu::check_slow(started + 10.0 * scripts_menu::SLOW_SECS); + assert_eq!(scripts_menu::revision(), before + 1); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + assert_eq!(scripts_menu::first_read_started(), None); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_first_read_that_ends_without_a_listing_says_the_folder_cannot_be_read_and_the_next_read_tries_again() { + let dir = folder("lost"); + let app = app(&dir); + write(&dir, "first.js", ""); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + scripts_menu::lose_read(); + let before = scripts_menu::revision(); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE), "no loading note left behind"); + assert_eq!(native_shape(&app), format!("({}), -, {FIXED}", scripts_menu::UNREADABLE)); + assert_eq!(scripts_menu::revision(), before + 1); + assert_eq!(scripts_menu::first_read_started(), None); + scripts_menu::refresh(&app, None); + scripts_menu::end_untaken(); + assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::LOADING)); + scripts_menu::wait(); + assert_eq!(shape(&scripts()), format!("first, -, {FIXED}")); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..10f87fbb98 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2730,6 +2730,10 @@ The rest of this section is VectorCraft's own rules: read finds new names after the menus have shown 16,384 different script and folder names since VectorCraft started. When the folder is there and cannot be read, the menu shows `The Scripts folder cannot be read`. +- Until the first read ends, the menu shows `Loading scripts…` in place of the listing, and + `The Scripts folder is still being read` once that read has taken 2 seconds. A first read that cannot start, or + ends without a listing, shows `The Scripts folder cannot be read`, and the next read tries again. Later reads keep + the last listing in the menu while they run. - A listed file is checked again when it is chosen. A file that is gone, is no longer a `.js` or `.jsx` file under the folder, or is or lies behind a link ends with `the script is no longer in the Scripts folder`, and nothing runs. The file is read once for that check, and the text that read checked is the text that runs; its `#include` lines From 8bc2d29d45f858bcdc7a073acecaad6e37711eb7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:21:37 -0800 Subject: [PATCH 083/138] Recolor Artwork: Save Changes keeps colors added and removed on the Edit tab Save Changes now gives the group the same colors OK would: a color removed with the Remove Color tool removes its swatch, and a color added with the Add Color tool joins the group after its other colors, also when the art holds colors of the group. `swatch.editGroup` takes `null` in `colors` to remove the swatch at that place. After the save, the rows follow the saved group, so a later edit or OK does not remove or add a color a second time. --- crates/engine/src/cmd/swatch.rs | 21 ++- crates/engine/src/tests/swatchcmds.rs | 14 ++ crates/ui-egui/src/dialogs/recolor.rs | 183 ++++++++++++++++++++++++-- docs/mcp.md | 7 +- 4 files changed, 206 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 6f2137d6d6..088c7d74c5 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Edit Color Group", ["Window", "Swatches"], None, - "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", + "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", has_doc, swatch_edit_group ), @@ -1317,29 +1317,36 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option Result { const C: &str = "swatch.editGroup"; let group = str_param(p, "group").ok_or_else(|| bad(C, "missing `group`"))?; - let colors: Vec = p + // A null removes the swatch at that place. + let colors: Vec> = p .get("colors") .and_then(Value::as_array) .ok_or_else(|| bad(C, "missing `colors`"))? .iter() - .map(|v| color_value(v).ok_or_else(|| bad(C, format!("bad colour {v}")))) + .map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) }) .collect::>()?; super::paint::check_keep_model(p, C)?; // A color its swatch already has keeps its model. The others take the document's. let old: Vec> = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default(); - let colors: Vec = - colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect(); + let mut colors: Vec> = colors + .into_iter() + .enumerate() + .map(|(i, c)| c.map(|c| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) })) + .collect(); + // A null past the group's swatches removes nothing. + while colors.len() > old.len() && colors.last() == Some(&None) { + colors.pop(); + } let rename = str_param(p, "rename"); // The group's own colors, in order, under its own name change nothing: no undo step. if let Some(g) = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group) && rename.map(str::trim).is_none_or(|n| n.is_empty() || n == group) && old.len() == colors.len() - && old.iter().zip(&colors).all(|(o, c)| *o == Some(*c)) + && old.iter().zip(&colors).all(|(o, c)| c.is_some() && o == c) { return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::>(), "relinked": 0})); } - let colors: Vec> = colors.into_iter().map(Some).collect(); let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?; e.defaults(s)?; Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked})) diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index 88276a9e31..03ab5fdbe2 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -445,6 +445,20 @@ fn edit_color_group_with_its_own_colors_records_no_undo_step() { assert_eq!(undo_len(&s), undo + 2, "a new name is a step"); } +#[test] +fn edit_color_group_with_a_null_removes_that_swatch() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})); + let undo = undo_len(&s); + let r = run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", null, "#0000ff"]})); + assert_eq!(r["swatches"], json!(["R=255 G=0 B=0", "R=0 G=0 B=255"])); + assert_eq!(names(&s, Some("Mine")), ["R=255 G=0 B=0", "R=0 G=0 B=255"]); + assert_eq!(undo_len(&s), undo + 1, "a removed swatch is a step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": ["#ff0000", "#0000ff", null]})); + assert_eq!(undo_len(&s), undo + 1, "a null past the swatches removes nothing and records no step"); + assert!(s.execute("swatch.editGroup", &json!({"group": "Mine", "colors": ["#ff0000", "nope"]})).is_err()); +} + #[test] fn unused_leaves_out_linked_colours_gradients_and_patterns_in_use() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index cd3c41206d..42e42eb768 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -570,16 +570,18 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res Some("save") => { let rs = rows(d); let p = apply_params(d); - // With art, the group's colors no row took follow, adjusted and snapped as OK gives them; a - // row made with New Row that holds no current colors gives the group no color. - let filled: Vec<&Value> = rs.iter().filter(|r| !r["from"].as_array().is_some_and(Vec::is_empty)).collect(); + // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, + // then the colors added on the Edit tab; a row made with New Row that holds no current + // colors gives the group no color. + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); let rest: Vec = p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); - let mut colors = group_colors(app, d, filled.into_iter().chain(&rest)); + let mut colors: Vec = filled.iter().filter_map(|r| saved_color(app, d, r)).chain(group_colors(app, d, rest.iter())).collect(); cancel_preview(app, d); // With art in a color of the group, the group keeps its swatch order: a swatch whose color // a row lists takes that row's new color (its own color when the row is excluded), so the // art linked to it takes the color its row shows, and every other swatch keeps its color. + // The colors added on the Edit tab follow. let own: Vec = doc_groups(app) .into_iter() .find(|(n, _)| group.as_deref() == Some(n.as_str())) @@ -587,12 +589,14 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res .unwrap_or_default(); let row_of = |k: &Value| row_listing(&rs, k); if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { + let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null()); colors = own .iter() .map(|k| match row_of(k) { - Some(r) if !excluded(r) => group_colors(app, d, std::iter::once(r)).into_iter().next().unwrap_or_else(|| k.clone()), + Some(r) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), _ => k.clone(), }) + .chain(group_colors(app, d, added)) .collect(); } let before = art_colors(app); @@ -601,7 +605,38 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res d.fields.insert("group".into(), name.clone()); d.fields.insert(GROUP_LOADED.into(), name.clone()); d.fields.insert("groupName".into(), name); - if d.bool("__art") { + // The rows follow the saved group, so a later edit or OK does not remove or add a color + // again: a removed color's row goes (its art keeps its colors). Without art, a color added + // on the Edit tab becomes a row of its own color, after the rows of the group's other + // colors; with art, its row goes and the color is one of the group's colors no row takes. + let art = d.bool("__art"); + let joins = |r: &Value| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null(); + let gone: Vec = + rows(d).iter().filter(|r| color_removed(r)).flat_map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect(); + let (mut joined, mut rs): (Vec, Vec) = rows(d).into_iter().filter(|r| !color_removed(r)).partition(|r| joins(r)); + if art { + joined.clear(); + } + for r in &mut joined { + r["from"] = json!([r["to"].clone()]); + if let Some(o) = r.as_object_mut() { + o.remove("added"); + } + } + // The save added them after the group's other colors, whatever the rows' order. + rs.extend(joined); + if rs != rows(d) { + d.fields.insert("__sel".into(), json!([])); + } + d.fields.insert("rows".into(), Value::Array(rs)); + if art { + // The group's colors no row takes are those of the saved group. + let saved: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| Some(n.as_str()) == r["name"].as_str()) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + d.fields.insert("__assign".into(), Value::Array(saved)); // The saved group holds the Global Adjust: the rows' new colors take it, and it goes // back to 0%, so neither the preview nor OK applies it again. bake_adjust(app, d); @@ -609,7 +644,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res if art_colors(app) == before { mark_saved(app, d); } else { - reread_rows(app, d, &rs, &before); + reread_rows(app, d, &rs, &before, &gone); } } Ok(()) @@ -624,14 +659,21 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res } } +/// The color Save Changes gives the group's swatch for `row`: `null` when the row's color was +/// removed, which removes the swatch as OK does, otherwise its new color as OK gives it. +fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { + if color_removed(row) { Some(Value::Null) } else { group_colors(app, d, std::iter::once(row)).into_iter().next() } +} + /// After Save Changes recolored the art linked to the group's global swatches, read the rows from /// the art again. A row that lists a color the save gave the art (a paint of a selected object /// that differs from `before`, [`art_colors`] before the save) is excluded with its first color, /// so the art keeps it, also when other art has that color: `recolor.apply` recolors every use /// of a color alike, so the row cannot keep that art's earlier new color without undoing the save. Any other row whose first current color one of the `old` rows listed takes /// that row's new color and exclusion (art the save left as it was keeps its recolor); the rest -/// are excluded too. -fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec]) { +/// are excluded too. A row that lists only `gone` colors (those of swatches the save removed) is +/// left out: its art keeps its colors, and the row gives the group no color. +fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec], gone: &[Value]) { let given: Vec = art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); d.fields.insert(THEME_PICKS.into(), json!([])); @@ -652,6 +694,7 @@ fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: } } } + rs.retain(|r| r["from"].as_array().is_none_or(|f| f.is_empty() || !f.iter().all(|c| gone.contains(c)))); d.fields.insert("rows".into(), Value::Array(rs)); mark_saved(app, d); } @@ -979,6 +1022,12 @@ fn no_current(row: &Value) -> bool { row["from"].as_array().is_none_or(Vec::is_empty) } +/// Whether `row` holds current colors and its new color was removed (`to: null`) and isn't excluded: +/// its swatch in the color group is removed. +fn color_removed(row: &Value) -> bool { + !excluded(row) && !no_current(row) && row["to"].is_null() +} + /// Whether `row` is a color added on the Edit tab (`added`), which joins the color group. fn is_added(row: &Value) -> bool { row["added"].as_bool().unwrap_or(false) @@ -3506,6 +3555,94 @@ mod tests { assert_eq!(fill_hex(&app, red), "#ff0000", "art linked to a swatch no row lists is left as it is"); } + /// Save Changes with art in colors of the group keeps the Edit tab's changes: a removed color's + /// swatch is removed, and a color added on the Edit tab joins the group after the others. + #[test] + fn saving_a_group_keeps_added_and_removed_colors() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let yellow = square(&mut app, 70.0, "#ffff00"); + app.run("select.set", json!({"ids": [red, blue, yellow]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + let order = group_hex(&app, "Linked").unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#0000ff") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 0 128 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let mut want: Vec = order.into_iter().filter(|h| h != "#0000ff").collect(); + want.push("#008000".into()); + assert_eq!(group_hex(&app, "Linked"), Some(want.clone()), "the removed swatch goes and the added color follows the others"); + assert_eq!(fill_hex(&app, blue), "#0000ff", "art linked to a removed swatch keeps its color"); + let rs = super::rows(app.ui.dialog.as_ref().unwrap()); + assert!(rs.iter().all(|r| !r["to"].is_null() && !is_added(r)), "the rows follow the saved group: {rs:?}"); + let assign = app.ui.dialog.as_ref().unwrap().fields["__assign"].clone(); + let assign: Vec = assign.as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + assert_eq!(Some(assign), group_hex(&app, "Linked"), "a later edit gives the group no removed swatch back"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(want), "OK removes and adds nothing more"); + } + + /// Save Changes that recolors linked art reads the rows from the art again; a color added on the + /// Edit tab stays one of the group's colors and a removed one does not come back, so OK after a + /// further edit keeps them as saved. + #[test] + fn saving_a_group_that_reads_the_rows_again_keeps_an_added_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let red = square(&mut app, 10.0, "#ff0000"); + let blue = square(&mut app, 40.0, "#0000ff"); + let lime = square(&mut app, 70.0, "#00ff00"); + app.run("select.set", json!({"ids": [red, blue, lime]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + let to = match from_colors(r).first().map(|c| c.to_hex()).as_deref() { + Some("#ff0000") => json!("rgb 0 128 0"), + Some("#00ff00") => Value::Null, + _ => r["from"][0].clone(), + }; + r["to"] = to; + } + rs.push(json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(fill_hex(&app, red), "#008000", "the save recolored the linked art"); + assert_eq!(fill_hex(&app, lime), "#00ff00", "art linked to the removed swatch keeps its color"); + let group = group_hex(&app, "Linked").unwrap(); + assert!(group.contains(&"#ffff00".to_string()) && !group.contains(&"#00ff00".to_string()), "{group:?}"); + let mut d = app.ui.dialog.clone().unwrap(); + let mut rs = super::rows(&d); + assert!(rs.iter().all(|r| !is_added(r)), "{rs:?}"); + if let Some(r) = rs.last_mut() { + r["to"] = json!("rgb 10 10 10"); + } + d.fields.insert("rows".into(), Value::Array(rs)); + let colors: Vec = apply_params(&d)["groupColors"].as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + assert_eq!(colors.iter().filter(|c| *c == "#ffff00").count(), 1, "OK after a further edit keeps the added color once: {colors:?}"); + assert!(!colors.contains(&"#00ff00".to_string()), "nor brings the removed color back: {colors:?}"); + } + /// Save Changes where the rows list their current colors as "#rrggbb": a row matches the swatch /// of the same color, so the swatches keep their order and the one a row lists takes its new /// color; read again afterwards, a row whose old entry was a hex keeps its new color. @@ -3627,6 +3764,34 @@ mod tests { assert_eq!(group_hex(&app, "Plain").unwrap(), saved, "OK does not darken the group again"); } + /// Without art, Save Changes removes a removed color's swatch and adds a color added on the Edit + /// tab, and OK afterwards gives the group the same colors: it removes and adds nothing more. + #[test] + fn saving_a_group_without_art_with_added_and_removed_colors_keeps_them_at_ok() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#00ff00", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#00ff00") { + r["to"] = Value::Null; + } + } + // The added color's row was moved ahead of the others. + rs.insert(0, json!({"from": [], "to": "rgb 255 255 0", "added": true})); + d.fields.insert("rows".into(), Value::Array(rs)); + act(&mut app, &ctx, 0.1, "save").unwrap(); + let want: Vec = ["#ff0000", "#0000ff", "#ffff00"].map(String::from).to_vec(); + assert_eq!(group_hex(&app, "Plain"), Some(want.clone()), "the save removes green and adds yellow"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(want), "OK gives the group the same colors"); + } + /// With art: a group picked in the list reduces the art to a row per color of the group, which /// become the rows' new colors, and the art previews them; the list draws beside the tabs and /// hides with `groupStorage`. diff --git a/docs/mcp.md b/docs/mcp.md index 3d884d5c66..754de2aea3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4685,8 +4685,8 @@ linked moves and the Color Theme Picker leave its new color as it is, and Save A from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo -step (art linked to its global swatches follows); given the group's own colors in order and no new name, it records no -undo step. And `recolor.apply` with `group` recolours the art and rewrites the +step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and +given the group's own colors in order and no new name, it records no undo step. And `recolor.apply` with `group` recolours the art and rewrites the group together. A `null` in `groupColors` removes the group's swatch at that place, and the swatches after it keep their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still @@ -4767,7 +4767,8 @@ dialog runs it (OK with it set in the same request runs it first): and `delete` (Delete) runs `swatch.delete` on the selected group. Each is its own undo step, and the art keeps its preview. When the art has colors of the group, `save` keeps the group's swatches in order: a swatch whose color a row lists takes that row's new color (its own color when the row is excluded), so art linked to the swatch takes the color -its row shows, and every other swatch keeps its color. After a `save` with art, the rows' new colors take the Global +its row shows, and every other swatch keeps its color. A row whose color was removed (`to: null`) and is not excluded +removes its swatch, and the colors added on the Edit tab follow the group's other colors, as at OK. After a `save` with art, the rows' new colors take the Global Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its colors alike. Until the rows or the Global Adjust change, OK changes the saved group only by the name From 98f5086c2095d157b84ab4d88ad32700b5ea626a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:59:21 -0800 Subject: [PATCH 084/138] =?UTF-8?q?Fix=20#8034:=20Other=20Library=E2=80=A6?= =?UTF-8?q?=20brings=20a=20.ai=20library's=20pattern=20swatches=20with=20t?= =?UTF-8?q?heir=20patterns?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Swatches › Open Swatch Library › Other Library… read a document's swatches without its pattern swatches, so a pattern from a .ai swatch library came in only as the colors it uses. - swatch.library.load keeps a document's pattern swatches, and keeps the document for a library that has them. swatch.library.add brings the pattern with its tile and art, as a pattern swatch with the library swatch's name, placement and color group. - The library panel draws those pattern swatches from their pattern. - The Swatch Libraries filter of Other Library… lists .ai and .eps files. - A file with no swatches, and a .ai or .eps whose swatches are only the default ones, are refused with "`` has no swatches of its own". Copy to User Defined refuses a loaded library with pattern swatches, since a .vcswatches file can't hold them. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/formats.rs | 4 +- crates/engine/src/cmd/fileio/tests.rs | 13 ++ .../engine/src/cmd/fileio/tests_aiimport.rs | 96 +++++++++++ crates/engine/src/cmd/swatchlib.rs | 157 +++++++++++++++--- crates/engine/src/tests/swatchlib.rs | 41 +++++ crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.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/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/panels/library_panel.rs | 2 +- crates/ui-egui/src/panels/swatches.rs | 2 +- .../ui-egui/src/panels/swatches/libraries.rs | 8 +- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 34 files changed, 344 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index acd25aea28..dd23467979 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -834,13 +834,13 @@ fn other_open_filters() -> impl Iterator impl Iterator { - std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| *f != (library_label, library_exts))) + std::iter::once((library_label, library_exts)).chain(builtin_open_filters().filter(move |f| f.0 != library_label)) } /// File → Place dialog filters: "All placeable files", then one per placeable format, then text, diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index bbf6883834..7ae78cb853 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -492,6 +492,19 @@ fn library_open_filters_list_library_formats_first() { } } +/// Other Library…'s Swatch Libraries filter lists the `.ai` and `.eps` documents whose swatches load +/// as a library, and it is the only filter of that label. +#[test] +fn the_swatch_library_filter_lists_ai_and_eps_files() { + let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect(); + for ext in ["ai", "eps", "ase", "gpl", "acb", "vcswatches"] { + assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]); + } + assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}"); + // File › Open still opens a `.ai` as a document, not as a swatch library. + assert!(!crate::cmd::swatchlib::LIBRARY_EXTS.contains(&"ai") && !opens_as_other("ai")); +} + /// The extensions usage texts list for export: one per writable format, each picking that format /// (`.png` picks PNG; PNG-8 is asked for by `format`). #[test] diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 78cca92873..e3ff266b9d 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -413,6 +413,102 @@ fn a_swatch_library_in_a_ai_file_without_layers_loads_its_palette() { assert!(matches!(sky, Some(vectorcraft_color::Paint::Gradient(_))), "{sky:?}"); } +/// A `.ai` swatch library (a palette and no layers) holding White, the gradient Sky and, in the +/// color group Textures, the swatch Tiles of the 4 pt pattern Dots, whose square is painted with +/// `square` (a color operator), a color the palette doesn't list. +fn textures_library(square: &str) -> Vec { + let dots = format!("%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_{square}\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"); + let gradient = + "%AI5_BeginGradient: (Sky)\n(Sky) 0 2 Bd\n[\n%_0 0 0 0 1 1 1 2 1 6 50 0 Bs\n%_0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\nBD\n%AI5_EndGradient\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\n0 0 0 0 1 1 1 Xa\n(White)\nPc\nBb\n2 (Sky) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB\n(Sky)\nPc\n\ + 1 (Textures) 1 Pg\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Tiles)\nPc\nPB\n%AI5_EndPalette\n"; + let data = ai::editing_data(200.0, 100.0, &format!("{dots}{gradient}{palette}")); + ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f") +} + +/// `swatch.library.load` of `file` named `name` → its library id. +fn load_library(s: &mut Session, name: &str, file: &[u8]) -> Value { + let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "name": name}); + s.execute("swatch.library.load", &p).unwrap()["library"].clone() +} + +/// Other Library… on a `.ai` swatch library lists its colors, gradients and pattern swatches in its +/// order and color groups, and adding the pattern swatch makes a pattern swatch with the pattern's +/// tile and art in the document, in the library's color group, not the pattern's colors. +#[test] +fn a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0 0 1 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let kinds: Vec<(&str, &str, Option<&str>)> = + lib["swatches"].as_array().unwrap().iter().map(|w| (w["name"].as_str().unwrap(), w["kind"].as_str().unwrap(), w["group"].as_str())).collect(); + assert_eq!(kinds, [("White", "color", None), ("Sky", "gradient", None), ("Tiles", "pattern", Some("Textures"))], "{lib}"); + assert_eq!(lib["swatches"][2]["pattern"], json!("Dots"), "{lib}"); + // The library panel draws the pattern from the file it came from; a copy of the swatch isn't its own. + let (_, library) = crate::cmd::swatchlib::library(&s, id.as_str().unwrap()).unwrap(); + let tiles = library.iter().find(|w| w.name == "Tiles").unwrap(); + assert!(crate::cmd::swatchlib::pattern_source(&s, tiles).is_some_and(|d| d.pattern("Dots").is_some())); + assert!(crate::cmd::swatchlib::pattern_source(&s, &tiles.clone()).is_none()); + + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let r = s.execute("swatch.library.add", &json!({"library": id, "names": ["Textures"]})).unwrap(); + assert_eq!(r["added"], json!(["Tiles"]), "{r}"); + let doc = &s.doc().unwrap().doc; + let dots = doc.pattern("Dots").expect("the pattern comes with its swatch"); + assert_eq!((dots.tile.width(), dots.tile.height()), (4.0, 4.0)); + assert_eq!(dots.art.len(), 1, "{:?}", dots.art); + let textures = doc.swatch_groups.iter().find(|g| g.name == "Textures").expect("the color group comes too"); + let tiles: Vec<_> = textures.swatches.iter().map(|w| (w.name.as_str(), &w.paint)).collect(); + assert!(matches!(tiles[..], [("Tiles", vectorcraft_color::Paint::Pattern { pattern, .. })] if pattern == "Dots"), "{tiles:?}"); + // Added again, the swatch the document has is used. + let again = s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + assert_eq!((again["added"].clone(), again["existing"].clone()), (json!([]), json!(["Tiles"])), "{again}"); +} + +/// A pattern swatch of a `.ai` library whose pattern paints with a color the library doesn't list +/// still comes in with that color in its art. +#[test] +fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() { + let mut s = Session::new(); + let id = load_library(&mut s, "textures.ai", &textures_library("0 0.5 1 0 k")); + let lib = s.execute("swatch.library.get", &json!({"library": id})).unwrap(); + let names: Vec<&str> = lib["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["White", "Sky", "Tiles"], "the pattern's color isn't listed: {lib}"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("swatch.library.add", &json!({"library": id, "names": ["Tiles"]})).unwrap(); + let doc = &s.doc().unwrap().doc; + let art = &doc.pattern("Dots").unwrap().art; + let fill = art.first().and_then(|n| n.appearance.fill()).map(|f| f.paint.color()); + assert_eq!(fill, Some(Some(vectorcraft_color::Color::cmyk(0.0, 0.5, 1.0, 0.0))), "{art:?}"); + // Copy to User Defined would write a .vcswatches file, which can't hold the pattern swatch: it is + // refused, writes nothing and leaves the library loaded. + let dir = std::env::temp_dir().join(format!("vc-pattern-copy-{}", std::process::id())); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let e = s.execute("swatch.library.copyToUser", &json!({"library": id})).unwrap_err().to_string(); + assert!(e.contains("`textures` has pattern swatches"), "{e}"); + assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().next().is_none(), "nothing written"); + assert!(s.execute("swatch.library.get", &json!({"library": id})).is_ok()); + std::fs::remove_dir_all(&dir).ok(); +} + +/// A `.ai` file without a palette of its own, and a library file with no swatches, are refused as +/// swatch libraries with a message, not listed as the default swatches or as an empty library. A +/// damaged `.ai` is refused with the reader's error, and neither is listed. +#[test] +fn swatch_library_files_without_swatches_or_damaged_are_refused() { + let mut s = Session::new(); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)))); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("`art.ai` has no swatches of its own"), "{e}"); + let e = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap_err().to_string(); + assert!(e.contains("`Empty.gpl` has no swatches of its own"), "{e}"); + let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"}); + assert!(s.execute("swatch.library.load", &damaged).is_err()); + let list = s.execute("swatch.library.list", &json!({})).unwrap(); + assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}"); +} + /// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the /// library the styles of its list, in the list's order, not the default styles; the file opens with /// them too. diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index ed712d8509..a6894ecb4d 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Other Library…", ["Window", "Swatch Libraries"], None, - "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}", + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and colour groups; swatch.library.add brings a pattern swatch's pattern with it. A file with no swatches is an error, and so is a .ai or .eps whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}", always, load ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Copy to User Defined", ["Window", "Swatch Libraries"], None, - "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file. A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", + "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused: a .vcswatches file can't hold them). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", has_user_folder, copy_to_user ), @@ -109,6 +109,9 @@ pub struct Libraries { /// the file name instead. [`Libraries::rescan`] drops an entry whose file no longer holds those /// bytes, and keeps one whose file is missing so a file put back can be checked. saved_as: HashMap, + /// The documents loaded swatch libraries were read from, by library id, for those with pattern + /// swatches: the patterns live there ([`Libraries::pattern_doc`]). + pattern_docs: HashMap>, } /// A User Defined file this session wrote: the library's name, and [`vectorcraft_doc::links::hash_bytes`] @@ -149,6 +152,35 @@ impl LibraryFile for SwatchLibrary { /// The extensions of library files [`palette_io::read_bytes`] reads. pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"]; +/// The extensions the Swatch Libraries filter of Other Library… lists: the library files, and the +/// `.ai` and `.eps` documents whose swatches load as a library (`swatch.library.load`). +pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "eps"]; + +impl Libraries { + /// Keep `doc`, the document loaded library `id` was read from, for its pattern swatches; `None` + /// forgets the one kept for `id`. + fn set_pattern_doc(&mut self, id: &str, doc: Option>) { + match doc { + Some(doc) => self.pattern_docs.insert(id.to_string(), doc), + None => self.pattern_docs.remove(id), + }; + } + + /// The document holding the patterns of loaded library `id`'s pattern swatches. + pub fn pattern_doc(&self, id: &str) -> Option> { + self.pattern_docs.get(id).cloned() + } + + /// The document holding the pattern of swatch `w`, when `w` is one of a loaded library's own + /// pattern swatches (a library panel draws them from it). + pub fn pattern_source(&self, w: &Swatch) -> Option> { + let Paint::Pattern { pattern, .. } = &w.paint else { return None }; + let own = |lib: &SwatchLibrary| lib.iter().any(|s| std::ptr::eq(s, w)); + let e = self.extra.iter().find(|e| own(&e.lib))?; + self.pattern_doc(&e.info.id).filter(|d| d.pattern(pattern).is_some()) + } +} + /// A library file the save commands write ([`Libraries::write`]). pub(crate) enum FileData { /// Text (`.vcswatches`, `.gpl`, CSS, `.vcstyles`), returned as `data`. @@ -646,6 +678,12 @@ pub fn library_swatches(s: &Session, key: &str) -> Option> { Some(library(s, key)?.1.iter().filter(own).cloned().collect()) } +/// The document holding the pattern of library swatch `w`: a built-in pattern library's or a loaded +/// library's own pattern swatch (a library panel draws them from it). +pub fn pattern_source(s: &Session, w: &Swatch) -> Option> { + patternlib::swatch_source(w).or_else(|| s.swatch_libraries.pattern_source(w)) +} + /// The `limitTo` parameter's palette ([`limit_palette`]); `None` without one (or for "" or null). /// A `limitTo` that is not a string, such as `5`, names no library. pub(crate) fn limit_param(s: &Session, p: &Value, cmd: &str) -> Result> { @@ -694,13 +732,17 @@ fn list(s: &mut Session, _: &Value) -> Result { } /// The document's swatches `names` (swatches or colour groups; empty: all) as a library named -/// `name`, without None and patterns. -fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, cmd: &str) -> Result { +/// `name`, without None, and without pattern swatches unless `patterns`. +fn document_library(d: &vectorcraft_doc::Document, names: &[String], name: String, patterns: bool, cmd: &str) -> Result { if let Some(n) = names.iter().find(|n| !d.swatch_name_taken(n)) { return Err(bad(cmd, format!("no swatch or colour group `{n}`"))); } let want = |n: &str| names.is_empty() || names.iter().any(|x| x == n); - let savable = |w: &&Swatch| matches!(w.paint, Paint::Solid { .. } | Paint::Gradient(_)); + let savable = |w: &&Swatch| match w.paint { + Paint::Solid { .. } | Paint::Gradient(_) => true, + Paint::Pattern { .. } => patterns, + _ => false, + }; let swatches = d.swatches.iter().filter(savable).filter(|w| want(&w.name)).cloned().collect(); let groups = d .swatch_groups @@ -724,7 +766,7 @@ fn save(s: &mut Session, p: &Value) -> Result { let names = names_param(p, C)?; let st = s.doc()?; let name = text_param(p, "name", C)?.map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string); - let lib = document_library(&st.doc, &names, name, C)?; + let lib = document_library(&st.doc, &names, name, false, C)?; let bytes = palette_io::write(&lib, format).map_err(|e| bad(C, e))?; let data = if format.binary() { FileData::Binary(bytes) } else { FileData::Text(String::from_utf8_lossy(&bytes).into_owned()) }; let mut out = json!({"format": format.id(), "count": lib.iter().filter(|w| format.holds(&w.paint)).count()}); @@ -734,21 +776,48 @@ fn save(s: &mut Session, p: &Value) -> Result { fn load(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.load"; + // The document a library with pattern swatches was read from, which holds their patterns. + let mut patterns = None; let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| { // A library file, or a document whose swatches become the library. - if palette_io::sniff_bytes(bytes) { - palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)) + let lib = if palette_io::sniff_bytes(bytes) { + palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))? } else { let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; if loaded.preview_only { return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); } - document_library(&loaded.doc, &[], stem(file).to_string(), C) + // A `.ai` or EPS file without a palette of its own opens with the default swatches. + if matches!(loaded.format.id, "ai" | "ait" | "eps") && has_only_default_swatches(&loaded.doc) { + return Err(bad(C, format!("`{file}` has no swatches of its own"))); + } + let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; + if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) { + patterns = Some(Arc::new(loaded.doc)); + } + lib + }; + if lib.is_empty() { + return Err(bad(C, format!("`{file}` has no swatches of its own"))); } + Ok(lib) })?; + if info.category == "loaded" { + s.swatch_libraries.set_pattern_doc(&info.id, patterns); + } Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } +/// `d`'s swatches and colour groups are exactly the default ones of a colour mode, as a new +/// document's are. +fn has_only_default_swatches(d: &vectorcraft_doc::Document) -> bool { + use vectorcraft_color::cms::Model; + [Model::Rgb, Model::Cmyk].into_iter().any(|model| { + let (swatches, groups) = default_swatches(model); + d.swatches[..] == swatches[..] && d.swatch_groups[..] == groups[..] + }) +} + fn get(s: &mut Session, p: &Value) -> Result { let (info, lib) = library_param(s, p, "swatch.library.get")?; let ungrouped = lib.swatches.iter().map(|w| swatch_json(w, None)); @@ -772,6 +841,9 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.copyToUser"; let (info, lib) = library_param(s, p, C)?; let (info, lib, copied) = match info.category { + "loaded" if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) => { + return Err(bad(C, format!("`{}` has pattern swatches, which a .vcswatches file can't hold", info.name))); + } "loaded" => { let native = |lib: &SwatchLibrary| palette_io::write(lib, PaletteFormat::Native).map_err(|e| bad(C, e)); s.swatch_libraries.copy_to_user(&info.id, PaletteFormat::Native.id(), native, C)? @@ -811,6 +883,22 @@ fn picked<'a>(lib: &'a SwatchLibrary, names: &[String], cmd: &str) -> Result Option { + let Paint::Pattern { pattern, xf } = &w.paint else { return None }; + let paint = Paint::Pattern { pattern: target.to_string(), xf: *xf }; + let named = |n: &str| { + w.name == *pattern + || n == w.name + || n.strip_prefix(w.name.as_str()) + .and_then(|r| r.strip_prefix(' ')) + .is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit())) + }; + d.swatches_iter().find(|x| x.paint == paint && named(&x.name)).map(|x| x.name.clone()) +} + /// Every name a swatch or colour group of `d` uses (they share one namespace, with the registration swatch). fn taken_names(d: &vectorcraft_doc::Document) -> HashSet { let names = d.swatches_iter().map(|w| &w.name).chain(d.swatch_groups.iter().map(|g| &g.name)); @@ -840,8 +928,9 @@ fn add(s: &mut Session, p: &Value) -> Result { let focus = switch_or(p, "focus", true, C)?; let picked = picked(&lib, &names_param(p, C)?, C)?; // Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the - // same pattern) are reused, not added again. - let patterns = patternlib::library_doc(&info.id); + // same pattern) are reused, not added again. The patterns are in a built-in pattern library's + // document, or in the document a loaded library was read from. + let patterns = patternlib::library_doc(&info.id).or_else(|| s.swatch_libraries.pattern_doc(&info.id)); let d = &s.doc()?.doc; // The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked // up once so that a large palette takes linear time. @@ -851,7 +940,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } let there = |w: &Swatch| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { - patternlib::existing_pattern(d, src, pattern).and_then(|target| patternlib::pattern_swatch(d, &target)) + patternlib::existing_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } _ => match by_name.get(w.name.as_str()) { Some(x) => x.paint == w.paint, @@ -881,24 +970,38 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut placed: Vec<(&str, usize)> = vec![]; let mut taken = taken_names(d); for (group, w) in fresh { - if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { + let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { // The pattern comes with its swatch; a pattern the document has without one - // gets one. + // gets one. The swatch a pattern that comes in brings is named after the pattern: + // it takes the library swatch's name and colour group instead. + let had = taken_names(d); let target = patternlib::import(d, src, pattern)?; - let name = match patternlib::pattern_swatch(d, &target) { - Some(name) => name, - None => { - let name = d.free_swatch_name(&target); - d.swatches.push(Swatch { name: name.clone(), paint: pattern_paint(&target), global: false, spot: false }); - name - } - }; - out.push((w.name.clone(), name)); + if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { + out.push((w.name.clone(), name)); + taken = taken_names(d); + continue; + } + let made = patternlib::pattern_swatch(d, &target).filter(|n| !had.contains(n)); + if let Some(made) = &made { + d.swatches.retain(|x| x.name != *made); + } taken = taken_names(d); - continue; - } - let name = free_in(&mut taken, &w.name); - let sw = Swatch { name: name.clone(), ..(*w).clone() }; + let name = match made { + Some(made) if w.name == *pattern => made, + None if w.name == *pattern => d.free_swatch_name(&target), + _ => free_in(&mut taken, &w.name), + }; + taken.insert(name.clone()); + // The library swatch's placement of its pattern is kept. + let paint = match &w.paint { + Paint::Pattern { xf, .. } => Paint::Pattern { pattern: target, xf: *xf }, + _ => pattern_paint(&target), + }; + (name.clone(), Swatch { name, paint, global: false, spot: false }) + } else { + let name = free_in(&mut taken, &w.name); + (name.clone(), Swatch { name, ..(*w).clone() }) + }; match group { Some(g) => { let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index dbf32eba7c..f44266b9de 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -300,6 +300,47 @@ fn another_documents_swatches_load_as_a_library() { assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err()); } +/// Three pattern swatches of another document that paint one pattern, one of them turned, load as +/// three library swatches and come into a document as three swatches of one pattern, each with its +/// own name and placement. +#[test] +fn another_documents_pattern_swatches_of_one_pattern_add_as_separate_swatches() { + use std::sync::Arc; + let turned = vectorcraft_geom::Affine::rotate(0.5); + let mut s = session(); + s.edit("Pattern", |d, _| { + let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)); + let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art()); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) }); + let swatch = |name: &str, xf| vectorcraft_color::Swatch { + name: name.into(), + paint: Paint::Pattern { pattern: "Dots".into(), xf }, + global: false, + spot: false, + }; + d.swatches.push(swatch("Tiles", vectorcraft_geom::Affine::IDENTITY)); + d.swatches.push(swatch("More tiles", vectorcraft_geom::Affine::IDENTITY)); + d.swatches.push(swatch("Turned tiles", turned)); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "More tiles", "Turned tiles"]})); + assert_eq!(r["added"], json!(["Tiles", "More tiles", "Turned tiles"]), "{r}"); + let d = doc(&s); + assert_eq!(d.patterns.iter().filter(|p| p.name.starts_with("Dots")).count(), 1, "one pattern"); + let xf = |name: &str| match d.swatch(name).map(|w| &w.paint) { + Some(Paint::Pattern { pattern, xf }) if pattern == "Dots" => Some(*xf), + _ => None, + }; + assert_eq!((xf("Tiles"), xf("Turned tiles")), (Some(vectorcraft_geom::Affine::IDENTITY), Some(turned))); + let again = run(&mut s, "swatch.library.add", json!({"library": id})); + assert_eq!(again["added"], json!([]), "{again}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..a58eac2b35 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6173,6 +6173,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no target object has an opacity mask: select one or give `id` no hi ha cap objecte de destinació amb màscara d’opacitat: seleccioneu-ne un o doneu `id` @msg no threaded text selected no hi ha cap text encadenat seleccionat @msg no user library folder here aquí no hi ha cap carpeta de biblioteca d’usuari +@msg `{file}` has no swatches of its own `{file}` no té mostres pròpies +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` té mostres de motius, que un fitxer .vcswatches no pot contenir @msg no user workspace `{from}` no hi ha l’espai de treball d’usuari `{from}` @msg node {_1} is not text el node {_1} no és text @msg node {_1} is on a locked artboard el node {_1} és en un tauler bloquejat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..b19042c023 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8228,6 +8228,8 @@ breakText Glyphs Glyfy @msg `{f}` is the copy of a document open now `{f}` je kopie právě otevřeného dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` není formát, který lze zapisovat (viz document.formats) @msg `{id}` isn't a loaded library `{id}` není načtená knihovna +@msg `{file}` has no swatches of its own `{file}` nemá žádné vlastní vzorky +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` obsahuje vzorky, které soubor .vcswatches nepojme @msg `{key}` has no colours `{key}` neobsahuje žádné barvy @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` obsahuje více než {MAX_EDIT_WORDS} slov @msg `{key}` is a design name `{key}` je název návrhu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..1b830f4440 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1252,6 +1252,8 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{f}` is the copy of a document open now `{f}` er kopien af et dokument, der er åbent nu @msg `{id}` is no writable format (see document.formats) `{id}` er ikke et skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` er ikke et indlæst bibliotek +@msg `{file}` has no swatches of its own `{file}` har ingen egne farveprøver +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mønsterprøver, som en .vcswatches-fil ikke kan indeholde @msg `{key}` has no colours `{key}` har ingen farver @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` indeholder mere end {MAX_EDIT_WORDS} ord @msg `{key}` is a design name `{key}` er et designnavn diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..e3ae47d44e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7978,6 +7978,8 @@ breakText Glyphs Glyphen @msg `{f}` is the copy of a document open now `{f}` ist die Kopie eines gerade geöffneten Dokuments @msg `{id}` is no writable format (see document.formats) `{id}` ist kein beschreibbares Format (siehe document.formats) @msg `{id}` isn't a loaded library `{id}` ist keine geladene Bibliothek +@msg `{file}` has no swatches of its own `{file}` hat keine eigenen Farbfelder +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` enthält Musterfelder, die eine .vcswatches-Datei nicht aufnehmen kann @msg `{key}` has no colours `{key}` hat keine Farben @msg `{key}` is a design name `{key}` ist ein Designname @msg `{key}` is a design name or a list of them `{key}` ist ein Designname oder eine Liste davon diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..aca6372062 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4966,6 +4966,8 @@ digits Malayalam Μαλαγιάλαμ @msg no target object has an opacity mask: select one or give `id` κανένα αντικείμενο-στόχος δεν έχει μάσκα αδιαφάνειας: επιλέξτε ένα ή δώστε `id` @msg no threaded text selected δεν έχει επιλεγεί συνδεδεμένο κείμενο @msg no user library folder here δεν υπάρχει φάκελος βιβλιοθήκης χρήστη εδώ +@msg `{file}` has no swatches of its own το `{file}` δεν έχει δικά του δείγματα χρωμάτων +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold το `{_1}` έχει δείγματα μοτίβου, που ένα αρχείο .vcswatches δεν μπορεί να περιέχει @msg no user workspace `{from}` δεν υπάρχει χώρος εργασίας χρήστη `{from}` @msg node {_1} is not text ο κόμβος {_1} δεν είναι κείμενο @msg node {_1} is on a locked artboard ο κόμβος {_1} βρίσκεται σε κλειδωμένο πίνακα σχεδίασης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..3ceae127b3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5012,6 +5012,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg no target object has an opacity mask: select one or give `id` ningún objeto de destino tiene máscara de opacidad: selecciona uno o indica `id` @msg no threaded text selected no hay texto enlazado seleccionado @msg no user library folder here aquí no hay ninguna carpeta de bibliotecas de usuario +@msg `{file}` has no swatches of its own `{file}` no tiene muestras propias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tiene muestras de motivo, que un archivo .vcswatches no puede contener @msg no user workspace `{from}` no existe el espacio de trabajo de usuario `{from}` @msg node {_1} is not text el nodo {_1} no es texto @msg node {_1} is on a locked artboard el nodo {_1} está en una mesa de trabajo bloqueada diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..5ec1c92b88 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5236,6 +5236,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no target object has an opacity mask: select one or give `id` millään kohdeobjektilla ei ole peittävyysmaskia: valitse sellainen tai anna `id` @msg no threaded text selected ketjutettua tekstiä ei ole valittu @msg no user library folder here täällä ei ole käyttäjäkirjastokansiota +@msg `{file}` has no swatches of its own tiedostossa `{file}` ei ole omia värimalleja +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold kirjastossa `{_1}` on kuviomalleja, joita .vcswatches-tiedosto ei voi sisältää @msg no user workspace `{from}` ei käyttäjän työtilaa `{from}` @msg node {_1} is not text solmu {_1} ei ole tekstiä @msg node {_1} is on a locked artboard solmu {_1} on lukitulla piirtoalustalla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..5d0b01a9e9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8090,6 +8090,8 @@ breakText Glyphs Glyphes @msg `{f}` is the copy of a document open now `{f}` est la copie d’un document actuellement ouvert @msg `{id}` is no writable format (see document.formats) `{id}` n’est pas un format inscriptible (voir document.formats) @msg `{id}` isn't a loaded library `{id}` n’est pas une bibliothèque chargée +@msg `{file}` has no swatches of its own `{file}` n’a pas de nuances propres +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` contient des nuances de motif, qu’un fichier .vcswatches ne peut pas contenir @msg `{key}` has no colours `{key}` ne contient aucune couleur @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contient plus de {MAX_EDIT_WORDS} mots @msg `{key}` is a design name `{key}` est un nom de motif diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..e69d1f0850 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6099,6 +6099,8 @@ antiAlias Sharp शार्प @msg `{id}` is no writable format (see document.formats) `{id}` लिखने योग्य फ़ॉर्मैट नहीं है (document.formats देखें) @msg `{id}` is not a colour adjustment `{id}` एक रंग समायोजन नहीं है @msg `{id}` isn't a loaded library `{id}` एक लोड लाइब्रेरी नहीं है +@msg `{file}` has no swatches of its own `{file}` में अपने कोई स्वॉचेस नहीं हैं +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` में पैटर्न स्वॉचेस हैं, जिन्हें .vcswatches फ़ाइल नहीं रख सकती @msg `{k}.family` is required `{k}.family` की आवश्यकता है @msg `{k}` is a number 0..1 `{k}` एक नंबर 0..1 है। @msg `{k}` is true or false `{k}` true या false है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..05bd1f725d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8099,6 +8099,8 @@ breakText Glyphs Glifák @msg `{f}` is the copy of a document open now egy most megnyitott dokumentum másolata: `{f}` @msg `{id}` is no writable format (see document.formats) nem írható formátum: `{id}` (lásd: document.formats) @msg `{id}` isn't a loaded library nem betöltött könyvtár: `{id}` +@msg `{file}` has no swatches of its own nincsenek saját színminták: `{file}` +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold mintázatszínmintákat tartalmaz, amelyeket egy .vcswatches fájl nem tud tárolni: `{_1}` @msg `{key}` has no colours `{key}`: nincsenek benne színek @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`: több mint {MAX_EDIT_WORDS} szót tartalmaz @msg `{key}` is a design name `{key}`: diagramminta neve diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..cf0529a250 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8028,6 +8028,8 @@ breakText Glyphs Glifi @msg `{f}` is the copy of a document open now `{f}` è la copia di un documento aperto in questo momento @msg `{id}` is no writable format (see document.formats) `{id}` non è un formato scrivibile (vedi document.formats) @msg `{id}` isn't a loaded library `{id}` non è una libreria caricata +@msg `{file}` has no swatches of its own `{file}` non ha campioni propri +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` ha campioni motivo, che un file .vcswatches non può contenere @msg `{key}` has no colours `{key}` non ha colori @msg `{key}` is a design name `{key}` è il nome di un design @msg `{key}` is a design name or a list of them `{key}` è il nome di un design o un elenco di nomi diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..09c16bb60d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7193,6 +7193,8 @@ axis Y Axis Y 軸 @msg `{f}` is the copy of a document open now `{f}` は現在開いているドキュメントのコピーです @msg `{id}` is no writable format (see document.formats) `{id}` は書き出せる形式ではありません (document.formats を参照) @msg `{id}` isn't a loaded library `{id}` は読み込まれているライブラリではありません +@msg `{file}` has no swatches of its own `{file}` には独自のスウォッチがありません +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` にはパターンスウォッチがあり、.vcswatches ファイルには保存できません @msg `{key}` has no colours `{key}` にカラーがありません @msg `{key}` is a design name `{key}` にはデザイン名を指定してください @msg `{key}` is a design name or a list of them `{key}` にはデザイン名またはそのリストを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..d54224ce3c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -408,6 +408,8 @@ @msg `{f}` is the copy of a document open now `{f}` ახლა გახსნილი დოკუმენტის ასლია @msg `{id}` is no writable format (see document.formats) `{id}` ჩაწერადი ფორმატი არ არის (იხ. document.formats) @msg `{id}` isn't a loaded library `{id}` ჩატვირთული ბიბლიოთეკა არ არის +@msg `{file}` has no swatches of its own `{file}`-ს საკუთარი ფერის ნიმუშები არ აქვს +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`-ს აქვს პატერნის ნიმუშები, რომლებსაც .vcswatches ფაილი ვერ შეინახავს @msg `{key}` has no colours `{key}`: ფერები არ არის @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` {MAX_EDIT_WORDS}-ზე მეტ სიტყვას შეიცავს @msg `{key}` is a design name `{key}` არის დიზაინის სახელი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..28bf41fa6c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7823,6 +7823,8 @@ breakText Glyphs 글리프 @msg `{f}` is the copy of a document open now `{f}`은(는) 지금 열려 있는 문서의 복사본입니다 @msg `{id}` is no writable format (see document.formats) `{id}`은(는) 기록할 수 있는 형식이 아닙니다(document.formats 참조) @msg `{id}` isn't a loaded library `{id}`은(는) 불러온 라이브러리가 아닙니다 +@msg `{file}` has no swatches of its own `{file}`에 자체 견본이 없습니다 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}`에 패턴 견본이 있어 .vcswatches 파일에 담을 수 없습니다 @msg `{key}` has no colours `{key}`에 색상이 없습니다 @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}`에 단어가 {MAX_EDIT_WORDS}개보다 많습니다 @msg `{key}` is a design name `{key}`은(는) 디자인 이름입니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..6704d538ed 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6107,6 +6107,8 @@ imageTrace Outline Contour @msg `{f}` is the copy of a document open now `{f}` is de kopie van een document dat nu geopend is @msg `{id}` is no writable format (see document.formats) `{id}` is geen schrijfbare indeling (zie document.formats) @msg `{id}` isn't a loaded library `{id}` is geen geladen bibliotheek +@msg `{file}` has no swatches of its own `{file}` heeft geen eigen stalen +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` heeft patroonstalen, die een .vcswatches-bestand niet kan bevatten @msg `{key}` has no colours `{key}` heeft geen kleuren @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` bevat meer dan {MAX_EDIT_WORDS} woorden @msg `{key}` is a design name `{key}` is de naam van een ontwerp diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..1b33c2df92 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8269,6 +8269,8 @@ breakText Glyphs Glify @msg `{f}` is the copy of a document open now `{f}` to kopia otwartego teraz dokumentu @msg `{id}` is no writable format (see document.formats) `{id}` nie jest formatem z możliwością zapisu (patrz document.formats) @msg `{id}` isn't a loaded library `{id}` nie jest wczytaną biblioteką +@msg `{file}` has no swatches of its own `{file}` nie ma własnych próbek +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` zawiera próbki wzorków, których plik .vcswatches nie może przechować @msg `{key}` has no colours `{key}` nie zawiera kolorów @msg `{key}` is a design name `{key}` to nazwa wzoru @msg `{key}` is a design name or a list of them `{key}` to nazwa wzoru lub lista takich nazw diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..e84106062a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8290,6 +8290,8 @@ swatch Yellow Green Verde-amarelado @msg `{f}` is the copy of a document open now `{f}` é a cópia de um documento aberto agora @msg `{id}` is no writable format (see document.formats) `{id}` não é um formato gravável (veja document.formats) @msg `{id}` isn't a loaded library `{id}` não é uma biblioteca carregada +@msg `{file}` has no swatches of its own `{file}` não tem amostras próprias +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` tem amostras de padrão, que um arquivo .vcswatches não pode conter @msg `{key}` has no colours `{key}` não tem cores @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` contém mais de {MAX_EDIT_WORDS} palavras @msg `{key}` is a design name `{key}` é o nome de um projeto diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..63773818ba 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8213,6 +8213,8 @@ shape Open Открытый @msg `{f}` is the copy of a document open now `{f}` — копия документа, открытого сейчас @msg `{id}` is no writable format (see document.formats) `{id}` не является форматом для записи (см. document.formats) @msg `{id}` isn't a loaded library `{id}` не является загруженной библиотекой +@msg `{file}` has no swatches of its own в `{file}` нет собственных образцов +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold в `{_1}` есть образцы узоров, которые файл .vcswatches не может хранить @msg `{key}` has no colours в `{key}` нет цветов @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` содержит больше {MAX_EDIT_WORDS} слов @msg `{key}` is a design name `{key}` — имя дизайна diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..428471a4cc 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7793,6 +7793,8 @@ digits Hindi Hindi @msg `{file}` is over {_1} MB `{file}` är större än {_1} MB @msg `{id}` is no writable format (see document.formats) `{id}` är inget skrivbart format (se document.formats) @msg `{id}` isn't a loaded library `{id}` är inte ett inläst bibliotek +@msg `{file}` has no swatches of its own `{file}` har inga egna färgrutor +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` har mönsterprover, som en .vcswatches-fil inte kan innehålla @msg `{k}.family` is required `{k}.family` är obligatoriskt @msg `{k}` is a number 0..1 `{k}` är ett tal 0..1 @msg `{k}` is true or false `{k}` är true eller false diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..4b14bec245 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7576,6 +7576,8 @@ axis Y Axis Y ekseni @msg `{f}` is the copy of a document open now `{f}` şu anda açık olan bir belgenin kopyası @msg `{id}` is no writable format (see document.formats) `{id}` yazılabilir bir biçim değil (bkz. document.formats) @msg `{id}` isn't a loaded library `{id}` yüklenmiş bir kütüphane değil +@msg `{file}` has no swatches of its own `{file}` dosyasının kendi renk örnekleri yok +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` desen örnekleri içeriyor ve bir .vcswatches dosyası bunları tutamaz @msg `{key}` has no colours `{key}` renk içermiyor @msg `{key}` is a design name `{key}` bir tasarım adıdır @msg `{key}` is a design name or a list of them `{key}` bir tasarım adı veya tasarım adları listesidir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..1df459bc74 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7827,6 +7827,8 @@ breakText Glyphs Гліфи @msg `{f}` is the copy of a document open now `{f}` — це копія документа, відкритого зараз @msg `{id}` is no writable format (see document.formats) `{id}` не є форматом, доступним для запису (див. document.formats) @msg `{id}` isn't a loaded library `{id}` не є завантаженою бібліотекою +@msg `{file}` has no swatches of its own у `{file}` немає власних зразків +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold у `{_1}` є зразки візерунків, яких файл .vcswatches не може містити @msg `{key}` has no colours `{key}` не містить кольорів @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` містить понад {MAX_EDIT_WORDS} слів @msg `{key}` is a design name `{key}` — це назва дизайну diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..9bd765d12e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5373,6 +5373,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg no target object has an opacity mask: select one or give `id` không có đối tượng đích có mặt nạ độ mờ: hãy chọn hoặc cung cấp `id` @msg no threaded text selected chưa chọn văn bản liên kết @msg no user library folder here không có thư mục thư viện người dùng ở đây +@msg `{file}` has no swatches of its own `{file}` không có mẫu màu riêng +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` có mẫu họa tiết, mà tệp .vcswatches không thể chứa @msg no user workspace `{from}` không có không gian làm việc người dùng `{from}` @msg node {_1} is not text nút {_1} không phải là văn bản @msg node {_1} is on a locked artboard nút {_1} nằm trên bảng vẽ bị khóa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..72232280d7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8255,6 +8255,8 @@ breakText Glyphs 字形 @msg `{f}` is the copy of a document open now `{f}` 是当前已打开文档的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可写入的格式 (参见 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已载入的库 +@msg `{file}` has no swatches of its own `{file}` 没有自己的色板 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有图案色板,.vcswatches 文件无法保存 @msg `{key}` has no colours `{key}` 中没有颜色 @msg `{key}` is a design name `{key}` 是设计名称 @msg `{key}` is a design name or a list of them `{key}` 是一个设计名称或设计名称的列表 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..4a5927fd0b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8183,6 +8183,8 @@ breakText Glyphs 字符 @msg `{f}` is the copy of a document open now `{f}` 是目前開啟文件的副本 @msg `{id}` is no writable format (see document.formats) `{id}` 不是可寫入的格式 (請參閱 document.formats) @msg `{id}` isn't a loaded library `{id}` 不是已載入的資料庫 +@msg `{file}` has no swatches of its own `{file}` 沒有自己的色票 +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` 含有圖樣色票,.vcswatches 檔案無法儲存 @msg `{key}` has no colours `{key}` 沒有顏色 @msg `{key}` is a design name `{key}` 是設計名稱 @msg `{key}` is a design name or a list of them `{key}` 是設計名稱或設計名稱的清單 diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index fdfb2f7c3b..01c3af49a2 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -576,7 +576,7 @@ fn set(app: &mut VectorcraftApp, panel: &str, mut params: Value) { /// (symbol and brush libraries: any document). pub(crate) fn library_pick_filters(kind: &str) -> Vec<(&'static str, &'static [&'static str])> { match kind { - super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_EXTS).collect(), + super::swatches::SwatchLibraries::KIND => fileio::library_open_filters("Swatch libraries", swatchlib::LIBRARY_PICK_EXTS).collect(), super::graphic_styles::GraphicStyleLibraries::KIND => fileio::library_open_filters("Graphic Style Libraries", &[STYLES_EXT]).collect(), _ => fileio::builtin_open_filters().collect(), } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index a27c8b65ff..75959323f2 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -14,7 +14,7 @@ use vectorcraft_color::libraries::{BuiltinLibrary, GRADIENT_LIBRARIES, SWATCH_LI use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, GradientKind, Paint, Swatch, SwatchLibrary}; use vectorcraft_doc::Document; -use vectorcraft_engine::cmd::patternlib::{self, PATTERN_LIBRARIES}; +use vectorcraft_engine::cmd::patternlib::PATTERN_LIBRARIES; use vectorcraft_engine::cmd::swatchlib; use super::library_panel::{self, LibraryKind, LibraryRef, Row}; diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 864f6ae7e0..d5722e6354 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -3,7 +3,7 @@ use super::dnd::selection; use super::tiles::{describe, global_mark, list_icons, pattern_thumb_in}; use super::{ Arc, BuiltinLibrary, GRADIENT_LIBRARIES, Item, LibraryKind, LibraryRef, PATTERN_LIBRARIES, Rect, Row, SWATCH_LIBRARIES, Swatch, SwatchLibrary, - Ui, Value, VectorcraftApp, json, library_panel, menu_item, patternlib, swatch_tile, swatchlib, + Ui, Value, VectorcraftApp, json, library_panel, menu_item, swatch_tile, swatchlib, }; fn library_refs(libs: Vec) -> Vec { @@ -97,10 +97,10 @@ impl LibraryKind for SwatchLibraries { } out } - fn draw(_: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { + fn draw(app: &VectorcraftApp, ui: &Ui, r: Rect, w: &Swatch, selected: bool, hovered: bool) { swatch_tile(ui, r, &w.paint, selected, hovered); - // A built-in pattern library's pattern, drawn from the library. - if let Some(src) = patternlib::swatch_source(w) { + // A pattern library's pattern, or a loaded library's, drawn from the library. + if let Some(src) = swatchlib::pattern_source(&app.session, w) { pattern_thumb_in(&src, ui, r.shrink(1.0), &w.paint); } if w.global { diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..851d7c8871 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4887,9 +4887,15 @@ spot or process swatches and keeps their color groups. A color book (such as a P CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the same extension and bytes as one there, loads as that User Defined library (category `user`). +From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches +in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and +art, into the document as a pattern swatch under the library swatch's name and in its color group. A file with no +swatches, and a `.ai` or `.eps` file whose swatches are only the default ones, are refused with +"`` has no swatches of its own". The Swatch Libraries filter of Other Library… lists `.ai` and `.eps` files +as well as the library files. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` -as `.vcswatches`) under a name no file there has, and lists it as User Defined from then on; until the app +as `.vcswatches`; a library with pattern swatches is refused, since a `.vcswatches` file can't hold them) under a name no file there has, and lists it as User Defined from then on; until the app quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` when the folder already held the same file). Without a user library folder the command is disabled. These commands refuse a parameter of the wrong form with an error that names it: `library`, `apply`, `path`, `data`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..1e57a1d692 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1862,6 +1862,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A file with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_files_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From 3edb8446835d2b09e9f30bb7da7a3ea9f084c682 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:07:25 -0800 Subject: [PATCH 085/138] Performance: Low-Latency Drawing preference presents without vsync, capped at 240 fps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Preferences › Performance › Low-Latency Drawing (lowLatencyDrawing, off by default) is read when the app starts and asks for wgpu's AutoNoVsync. The present mode comes from --present-mode, then VECTORCRAFT_PRESENT_MODE, then the preference, then the default; with the preference off and no override the window surface is unchanged. The startup log names "(preference)" or "(override)" after the mode. Whenever the window presents without vsync, from the preference or an override, main-window frames start at most 240 times a second (about 4.17 ms apart). The wait comes before egui reads the frame's input, and the frame's time moves on by it. With vsync the display paces the frames and no cap applies. The checkbox shows on the desktop with the note that it applies the next time VectorCraft starts. A value that is not a boolean is an error. Fixes #6013 --- apps/vectorcraft/src/app.rs | 10 ++ apps/vectorcraft/src/main.rs | 23 +++- apps/vectorcraft/src/presentation.rs | 137 ++++++++++++++++++++--- crates/engine/src/cmd/prefscmds.rs | 2 + crates/engine/src/prefs.rs | 5 + crates/engine/src/tests/prefs.rs | 31 +++++ 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/prefs_dialog.rs | 14 +++ crates/ui-egui/src/prefs_dialog/tests.rs | 38 +++++++ docs/development.md | 1 + docs/mcp.md | 5 + 38 files changed, 276 insertions(+), 18 deletions(-) diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index dddaf0a91e..a40eb0c92f 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -43,6 +43,16 @@ impl eframe::App for App { /// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the /// app's raw-input hook while the keyboard user is unconfined. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + // Without vsync, a main-window frame starts no sooner than the minimum interval after the + // last one. eframe runs this hook once per frame, shown or not, before egui reads the input. + // The frame's time moves on by the wait, and the hang report's frame time starts after it. + if raw.viewport_id == egui::ViewportId::ROOT { + if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) { + std::thread::sleep(wait); + raw.time = raw.time.map(|time| time + wait.as_secs_f64()); + } + self.last_frame_began = Some(std::time::Instant::now()); + } let _timed = BEACON.enter_timed(Stage::Input); self.frame_start = Some(std::time::Instant::now()); // winit gives the window its caption back when it changes the window's flags (maximize, diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 8a892a381a..5a1e5f08fb 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -141,6 +141,11 @@ struct App { display_profile: display_profile::Reader, /// When this frame's input hook started, for the hang report's frame times (`hang_watch`). frame_start: Option, + /// The shortest time between the starts of two frames, while the window presents without vsync + /// ([`presentation::min_frame_interval`]). + min_frame: Option, + /// When the last frame started, after its wait for [`Self::min_frame`]. + last_frame_began: Option, } /// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s. @@ -364,6 +369,10 @@ fn main() -> std::process::ExitCode { let saved_window = saved.as_ref().and_then(|ui| ui.window); #[cfg(feature = "wgpu")] let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str); + // Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off. + #[cfg(feature = "wgpu")] + let low_latency_drawing = + saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false); #[cfg(feature = "wgpu")] let power_env = eframe::wgpu::PowerPreference::from_env(); #[cfg(feature = "wgpu")] @@ -457,10 +466,11 @@ fn main() -> std::process::ExitCode { let mut options = options; // One frame queued, not two: the canvas is rasterized on the CPU and the GPU only // composites it, so the window answers the pointer a frame sooner (#444). - // `--present-mode` and `--frame-latency` change it for a launch (`presentation`). - options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY); + // `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing + // asks for no vsync when neither sets the mode (`presentation`). + options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing); // What the app asks for: the driver picks novsync's mode and may clamp the latency. - log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation)); + log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing)); // Only adapters that can show the window, in the order `gpu` gives (#306, #502). if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone())); @@ -507,6 +517,11 @@ fn main() -> std::process::ExitCode { // For the hang report (`hang_watch`). #[cfg(feature = "wgpu")] let requested_surface = options.wgpu_options.surface; + // Without vsync, frames start at most 240 times a second (`presentation`). + #[cfg(feature = "wgpu")] + let min_frame = presentation::min_frame_interval(&requested_surface); + #[cfg(not(feature = "wgpu"))] + let min_frame = None; // A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash. let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| { #[cfg(target_os = "linux")] @@ -692,6 +707,8 @@ fn main() -> std::process::ExitCode { monitors_listed: None, display_profile: Default::default(), frame_start: None, + min_frame, + last_frame_began: None, })) }), ) diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs index 3910984c93..0989254a21 100644 --- a/apps/vectorcraft/src/presentation.rs +++ b/apps/vectorcraft/src/presentation.rs @@ -6,9 +6,17 @@ //! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag //! overrides its variable; a value that isn't one of these stops the app with a message, as //! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`. -//! The surface the app asks for is logged at start-up. +//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at +//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the +//! surface presents without vsync, frames start at most 240 times a second. The surface the app +//! asks for is logged at start-up, with where its present mode came from. use std::ffi::OsString; +use std::time::Duration; + +/// The most frames a second the window draws while it presents without vsync. +#[cfg(feature = "wgpu")] +pub const UNSYNCED_FRAME_CAP: u32 = 240; /// A present mode the command line or the environment can ask for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -95,25 +103,44 @@ impl Overrides { Ok(Self { mode, latency }) } - /// `surface` with the overrides applied. + /// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and + /// no present mode override, the mode is `novsync`. #[cfg(feature = "wgpu")] - pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig { + pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig { use eframe::wgpu::PresentMode; let present_mode = match self.mode { Some(Mode::Fifo) => PresentMode::Fifo, Some(Mode::AutoVsync) => PresentMode::AutoVsync, Some(Mode::NoVsync) => PresentMode::AutoNoVsync, + None if low_latency_drawing => PresentMode::AutoNoVsync, None => surface.present_mode, }; eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) } } } -/// The present mode and frame latency `surface` asks for, for the start-up log: -/// "autovsync, frame latency 1", with "(override)" -/// after a value a flag or variable set. +/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the +/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it. #[cfg(feature = "wgpu")] -pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String { +pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option { + use eframe::wgpu::PresentMode; + match surface.present_mode { + PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP), + PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None, + } +} + +/// How long a frame waits before it starts, `since_last` after the previous frame started, so that +/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed). +pub fn frame_wait(min: Option, since_last: Option) -> Option { + min?.checked_sub(since_last?).filter(|wait| !wait.is_zero()) +} + +/// The present mode and frame latency `surface` asks for, for the start-up log: +/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and +/// "(preference)" after a present mode Low-Latency Drawing set. +#[cfg(feature = "wgpu")] +pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String { use eframe::wgpu::PresentMode; let mode = match surface.present_mode { PresentMode::AutoVsync => "autovsync", @@ -125,7 +152,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override }; let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); let tag = |set: bool| if set { " (override)" } else { "" }; - format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some())) + let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) }; + format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some())) } #[cfg(test)] @@ -223,20 +251,99 @@ mod tests { use eframe::wgpu::PresentMode; let app = SurfaceConfig::LOW_LATENCY; // No override: the surface the app asks for is unchanged. - assert_eq!(Overrides::default().apply(app), app); + assert_eq!(Overrides::default().apply(app, false), app); let latency = Overrides { mode: None, latency: Some(2) }; - let s = latency.apply(app); + let s = latency.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2))); - assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)"); + assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)"); let fifo = Overrides { mode: Some(Mode::Fifo), latency: None }; - let s = fifo.apply(app); + let s = fifo.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency)); // Never a mode the driver may lack: no vsync lets wgpu fall back by support. let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) }; - let s = novsync.apply(app); + let s = novsync.apply(app, false); assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3))); - assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)"); + assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)"); let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None }; - assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default"); + assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default"); + } + + /// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an + /// explicit Immediate or Mailbox; off, the app's surface is exactly its own. + #[cfg(feature = "wgpu")] + #[test] + fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let none = Overrides::default(); + assert_eq!(none.apply(app, false), app); + let s = none.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoNoVsync); + assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency); + let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string()); + assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}")); + // A latency override still applies with the preference's mode. + let latency = Overrides { mode: None, latency: Some(2) }; + let s = latency.apply(app, true); + assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2))); + assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)"); + } + + /// The flag and the variable each set the present mode over Low-Latency Drawing. + #[cfg(feature = "wgpu")] + #[test] + fn the_flag_and_the_variable_win_over_low_latency_drawing() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let flag = parse(&["--present-mode", "fifo"]).unwrap(); + let s = flag.apply(app, true); + assert_eq!(s.present_mode, PresentMode::Fifo); + assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true)); + let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap(); + let s = var.apply(app, true); + assert_eq!(s.present_mode, PresentMode::AutoVsync); + assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true)); + // The flag wins over the variable, and both over the preference. + let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap(); + assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo); + } + + /// Frames start at most 240 times a second without vsync, from the preference or an override, + /// and the display paces them with vsync. + #[cfg(feature = "wgpu")] + #[test] + fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() { + use eframe::egui_wgpu::SurfaceConfig; + use eframe::wgpu::PresentMode; + let app = SurfaceConfig::LOW_LATENCY; + let cap = Duration::from_secs(1) / 240; + assert_eq!(cap.as_nanos(), 4_166_666); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap)); + assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None); + assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None); + for (mode, capped) in [ + (PresentMode::Immediate, true), + (PresentMode::Mailbox, true), + (PresentMode::AutoNoVsync, true), + (PresentMode::Fifo, false), + (PresentMode::FifoRelaxed, false), + (PresentMode::AutoVsync, false), + ] { + let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) }; + assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}"); + } + } + + #[test] + fn a_frame_waits_out_the_rest_of_the_minimum_interval() { + let min = Some(Duration::from_millis(4)); + assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3))); + assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None); + assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None); + assert_eq!(frame_wait(min, None), None, "the first frame starts at once"); + assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync"); } } diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index b6c500749f..a2411e6ea4 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -365,6 +365,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("gpuPerformance", "Performance", "GPU Performance", "GPU Performance", bool), p!("animatedZoom", "Performance", "GPU Performance", "Animated Zoom", bool), p!("gpuPreference", "Performance", "GPU Performance", "Graphics Processor", choice(GPU_PREFERENCES)), + // Read by the desktop app at startup: the window presents without vsync, capped at 240 fps (#6013). + p!("lowLatencyDrawing", "Performance", "GPU Performance", "Low-Latency Drawing", bool), p!("historyStates", "Performance", "", "History States", int(5, 1000)), p!("realTimeDrawing", "Performance", "", "Real-time Drawing and Editing", bool), p!("renderThreads", "Performance", "", "Render Threads (-1 = Automatic)", int(-1, 64)), diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 86525e9214..ebee8b6e77 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -214,6 +214,10 @@ pub struct Prefs { /// runs on: a Wayland compositor may not show frames from another GPU (#502). Single-GPU /// machines are unaffected. pub gpu_preference: String, + /// The desktop app's window presents without vsync, with frames capped at 240 a second (#6013). + /// Read at startup (it takes effect after a restart); `--present-mode` and + /// `VECTORCRAFT_PRESENT_MODE` take precedence over it. + pub low_latency_drawing: bool, pub history_states: u32, pub real_time_drawing: bool, /// Rasterizer worker threads; -1 = automatic. @@ -503,6 +507,7 @@ impl Default for Prefs { gpu_performance: true, animated_zoom: true, gpu_preference: s("automatic"), + low_latency_drawing: false, history_states: 500, real_time_drawing: true, render_threads: -1, diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 521d2eabde..d093ddf7f0 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -447,6 +447,37 @@ fn gpu_preference_defaults_to_automatic_and_validates() { assert_eq!(s.prefs.gpu_preference, "automatic"); } +/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written +/// before it, a boolean only, kept through a save/load round trip, listed under Performance and +/// reset with it. +#[test] +fn low_latency_drawing_defaults_off_and_takes_only_a_boolean() { + let mut s = Session::new(); + assert!(!s.prefs.low_latency_drawing); + assert_eq!(s.execute("prefs.get", &json!({"key": "lowLatencyDrawing"})).unwrap(), json!(false)); + s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": true})).unwrap(); + assert!(s.prefs.low_latency_drawing); + for bad in [json!(1), json!(null), json!("on"), json!("yes"), json!([true])] { + assert!(s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": bad})).is_err(), "{bad}"); + assert!(s.prefs.low_latency_drawing); + } + // Booleans may be given as "true" and "false", as for every boolean preference. + s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "false"})).unwrap(); + assert!(!s.prefs.low_latency_drawing); + s.execute("prefs.set", &json!({"key": "lowLatencyDrawing", "value": "true"})).unwrap(); + assert_eq!(s.prefs.to_json()["lowLatencyDrawing"], json!(true)); + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert!(back.low_latency_drawing); + let old: Prefs = serde_json::from_value(json!({"gpuPerformance": true})).unwrap(); + assert!(!old.low_latency_drawing); + let l = s.execute("prefs.list", &json!({})).unwrap(); + let row = l.as_array().unwrap().iter().find(|e| e["key"] == "lowLatencyDrawing").unwrap().clone(); + assert_eq!(row["category"], "Performance"); + assert_eq!(row["label"], "Low-Latency Drawing"); + s.execute("prefs.reset", &json!({"category": "Performance"})).unwrap(); + assert!(!s.prefs.low_latency_drawing); +} + /// Performance › Linux Display Server (#1151): automatic by default, X11 by value or label, and /// anything else is an error that changes nothing. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..5c840c01fd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5270,6 +5270,7 @@ lighting Light Светлина @msg missing panel layout липсващо оформление на панели @msg unsupported native docking operation неподдържана вградена операция за скачване Linux Display Server Дисплейен сървър за Linux + Low-Latency Drawing Рисуване с ниско забавяне X11 (XWayland) When a Pen Is Attached X11 (XWayland) при свързана писалка If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Ако писалката на графичния таблет не рисува, изберете опция X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..0af7fea77a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4041,6 +4041,7 @@ theme Appearance Izgled Scroll Sideways with Cmd/Ctrl + Wheel Pomjeraj vodoravno uz Cmd/Ctrl + točkić miša Scrub Numeric Fields by Dragging Mijenjaj numerička polja prevlačenjem Linux Display Server Linux server prikaza + Low-Latency Drawing Crtanje s malim kašnjenjem Print Preview Pregled štampanja Print Setup Podešavanje štampe Bitmap Bitmapa diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..d378804a98 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2485,6 +2485,7 @@ digits Malayalam Malaiàlam Linked Files Fitxers enllaçats Links Enllaços Linux Display Server Servidor de pantalla de Linux + Low-Latency Drawing Dibuix de baixa latència Liquify Liquifica List Data Sets Llista els conjunts de dades List Folder Llista la carpeta diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..93f2b367ef 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4146,6 +4146,7 @@ theme Appearance Motiv Scroll Sideways with Cmd/Ctrl + Wheel Posouvat vodorovně kolečkem s Cmd/Ctrl Scrub Numeric Fields by Dragging Měnit číselné hodnoty tažením Linux Display Server Zobrazovací server Linuxu + Low-Latency Drawing Kreslení s nízkou latencí Print Preview Náhled tisku Print Setup Nastavení tisku Bitmap Bitmapa diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..4139d6ccf2 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6529,6 +6529,7 @@ theme Appearance Udseende Scroll Sideways with Cmd/Ctrl + Wheel Rul vandret med Cmd/Ctrl + musehjul Scrub Numeric Fields by Dragging Juster numeriske felter ved at trække Linux Display Server Linux-visningsserver + Low-Latency Drawing Tegning med lav latens Print Preview Udskriftsvisning Print Setup Udskriftsopsætning Bitmap Bitmap diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..ec06403260 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5677,6 +5677,7 @@ lighting Light Licht @msg missing panel layout Bedienfeldanordnung fehlt @msg unsupported native docking operation Nicht unterstützte native Docking-Operation Linux Display Server Linux-Anzeigeserver + Low-Latency Drawing Zeichnen mit geringer Latenz X11 (XWayland) When a Pen Is Attached X11 (XWayland), wenn ein Stift angeschlossen ist If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Wenn der Stift eines Grafiktabletts nicht zeichnet, wählen Sie eine Option mit X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..e4d5a3c752 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5549,6 +5549,7 @@ digits Malayalam Μαλαγιάλαμ @msg missing panel layout λείπει η διάταξη πινάκων @msg unsupported native docking operation μη υποστηριζόμενη εγγενής λειτουργία σύνδεσης πινάκων Linux Display Server Διακομιστής οθόνης Linux + Low-Latency Drawing Σχεδίαση χαμηλής καθυστέρησης Ruler Origin Αρχή χαράκων Reset Ruler Origin Επαναφορά αρχής χαράκων @msg the compressed file unpacks to more than VectorCraft reads ({_1} MB of document, {_2} MB per image) το αποσυμπιεσμένο αρχείο υπερβαίνει τα όρια ανάγνωσης του VectorCraft ({_1} MB ανά έγγραφο, {_2} MB ανά εικόνα) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..b38faef222 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5700,6 +5700,7 @@ lighting Light Luz @msg missing panel layout Falta la distribución de paneles @msg unsupported native docking operation Operación nativa de anclaje no admitida Linux Display Server Servidor de pantalla de Linux + Low-Latency Drawing Dibujo de baja latencia X11 (XWayland) When a Pen Is Attached X11 (XWayland) cuando hay un lápiz conectado If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Si el lápiz de una tableta digitalizadora no dibuja, elige una opción X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..d619a6fa6d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4070,6 +4070,7 @@ theme Appearance Ulkoasu Scroll Sideways with Cmd/Ctrl + Wheel Vieritä vaakasuunnassa Cmd/Ctrl + hiiren rullalla Scrub Numeric Fields by Dragging Muuta numerokenttiä vetämällä Linux Display Server Linuxin näyttöpalvelin + Low-Latency Drawing Pienen viiveen piirto Print Preview Tulostuksen esikatselu Print Setup Tulostusasetukset Bitmap Bittikartta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..a94c5e30f3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5681,6 +5681,7 @@ lighting Light Lumière @msg missing panel layout Disposition des panneaux manquante @msg unsupported native docking operation Opération native d’ancrage non prise en charge Linux Display Server Serveur d’affichage Linux + Low-Latency Drawing Dessin à faible latence X11 (XWayland) When a Pen Is Attached X11 (XWayland) quand un stylet est branché If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Si le stylet d’une tablette graphique ne dessine pas, choisissez une option X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..554a82f946 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2027,6 +2027,7 @@ Linked Files લિંક કરેલી ફાઇલો Links લિંક્સ Linux Display Server Linux ડિસ્પ્લે સર્વર + Low-Latency Drawing ઓછા વિલંબવાળું ડ્રોઇંગ Liquify લિક્વિફાઇ List Data Sets ડેટા સેટની યાદી List Folder ફોલ્ડરની યાદી diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..25b5b97386 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2733,6 +2733,7 @@ antiAlias Sharp शार्प Linked Files लिंक्ड फ़ाइलें Links लिंक Linux Display Server Linux डिस्प्ले सर्वर + Low-Latency Drawing कम विलंब वाली ड्राइंग Liquify लिक्विफ़ाई List Data Sets सूची डेटा सेट List Folder सूची फ़ोल्डर diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..013d9904cd 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2485,6 +2485,7 @@ file-filter Templates Sablonok Linked File Not Found A csatolt fájl nem található Links Csatolások Linux Display Server Linuxos megjelenítőszerver + Low-Latency Drawing Alacsony késleltetésű rajzolás Liquify Folyékony torzítás List Data Sets Adatkészletek listázása List Folder Mappa listázása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..7bce564f05 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3806,6 +3806,7 @@ theme Appearance Tampilan Scroll Sideways with Cmd/Ctrl + Wheel Gulir horizontal dengan Cmd/Ctrl + roda mouse Scrub Numeric Fields by Dragging Atur nilai kolom numerik dengan menyeret Linux Display Server Server tampilan Linux + Low-Latency Drawing Penggambaran latensi rendah Print Preview Pratinjau cetak Print Setup Pengaturan cetak Bitmap Bitmap diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..10e3522095 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5728,6 +5728,7 @@ lighting Light Luce @msg missing panel layout Disposizione dei pannelli mancante @msg unsupported native docking operation Operazione nativa di ancoraggio non supportata Linux Display Server Server di visualizzazione Linux + Low-Latency Drawing Disegno a bassa latenza X11 (XWayland) When a Pen Is Attached X11 (XWayland) quando è collegata una penna If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Se la penna di una tavoletta grafica non disegna, scegli un'opzione X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..f5be000313 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5771,6 +5771,7 @@ lighting Light ライト @msg missing panel layout パネル配置がありません @msg unsupported native docking operation ネイティブドッキング操作は未対応です Linux Display Server Linux ディスプレイサーバー + Low-Latency Drawing 低遅延描画 X11 (XWayland) When a Pen Is Attached ペン接続時は X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. ペンタブレットのペンで描画できない場合は、X11 (XWayland) のいずれかを選択してください。 X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..63e4aa4aa1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5785,6 +5785,7 @@ theme Appearance იერსახე Scroll Sideways with Cmd/Ctrl + Wheel ჰორიზონტალური გადაადგილება Cmd/Ctrl + ბორბლით Scrub Numeric Fields by Dragging რიცხვითი ველების შეცვლა გადათრევით Linux Display Server Linux-ის ეკრანის სერვერი + Low-Latency Drawing დაბალი დაყოვნების ხატვა Print Preview ნახვა ამობეჭდვამდე Print Setup ბეჭდვის მომართვა Bitmap ბიტმაპი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..4e55e36891 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5692,6 +5692,7 @@ lighting Light 광원 @msg missing panel layout 패널 레이아웃이 없습니다 @msg unsupported native docking operation 지원되지 않는 기본 도킹 작업 Linux Display Server Linux 디스플레이 서버 + Low-Latency Drawing 저지연 그리기 X11 (XWayland) When a Pen Is Attached 펜 연결 시 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 드로잉 태블릿의 펜으로 그려지지 않으면 X11 (XWayland) 옵션을 선택하세요. X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..b24a1d7b99 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4423,6 +4423,7 @@ theme Appearance Vormgeving Scroll Sideways with Cmd/Ctrl + Wheel Horizontaal scrollen met Cmd/Ctrl + muiswiel Scrub Numeric Fields by Dragging Numerieke velden aanpassen door te slepen Linux Display Server Linux-weergaveserver + Low-Latency Drawing Tekenen met lage latentie Print Preview Afdrukvoorbeeld Print Setup Afdrukinstellingen Bitmap Bitmap diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..ce5f020e5c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4009,6 +4009,7 @@ theme Appearance Wygląd Scroll Sideways with Cmd/Ctrl + Wheel Przewijaj w poziomie kółkiem z Cmd/Ctrl Scrub Numeric Fields by Dragging Zmieniaj pola liczbowe przeciąganiem Linux Display Server Serwer wyświetlania Linux + Low-Latency Drawing Rysowanie z niskim opóźnieniem Print Preview Podgląd wydruku Print Setup Ustawienia wydruku Bitmap Bitmapa diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..fe9341cd37 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5735,6 +5735,7 @@ liquify-list-end {0}, {1} {0} e {1} Right Diagonal Diagonal Direita Left Diagonal Diagonal Esquerda Linux Display Server Servidor de Exibição do Linux + Low-Latency Drawing Desenho de Baixa Latência X11 (XWayland) When a Pen Is Attached X11 (XWayland) Quando Houver uma Caneta Conectada If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Se a caneta de uma mesa digitalizadora não desenhar, escolha uma opção X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..739c767ffa 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5726,6 +5726,7 @@ lighting Light Свет @msg missing panel layout Отсутствует расположение панелей @msg unsupported native docking operation Неподдерживаемая собственная операция прикрепления Linux Display Server Дисплейный сервер Linux + Low-Latency Drawing Рисование с низкой задержкой X11 (XWayland) When a Pen Is Attached X11 (XWayland) при подключенном пере If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Если перо графического планшета не рисует, выберите вариант X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..d71c308793 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5604,6 +5604,7 @@ lighting Light Ljus @msg missing panel layout panellayout saknas @msg unsupported native docking operation inbyggd dockningsåtgärd som inte stöds Linux Display Server Linux-skärmserver + Low-Latency Drawing Ritning med låg latens X11 (XWayland) When a Pen Is Attached X11 (XWayland) när en penna är ansluten If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Om ritplattans penna inte ritar väljer du ett X11 (XWayland)-alternativ. X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..87069d01dc 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5463,6 +5463,7 @@ lighting Light Işık @msg missing panel layout eksik panel düzeni @msg unsupported native docking operation desteklenmeyen yerel yerleştirme işlemi Linux Display Server Linux Görüntü Sunucusu + Low-Latency Drawing Düşük Gecikmeli Çizim X11 (XWayland) X11 (XWayland) Ruler Origin Cetvelin Kökeni Reset Ruler Origin Cetvel Başlangıç Noktasını Sıfırla diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..f26d454780 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5708,6 +5708,7 @@ lighting Light Світло @msg missing panel layout Відсутнє розташування панелей @msg unsupported native docking operation Непідтримувана власна операція прикріплення Linux Display Server Дисплейний сервер Linux + Low-Latency Drawing Малювання з низькою затримкою X11 (XWayland) When a Pen Is Attached X11 (XWayland), коли підключено перо If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Якщо перо графічного планшета не малює, виберіть варіант X11 (XWayland). X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..905d4ef964 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2319,6 +2319,7 @@ digits Hindi Hindi Linked File Not Found Không tìm thấy tệp liên kết Links Liên kết Linux Display Server Máy chủ hiển thị Linux + Low-Latency Drawing Vẽ độ trễ thấp Liquify Lỏng hóa List Data Sets Liệt kê tập dữ liệu List Folder Liệt kê thư mục diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..2245137ca8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5985,6 +5985,7 @@ lighting Light 光源 Horizontal Guide 水平参考线 Move Guide to Layer 将参考线移至图层 Linux Display Server Linux 显示服务器 + Low-Latency Drawing 低延迟绘图 X11 (XWayland) When a Pen Is Attached 连接手写笔时使用 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 如果数位板的笔无法绘画,请选择一个 X11 (XWayland) 选项。 X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..855f3a6988 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5821,6 +5821,7 @@ lighting Light 光源 Horizontal Guide 水平參考線 Move Guide to Layer 將參考線移至圖層 Linux Display Server Linux 顯示伺服器 + Low-Latency Drawing 低延遲繪圖 X11 (XWayland) When a Pen Is Attached 連接觸控筆時使用 X11 (XWayland) If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. 如果繪圖板的筆無法繪圖,請選擇一個 X11 (XWayland) 選項。 X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index e8a6368cbb..1b3f72ef7f 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -72,6 +72,7 @@ fn settings() -> impl Iterator { "appTitleBar" => APP_TITLE_BAR_SHOWN, "linuxDisplayServer" => DISPLAY_SERVER_CHOICE, "monitorProfileDisplay" => !cfg!(target_arch = "wasm32"), + "lowLatencyDrawing" => !cfg!(target_arch = "wasm32"), _ => true, }; let prefs = @@ -660,6 +661,9 @@ fn category_fields(ui: &mut egui::Ui, app: &mut VectorcraftApp, d: &mut Dialog, ui.label(egui::RichText::new(note).color(t.text_dim).size(11.0)); } } + // The desktop app only: it sets the window's present mode when it starts, so a note + // says the change applies at the next start. + PrefKind::Bool if sp.key == "lowLatencyDrawing" => desktop_startup_bool_row(ui, d, sp.key, sp.label, &t), PrefKind::Bool => bool_row(ui, d, sp.key, sp.label), PrefKind::Num { min, max, unit } => { labeled(ui, sp.label, |ui, label_id| { @@ -883,6 +887,16 @@ fn bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { } } +/// A checkbox the desktop app reads once, when it starts (Performance › Low-Latency Drawing, which +/// sets the window's present mode), with its restart note. The web build doesn't show it. +fn desktop_startup_bool_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, t: &Tokens) { + if cfg!(target_arch = "wasm32") { + return; + } + bool_row(ui, d, key, label); + ui.label(egui::RichText::new(tl!("Applies the next time VectorCraft starts.")).color(t.text_dim).size(11.0)); +} + fn labeled(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui, egui::Id)) { let t = Tokens::get(ui.ctx()); ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 3ecf868532..4bfacc4751 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -512,6 +512,44 @@ fn graphics_processor_preference_shows_and_persists() { assert_eq!(saved["engine_prefs"]["gpuPreference"], json!("highPerformance")); } +/// Performance › Low-Latency Drawing (#6013): shown off with its restart note, applied by OK, +/// saved with the UI state under the key the desktop app reads before the window opens, and every +/// bundled language translates its label. +#[test] +fn low_latency_drawing_preference_shows_and_persists() { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut a = app(); + open(&mut a, Some("Performance")); + assert_eq!(a.ui.dialog.as_ref().unwrap().fields.get("lowLatencyDrawing"), Some(&json!(false))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut a, ui.ctx())); + out.textures_delta.clear(); + let mut shown = vec![]; + out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); + let at = shown.iter().position(|t| t == "Low-Latency Drawing").unwrap_or_else(|| panic!("{shown:?}")); + // The note is the row's own: it comes before the next row's label. + let next = shown[at..].iter().position(|t| t.starts_with("History States")).map(|n| at + n).unwrap_or_else(|| panic!("{shown:?}")); + assert!(shown[at..next].iter().any(|t| t == "Applies the next time VectorCraft starts."), "{shown:?}"); + a.ui.dialog.as_mut().unwrap().fields.insert("lowLatencyDrawing".into(), json!(true)); + confirm(&mut a).unwrap(); + assert!(a.take_prefs_changed(), "OK asks the host to write the preferences file"); + assert!(a.session.prefs.low_latency_drawing); + let saved: Value = serde_json::from_slice(&serde_json::to_vec(&a.ui).unwrap()).unwrap(); + assert_eq!(saved["engine_prefs"]["lowLatencyDrawing"], json!(true)); + for lang in crate::i18n::Lang::all().filter(|l| l.code() != crate::i18n::Lang::EN.code()) { + assert!(crate::i18n::has(lang, "Low-Latency Drawing"), "{}", lang.code()); + } +} + /// User Interface › System Title Bar: shown with its next-launch note, applied by OK and /// saved with the UI state under the key the desktop app reads before the window opens. #[test] diff --git a/docs/development.md b/docs/development.md index 64b66678b5..14ee5dd9f9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -84,6 +84,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU ( - On Linux with Mesa, `MESA_VK_DEVICE_SELECT=10de:2f04!` (vendor:device as `vulkaninfo --summary` or `lspci -nn` show it) leaves only that GPU to Vulkan, and `DRI_PRIME=1` picks the other GPU. - Help › About and the control channel's `ui.inspect` (`graphicsAdapter`) show the adapter in use, and the app logs it at startup. - **How frames reach the display.** By default the window presents with `autovsync` and lets the display queue one frame. With `autovsync`, wgpu uses relaxed vsync (FifoRelaxed, which tears a frame that arrives late) where the driver offers it, else vsync (Fifo). For a launch, `--present-mode` (or `VECTORCRAFT_PRESENT_MODE`) sets the present mode to `fifo` (vsync), `autovsync` or `novsync` (wgpu uses Immediate, else Mailbox, else Fifo, whichever the driver offers), and `--frame-latency` (or `VECTORCRAFT_FRAME_LATENCY`) sets the frames the display may queue, `1` to `3`. A flag overrides its variable, and a value that is not one of these stops the app with a message. On Windows and Linux, a launch with either one set opens its files in a new window, as with `--new-instance`, instead of handing them to a running VectorCraft. At startup the log records what the app asks the window surface for, for example `requested window surface: autovsync, frame latency 2 (override)`. The driver chooses the mode that `autovsync` and `novsync` resolve to and may clamp the latency, and on macOS egui uses at least 2 frames while the window is being resized. The code is `apps/vectorcraft/src/presentation.rs`. +- **Preferences › Performance › Low-Latency Drawing** (`lowLatencyDrawing`, off by default) presents with `novsync` and is read when the app starts, so a change applies after a restart. The present mode comes from `--present-mode` first, then `VECTORCRAFT_PRESENT_MODE`, then this preference, then the default (`autovsync`); `--frame-latency` and `VECTORCRAFT_FRAME_LATENCY` still set the latency with it on. The log names where the mode came from: `requested window surface: novsync (preference), frame latency 1`. Whenever the window presents without vsync (`novsync`, from the preference or an override), frames start at most 240 times a second (about 4.17 ms apart); with vsync the display paces them and no cap applies. ## Logs diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..4bdcc0cbb2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6845,6 +6845,11 @@ is converted on its own. osManaged}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, `pending` or `unsupported`, `applied` says whether the canvas is converted, and `reason` says why not. +`lowLatencyDrawing` (Preferences › Performance › Low-Latency Drawing, off by default; desktop app) is read when the app +starts. On, the window presents without vsync (wgpu's `AutoNoVsync`) and frames start at most 240 times a second. +`--present-mode` and `VECTORCRAFT_PRESENT_MODE` take precedence over it (see `docs/development.md` › Desktop graphics +processor). A value that is not a boolean is an error. + `ctrlWheelScrollsSideways` (on by default): on, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming while `zoomWithMouseWheel` is off; off, Cmd/Ctrl-wheel zooms about the pointer. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer. Under either From dec50251477c0c0906174e75f5bf044a0b97bf08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 01:12:03 -0800 Subject: [PATCH 086/138] Fix #8034: review fixes for pattern swatches from another document MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - swatch.library.add lists a library pattern swatch that stands for a swatch added earlier in the same call under existing, not twice under added. - An empty library file (.gpl, .ase, .vcswatches) loads as an empty library again; only a document with no swatches is refused. A PostScript file whose swatches are only the default ones is refused like a .ai or .eps. - The Swatch Libraries filter of Other Library… also lists .ait and .epsf files. - The library panel finds a loaded library's pattern swatch by looking only at libraries that have pattern swatches. - The Czech message for Copy to User Defined names pattern swatches. - Color spelling in the new params text and comments; docs/mcp.md rewrapped. --- crates/engine/src/cmd/fileio/tests.rs | 2 +- .../engine/src/cmd/fileio/tests_aiimport.rs | 22 ++++-- crates/engine/src/cmd/swatchlib.rs | 67 ++++++++++--------- crates/engine/src/tests/swatchlib.rs | 28 ++++++++ crates/ui-egui/src/i18n/cs.tsv | 2 +- docs/mcp.md | 12 ++-- docs/target-app-parity.md | 2 +- 7 files changed, 89 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 7ae78cb853..f3161c229d 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -497,7 +497,7 @@ fn library_open_filters_list_library_formats_first() { #[test] fn the_swatch_library_filter_lists_ai_and_eps_files() { let filters: Vec<_> = library_open_filters("Swatch libraries", crate::cmd::swatchlib::LIBRARY_PICK_EXTS).collect(); - for ext in ["ai", "eps", "ase", "gpl", "acb", "vcswatches"] { + for ext in ["ai", "ait", "eps", "epsf", "ase", "gpl", "acb", "vcswatches"] { assert!(filters[0].1.contains(&ext), "{ext}: {:?}", filters[0]); } assert_eq!(filters.iter().filter(|f| f.0 == "Swatch libraries").count(), 1, "{filters:?}"); diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index e3ff266b9d..0766771e94 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -491,22 +491,34 @@ fn a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks() { std::fs::remove_dir_all(&dir).ok(); } -/// A `.ai` file without a palette of its own, and a library file with no swatches, are refused as +/// A `.ai` file without a palette of its own, and a document with no swatches, are refused as /// swatch libraries with a message, not listed as the default swatches or as an empty library. A -/// damaged `.ai` is refused with the reader's error, and neither is listed. +/// damaged `.ai` is refused with the reader's error, and none of them is listed. A library file +/// with no swatches loads as an empty library. #[test] -fn swatch_library_files_without_swatches_or_damaged_are_refused() { +fn swatch_library_documents_without_swatches_or_damaged_are_refused() { let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.edit("Clear", |d, _| { + d.swatches.clear(); + d.swatch_groups.clear(); + Ok(()) + }) + .unwrap(); + let b64 = s.execute("document.serialize", &json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string(); + let e = s.execute("swatch.library.load", &json!({"dataBase64": b64, "name": "Bare.vectorcraft"})).unwrap_err().to_string(); + assert!(e.contains("`Bare.vectorcraft` has no swatches of its own"), "{e}"); let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)))); let p = json!({"dataBase64": vectorcraft_format::base64_encode(&ai::ai(&compressed(data.as_bytes()), "1 0 0 rg 10 50 30 40 re f")), "name": "art.ai"}); let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); assert!(e.contains("`art.ai` has no swatches of its own"), "{e}"); - let e = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap_err().to_string(); - assert!(e.contains("`Empty.gpl` has no swatches of its own"), "{e}"); let damaged = json!({"data": "%PDF-1.4\n%damaged\n", "name": "damaged.ai"}); assert!(s.execute("swatch.library.load", &damaged).is_err()); let list = s.execute("swatch.library.list", &json!({})).unwrap(); assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "loaded"), "{list}"); + // A library file without swatches still loads, as an empty library. + let r = s.execute("swatch.library.load", &json!({"data": "GIMP Palette\nName: Empty\n#\n", "name": "Empty.gpl"})).unwrap(); + assert_eq!(r["count"], json!(0), "{r}"); } /// Other Library… on a `.ai` graphic style library (art styles, their list and no layers) gives the diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index a6894ecb4d..777b58e8ae 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Other Library…", ["Window", "Swatch Libraries"], None, - "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and colour groups; swatch.library.add brings a pattern swatch's pattern with it. A file with no swatches is an error, and so is a .ai or .eps whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}", + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}", always, load ), @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Copy to User Defined", ["Window", "Swatch Libraries"], None, - "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused: a .vcswatches file can't hold them). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", + "{library: id or name of a loaded library (category \"loaded\", swatch.library.load)} copy it into the user library folder of the desktop app, whose libraries VectorCraft lists as User Defined every time it starts (a loaded library is listed until the app quits): a library file as it is, the swatches of a document or a library loaded from data as a .vcswatches file (a library with pattern swatches is refused). A name the folder already has gets a number (\"Brand 2.ase\") and no file is replaced; when the folder already holds the same file, that file is used. The library is then listed as User Defined only, and until the app quits commands given its loaded id use the copy; a User Defined library comes back as it is → {library: its User Defined id, name, count, path (left out when it is outside the read roots), copied: false when nothing was written}", has_user_folder, copy_to_user ), @@ -153,8 +153,8 @@ impl LibraryFile for SwatchLibrary { pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb"]; /// The extensions the Swatch Libraries filter of Other Library… lists: the library files, and the -/// `.ai` and `.eps` documents whose swatches load as a library (`swatch.library.load`). -pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "eps"]; +/// `.ai`, `.ait` and `.eps` (`.epsf`) documents whose swatches load as a library (`swatch.library.load`). +pub const LIBRARY_PICK_EXTS: &[&str] = &["vcswatches", "gpl", "ase", "acb", "ai", "ait", "eps", "epsf"]; impl Libraries { /// Keep `doc`, the document loaded library `id` was read from, for its pattern swatches; `None` @@ -172,12 +172,15 @@ impl Libraries { } /// The document holding the pattern of swatch `w`, when `w` is one of a loaded library's own - /// pattern swatches (a library panel draws them from it). + /// pattern swatches (a library panel draws them from it). Only the libraries that have pattern + /// swatches are looked at, each by the address ranges of its swatch lists. pub fn pattern_source(&self, w: &Swatch) -> Option> { let Paint::Pattern { pattern, .. } = &w.paint else { return None }; - let own = |lib: &SwatchLibrary| lib.iter().any(|s| std::ptr::eq(s, w)); - let e = self.extra.iter().find(|e| own(&e.lib))?; - self.pattern_doc(&e.info.id).filter(|d| d.pattern(pattern).is_some()) + let at = std::ptr::from_ref(w); + let holds = |v: &[Swatch]| v.as_ptr_range().contains(&at); + let own = |lib: &SwatchLibrary| holds(&lib.swatches) || lib.groups.iter().any(|g| holds(&g.swatches)); + let (_, doc) = self.pattern_docs.iter().find(|(id, _)| self.extra.iter().any(|e| e.info.id == **id && own(&e.lib)))?; + Some(doc.clone()).filter(|d| d.pattern(pattern).is_some()) } } @@ -780,26 +783,22 @@ fn load(s: &mut Session, p: &Value) -> Result { let mut patterns = None; let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| { // A library file, or a document whose swatches become the library. - let lib = if palette_io::sniff_bytes(bytes) { - palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))? - } else { - let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; - if loaded.preview_only { - return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); - } - // A `.ai` or EPS file without a palette of its own opens with the default swatches. - if matches!(loaded.format.id, "ai" | "ait" | "eps") && has_only_default_swatches(&loaded.doc) { - return Err(bad(C, format!("`{file}` has no swatches of its own"))); - } - let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; - if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) { - patterns = Some(Arc::new(loaded.doc)); - } - lib - }; - if lib.is_empty() { + if palette_io::sniff_bytes(bytes) { + return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)); + } + let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?; + if loaded.preview_only { + return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); + } + // A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches. + let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc); + let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; + if defaults || lib.is_empty() { return Err(bad(C, format!("`{file}` has no swatches of its own"))); } + if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) { + patterns = Some(Arc::new(loaded.doc)); + } Ok(lib) })?; if info.category == "loaded" { @@ -808,7 +807,7 @@ fn load(s: &mut Session, p: &Value) -> Result { Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) } -/// `d`'s swatches and colour groups are exactly the default ones of a colour mode, as a new +/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new /// document's are. fn has_only_default_swatches(d: &vectorcraft_doc::Document) -> bool { use vectorcraft_color::cms::Model; @@ -962,8 +961,10 @@ fn add(s: &mut Session, p: &Value) -> Result { let added: Vec<(String, String)> = if fresh.is_empty() { vec![] } else { - s.edit("Add to Swatches", |d, _| { + let (added, reused) = s.edit("Add to Swatches", |d, _| { let mut out = vec![]; + // Library pattern swatches that stand for a swatch added earlier in this call. + let mut reused = vec![]; // Each library group goes into one document group: the group of that name the document // already had, or one made here. let before = d.swatch_groups.len(); @@ -973,11 +974,11 @@ fn add(s: &mut Session, p: &Value) -> Result { let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { // The pattern comes with its swatch; a pattern the document has without one // gets one. The swatch a pattern that comes in brings is named after the pattern: - // it takes the library swatch's name and colour group instead. + // it takes the library swatch's name and color group instead. let had = taken_names(d); let target = patternlib::import(d, src, pattern)?; if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { - out.push((w.name.clone(), name)); + reused.push((w.name.clone(), name)); taken = taken_names(d); continue; } @@ -1022,8 +1023,10 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } - Ok(out) - })? + Ok((out, reused)) + })?; + existing.extend(reused); + added }; let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::>(); let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)}); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index f44266b9de..3890e2b204 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -341,6 +341,34 @@ fn another_documents_pattern_swatches_of_one_pattern_add_as_separate_swatches() assert_eq!(again["added"], json!([]), "{again}"); } +/// A library swatch named after its pattern, added in one call after another swatch of that pattern +/// with the same placement, stands for the swatch just added: it is listed as existing, not added +/// again. +#[test] +fn a_pattern_swatch_named_after_its_pattern_reuses_one_added_in_the_same_call() { + use std::sync::Arc; + let mut s = session(); + s.edit("Pattern", |d, _| { + let path = vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)); + let dot = vectorcraft_doc::Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::default_art()); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Dots", vec![Arc::new(dot)]) }); + for name in ["Tiles", "Dots"] { + let paint = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + d.swatches.push(vectorcraft_color::Swatch { name: name.into(), paint, global: false, spot: false }); + } + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Dots"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Tiles"]), &json!(["Tiles"])), "{r}"); + let d = doc(&s); + assert_eq!(d.swatches_iter().filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Dots")).count(), 1, "{r}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b19042c023..7429d2826e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8229,7 +8229,7 @@ breakText Glyphs Glyfy @msg `{id}` is no writable format (see document.formats) `{id}` není formát, který lze zapisovat (viz document.formats) @msg `{id}` isn't a loaded library `{id}` není načtená knihovna @msg `{file}` has no swatches of its own `{file}` nemá žádné vlastní vzorky -@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` obsahuje vzorky, které soubor .vcswatches nepojme +@msg `{_1}` has pattern swatches, which a .vcswatches file can't hold `{_1}` obsahuje vzorkové položky vzorníku, které soubor .vcswatches nepojme @msg `{key}` has no colours `{key}` neobsahuje žádné barvy @msg `{key}` holds more than {MAX_EDIT_WORDS} words `{key}` obsahuje více než {MAX_EDIT_WORDS} slov @msg `{key}` is a design name `{key}` je název návrhu diff --git a/docs/mcp.md b/docs/mcp.md index 851d7c8871..5b95d199e5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4889,14 +4889,14 @@ them as process colors; `.acb` files are read, never written. A file in the user same extension and bytes as one there, loads as that User Defined library (category `user`). From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and -art, into the document as a pattern swatch under the library swatch's name and in its color group. A file with no -swatches, and a `.ai` or `.eps` file whose swatches are only the default ones, are refused with -"`` has no swatches of its own". The Swatch Libraries filter of Other Library… lists `.ai` and `.eps` files -as well as the library files. +art, into the document as a pattern swatch under the library swatch's name and in its color group. A document with +no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with +"`` has no swatches of its own". The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` +(`.epsf`) files as well as the library files. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` -as `.vcswatches`; a library with pattern swatches is refused, since a `.vcswatches` file can't hold them) under a name no file there has, and lists it as User Defined from then on; until the app -quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` +as `.vcswatches`; a library with pattern swatches is refused) under a name no file there has, and lists it as User +Defined from then on; until the app quits, commands given its loaded id use the copy → `{library, name, count, path, copied}` (`copied: false` when the folder already held the same file). Without a user library folder the command is disabled. These commands refuse a parameter of the wrong form with an error that names it: `library`, `apply`, `path`, `data`, `dataBase64`, `format` and `name` must be strings, `names` must be a list of names, and `focus`, `replace` and `user` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1e57a1d692..3524a73af9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1862,7 +1862,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A file with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_files_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From 68685ab2f18d255bfbdf8e2310176579b70fa3ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 02:20:08 -0800 Subject: [PATCH 087/138] Recolor Artwork: Save Changes and OK keep each swatch with its row and excluded rows' colors - With art in some of the group's colors, a second Save Changes after another edit of a row kept the color the first save gave that row's swatch, and OK gave the group's colors by row order, which could overwrite a swatch no row lists. Both now match each swatch to its row, also through the color that row listed when an earlier save gave the swatch its color. - An excluded row leaves its swatch its own color at Save Changes and at OK, with or without art. `recolor.apply` takes "keep" in `groupColors` for a swatch that keeps its color without the Global Adjust. - `swatch.editGroup` given the color keys of the group's own colors keeps those colors unrounded and records no undo step. --- crates/engine/src/cmd/recolor.rs | 20 ++- crates/engine/src/cmd/swatch.rs | 15 +- crates/engine/src/tests/recolor.rs | 11 ++ crates/engine/src/tests/swatchcmds.rs | 29 ++++ crates/ui-egui/src/dialogs/recolor.rs | 188 ++++++++++++++++++++++---- docs/mcp.md | 14 +- docs/target-app-parity.md | 2 +- 7 files changed, 244 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 566a87b22f..8cba055c9f 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -1680,12 +1680,26 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(Value::Array(cs)) => Some(cs), Some(_) => return Err(bad(C, "`groupColors` must be an array")), }; - // A null in groupColors removes the group's swatch at its place. + // A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch + // at its place its color, without the Global Adjust. + let own: Vec> = match group { + Some(g) => { + s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default() + } + None => vec![], + }; let new: Vec> = match group_colors { Some(cs) => cs .iter() - .map(|v| match v { + .enumerate() + .map(|(i, v)| match v { Value::Null => Ok(None), + // Past the group's swatches it adds nothing. + Value::String(k) if k == "keep" => match own.get(i) { + Some(Some(c)) => Ok(Some(*c)), + Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))), + None => Ok(None), + }, v => color_value(v) .map(|c| adjust.apply(c)) .map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 088c7d74c5..b66442a47f 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Edit Color Group", ["Window", "Swatches"], None, - "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", + "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; a null removes the swatch at that place; built-in swatches can't change; a color the swatch already has keeps its model, and a key that names the swatch's color, rounded to the key's steps, keeps the swatch's color unrounded), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", has_doc, swatch_edit_group ), @@ -1326,13 +1326,22 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result { .map(|v| if v.is_null() { Ok(None) } else { color_value(v).map(Some).ok_or_else(|| bad(C, format!("bad colour {v}"))) }) .collect::>()?; super::paint::check_keep_model(p, C)?; - // A color its swatch already has keeps its model. The others take the document's. + // A color its swatch already has keeps its model. The others take the document's. A color key + // (`recolor.colors`) names a color rounded to its steps, so a key of the swatch's own color + // gives the swatch that color, unrounded. let old: Vec> = s.doc()?.doc.swatch_groups.iter().find(|g| g.name == group).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default(); + let entries = p.get("colors").and_then(Value::as_array); + let is_key = |i: usize| entries.and_then(|a| a.get(i)).and_then(Value::as_str).and_then(vectorcraft_color::recolor::ColorKey::parse); let mut colors: Vec> = colors .into_iter() .enumerate() - .map(|(i, c)| c.map(|c| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) })) + .map(|(i, c)| { + c.map(|c| match old.get(i).copied().flatten() { + Some(o) if o == c || is_key(i).is_some_and(|k| k == vectorcraft_color::recolor::ColorKey::of(&o)) => o, + _ => super::paint::new_color(s, p, c), + }) + }) .collect(); // A null past the group's swatches removes nothing. while colors.len() > old.len() && colors.last() == Some(&None) { diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 8a950fcbb3..11c3418ff3 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -489,6 +489,17 @@ fn edit_group_relinks_art_and_apply_rewrites_the_group_with_the_art() { run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["#010203", "cmyk 0 0 0 20"]})); let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::>(), [Color::rgb8(1, 2, 3), Color::cmyk(0.0, 0.0, 0.0, 0.2)]); + // "keep" leaves a swatch its color, without the Global Adjust that the other colors take. + let adjust = json!({"brightness": -50}); + run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "#ffffff"], "globalAdjust": adjust})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + let colors: Vec = g.swatches.iter().map(|w| w.paint.color().unwrap()).collect(); + assert_eq!(colors[0], Color::rgb8(1, 2, 3)); + assert_ne!(colors[1].to_hex(), "#ffffff", "the other color takes the Global Adjust"); + // Past the group's swatches it adds nothing. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Theme", "groupColors": ["keep", "keep", "keep"]})); + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Theme").unwrap().clone(); + assert_eq!(g.swatches.iter().map(|w| w.paint.color().unwrap()).collect::>(), colors); } /// Art linked to a global swatch of the group that `recolor.apply` rewrites stays linked when the diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index 03ab5fdbe2..306d6b71ad 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -445,6 +445,35 @@ fn edit_color_group_with_its_own_colors_records_no_undo_step() { assert_eq!(undo_len(&s), undo + 2, "a new name is a step"); } +/// `swatch.editGroup` with the color keys of the group's own colors records no undo step when a +/// color lies between the keys' steps, and a rename keeps that color unrounded; a color given as a +/// value is taken as it is. +#[test] +fn edit_color_group_with_its_own_color_keys_keeps_the_colors() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Mine", "colors": [{"c": 60.005, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true})); + let colors = |s: &Session| -> Vec { + doc(s).swatch_groups.iter().find(|g| g.name == "Mine" || g.name == "Yours").unwrap().swatches.iter().filter_map(|w| w.paint.color()).collect() + }; + let own = colors(&s); + let keys: Vec = own.iter().map(|c| vectorcraft_color::recolor::ColorKey::of(c).to_string()).collect(); + assert_ne!(crate::cmd::color_value(&json!(keys[0])), Some(own[0]), "the key rounds the color"); + let undo = undo_len(&s); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys})); + assert_eq!(undo_len(&s), undo, "the group's own colors record no step"); + run(&mut s, "swatch.editGroup", json!({"group": "Mine", "colors": keys, "rename": "Yours"})); + assert_eq!(undo_len(&s), undo + 1, "a new name is a step"); + assert_eq!(colors(&s), own, "the colors are kept unrounded"); + // A color given as a value, not a key, is taken exactly, also within a key's step. + let Color::Cmyk { c, .. } = own[0] else { panic!("a CMYK swatch: {:?}", own[0]) }; + let nudged = Color::cmyk(c - 0.000_002, 0.0, 0.0, 0.0); + assert_eq!(vectorcraft_color::recolor::ColorKey::of(&nudged), vectorcraft_color::recolor::ColorKey::of(&own[0])); + let p = json!({"group": "Yours", "colors": [{"c": c - 0.000_002, "m": 0, "y": 0, "k": 0}, "#00ff00"], "keepModel": true}); + run(&mut s, "swatch.editGroup", p); + assert_eq!(undo_len(&s), undo + 2, "a new value is a step"); + assert_eq!(colors(&s)[0], nudged); +} + #[test] fn edit_color_group_with_a_null_removes_that_swatch() { let mut s = session(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 42e42eb768..f3c0dde0bf 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -519,6 +519,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.remove(THEME_DONE); d.fields.remove(SAVED_ROWS); d.fields.remove(SAVED_COLORS); + d.fields.remove(SWATCH_ROWS); if art { // The art is reduced again (`sync`) into a row per color of the group. d.fields.insert("colors".into(), json!(assign.len().max(1))); @@ -573,31 +574,48 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, // then the colors added on the Edit tab; a row made with New Row that holds no current // colors gives the group no color. + // An excluded row leaves its swatch its own color. let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); let rest: Vec = p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); - let mut colors: Vec = filled.iter().filter_map(|r| saved_color(app, d, r)).chain(group_colors(app, d, rest.iter())).collect(); + let assign: Vec = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).cloned().unwrap_or_default(); + let mut colors: Vec = filled + .iter() + .enumerate() + .filter_map(|(i, r)| if excluded(r) { kept_color(&assign, i, r).cloned() } else { saved_color(app, d, r) }) + .chain(group_colors(app, d, rest.iter())) + .collect(); cancel_preview(app, d); - // With art in a color of the group, the group keeps its swatch order: a swatch whose color - // a row lists takes that row's new color (its own color when the row is excluded), so the - // art linked to it takes the color its row shows, and every other swatch keeps its color. - // The colors added on the Edit tab follow. + // With art in a color of the group, the group keeps its swatch order: a swatch whose row + // ([`swatch_row`]) is found takes that row's new color (its own color when the row is + // excluded), so the art linked to it takes the color its row shows, and every other + // swatch keeps its color. The colors added on the Edit tab follow. let own: Vec = doc_groups(app) .into_iter() .find(|(n, _)| group.as_deref() == Some(n.as_str())) .map(|g| g.1.iter().map(key).collect()) .unwrap_or_default(); - let row_of = |k: &Value| row_listing(&rs, k); - if d.bool("__art") && own.iter().any(|k| row_of(k).is_some()) { + let found: Vec> = (0..own.len()).map(|i| swatch_row(d, &rs, &own, i)).collect(); + let mut links = None; + if d.bool("__art") && found.iter().any(Option::is_some) { let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r) && !r["to"].is_null()); - colors = own - .iter() - .map(|k| match row_of(k) { - Some(r) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), + let mut saved_links = vec![]; + colors = vec![]; + for (k, f) in own.iter().zip(&found) { + let c = match f { + Some((_, r)) if !excluded(r) => saved_color(app, d, r).unwrap_or_else(|| k.clone()), _ => k.clone(), - }) - .chain(group_colors(app, d, added)) - .collect(); + }; + // A removed swatch leaves the saved group. + if !c.is_null() { + saved_links.push(f.as_ref().map_or(Value::Null, |f| f.0.clone())); + } + colors.push(c); + } + let added = group_colors(app, d, added); + saved_links.extend(added.iter().map(|_| Value::Null)); + colors.extend(added); + links = Some(saved_links); } let before = art_colors(app); let r = app.run("swatch.editGroup", json!({"group": group, "colors": colors, "keepModel": true, "rename": p["rename"]}))?; @@ -637,6 +655,10 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res .map(|g| g.1.iter().map(key).collect()) .unwrap_or_default(); d.fields.insert("__assign".into(), Value::Array(saved)); + match links { + Some(l) => d.fields.insert(SWATCH_ROWS.into(), Value::Array(l)), + None => d.fields.remove(SWATCH_ROWS), + }; // The saved group holds the Global Adjust: the rows' new colors take it, and it goes // back to 0%, so neither the preview nor OK applies it again. bake_adjust(app, d); @@ -760,6 +782,27 @@ const SAVED_ROWS: &str = "__savedRows"; /// The selected group's colors after Save Changes, which OK gives it again with a new name. const SAVED_COLORS: &str = "__savedColors"; +/// With art, for each swatch of the selected group after Save Changes, the color that found the row +/// that gave it its new color (`null` for a swatch no row gave one), so a later Save Changes or OK +/// finds that row again when the row still lists its old current color. +const SWATCH_ROWS: &str = "__swatchRows"; + +/// The row that gives the swatch at place `i` of `own` (the group's colors) its new color, with the +/// color that finds it: the row listing the color [`SWATCH_ROWS`] holds for that swatch, else the +/// first row listing the swatch's own color. +fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Option<(Value, &'a Value)> { + let links = d.fields.get(SWATCH_ROWS).and_then(Value::as_array).filter(|l| l.len() == own.len()); + let link = links.and_then(|l| l.get(i)).filter(|l| !l.is_null()); + link.and_then(|l| row_listing(rs, l).map(|r| (l.clone(), r))).or_else(|| own.get(i).and_then(|k| row_listing(rs, k).map(|r| (k.clone(), r)))) +} + +/// The color an excluded row leaves its swatch, the row being the `i`th of the rows with current +/// colors: the swatch's own color in `assign` (the group's colors, with art), else the row's first +/// current color, which is its swatch's color without art. +fn kept_color<'a>(assign: &'a [Value], i: usize, row: &'a Value) -> Option<&'a Value> { + assign.get(i).or_else(|| row["from"].as_array().and_then(|f| f.first())) +} + /// Refuse a `groupAction` other than `save`, `new` or `delete`, `save` or `delete` with no group /// selected, and `save` on a group with a swatch that is not a color (a gradient, pattern or None /// swatch): the rows hold only the group's colors, so the save would replace or remove it. @@ -1057,12 +1100,18 @@ fn selection(d: &Dialog) -> Vec { /// `recolor.apply` parameters: the rows, method, library and the group with its new name and /// colors: the new colors of the rows with current colors, each in its swatch's place (`null` -/// for a row whose new color was removed, which removes its swatch), then (with art) the group's -/// colors no row took, then the colors added on the Edit tab. +/// for a row whose new color was removed, which removes its swatch, and `"keep"` for an excluded +/// row, which leaves its swatch its color), then (with art) the group's colors no row took, then the +/// colors added on the Edit tab. With art in a color of the group, each swatch whose row +/// ([`swatch_row`]) is found takes that row's new color instead, and every other swatch keeps its +/// color, as Save Changes gives them. fn apply_params(d: &Dialog) -> Value { let rs = rows(d); // The rows and Global Adjust unchanged since Save Changes: the group keeps its saved colors. let saved = unchanged_since_save(d); + let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).map_or(&[][..], Vec::as_slice); + let found: Vec> = (0..assign.len()).map(|i| swatch_row(d, &rs, assign, i)).collect(); + let keep = json!("keep"); let group = d.fields.get("group").and_then(Value::as_str).and_then(|g| { let name = d.str("groupName"); let rename = (!name.trim().is_empty() && name != g).then_some(name); @@ -1073,11 +1122,23 @@ fn apply_params(d: &Dialog) -> Value { } else { // A row made with New Row that holds no current colors gives the group no color; a color // added on the Edit tab (`added`) joins it after the others. - let took: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).map(|r| &r["to"]).collect(); - let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")); - let rest = assign.map_or(&[][..], |a| a.get(took.len()..).unwrap_or_default()); let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null()); - took.into_iter().chain(rest).chain(added).collect() + // A swatch that keeps its color takes no Global Adjust. + if found.iter().any(Option::is_some) { + found + .iter() + .map(|f| match f { + Some((_, r)) if !excluded(r) => &r["to"], + _ => &keep, + }) + .chain(added) + .collect() + } else { + let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let rest = assign.get(filled.len()..).unwrap_or_default(); + let took = filled.iter().map(|r| if excluded(r) { &keep } else { &r["to"] }); + took.chain(rest).chain(added).collect() + } }; Some(json!({"group": g, "groupColors": colors, "rename": rename})) }); @@ -2439,14 +2500,14 @@ mod tests { } /// Opened on a color group, OK rewrites it with the new colors of the rows that hold current - /// colors, then the group's colors no such row took: an empty row gives it no color. + /// colors, and the group's color no such row lists keeps its color: an empty row gives it no color. #[test] fn an_empty_row_gives_the_group_no_color() { let mut r = rows(); new_row(&mut r, &[]); let fields = json!({"rows": r, "group": "Trio", "__art": true, "__assign": ["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"]}); let p = apply_params(&Dialog::new("recolor", fields)); - assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "rgb 9 9 9"])); + assert_eq!(p["groupColors"], json!(["rgb 255 0 0", "rgb 0 0 255", "rgb 0 255 0", "keep"])); } /// Opened on colors alone, OK saves the new colors of the rows that hold current colors as the @@ -3638,7 +3699,7 @@ mod tests { r["to"] = json!("rgb 10 10 10"); } d.fields.insert("rows".into(), Value::Array(rs)); - let colors: Vec = apply_params(&d)["groupColors"].as_array().unwrap().iter().filter_map(color_value).map(|c| c.to_hex()).collect(); + let colors = sent_by(&app, &d); assert_eq!(colors.iter().filter(|c| *c == "#ffff00").count(), 1, "OK after a further edit keeps the added color once: {colors:?}"); assert!(!colors.contains(&"#00ff00".to_string()), "nor brings the removed color back: {colors:?}"); } @@ -3715,6 +3776,87 @@ mod tests { assert!(apply_params(app.ui.dialog.as_ref().unwrap()).get("group").is_none(), "OK leaves the saved group as it is"); } + /// The colors `d`'s OK gives the selected group, as hex, `"keep"` read as the color the swatch + /// at its place has. + fn sent_by(app: &VectorcraftApp, d: &Dialog) -> Vec { + let own = group_hex(app, &d.str("group")).unwrap_or_default(); + let p = apply_params(d); + let hex = |(i, k): (usize, &Value)| if *k == json!("keep") { own.get(i).cloned() } else { color_value(k).map(|c| c.to_hex()) }; + p["groupColors"].as_array().unwrap().iter().enumerate().filter_map(hex).collect() + } + + /// The colors OK gives the selected group, as [`sent_by`] reads them. + fn sent_hex(app: &VectorcraftApp) -> Vec { + sent_by(app, app.ui.dialog.as_ref().unwrap()) + } + + /// Sets the new color of the rows whose first current color is `hex` to `to`. + fn set_row(app: &mut VectorcraftApp, hex: &str, to: Value) { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some(hex) { + r["to"] = to.clone(); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + } + + /// With unlinked art in some of the group's colors, a second Save Changes after a further edit of + /// a row gives the swatch the first save gave that row's color the row's new color, and OK does + /// too; the swatch no row lists keeps its color both times. + #[test] + fn saving_a_group_twice_with_unlinked_art_gives_a_row_its_swatch_again() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff", "#ffff00"], "keepModel": true})).unwrap(); + let (blue, yellow) = (square(&mut app, 10.0, "#0000ff"), square(&mut app, 40.0, "#ffff00")); + app.run("select.set", json!({"ids": [blue, yellow]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + set_row(&mut app, "#ffff00", json!("rgb 255 255 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#008000".into(), "#ffff00".into()])); + frame(&mut app, &ctx, 0.2, vec![], 0); + set_row(&mut app, "#0000ff", json!("rgb 128 0 128")); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#800080", "#ffff00"], "OK gives the blue row's swatch its new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#800080".into(), "#ffff00".into()]), "the second save does too"); + } + + /// Without art, an excluded row leaves its swatch its own color at Save Changes and at OK, even + /// when its new color was changed before it was excluded. + #[test] + fn saving_a_group_without_art_keeps_an_excluded_rows_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#ff0000") { + r["to"] = json!("rgb 0 128 0"); + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + let sent = sent_hex(&app); + assert_eq!(sent, ["#ff0000", "#0000ff"], "OK keeps the excluded row's swatch"); + let p = apply_params(app.ui.dialog.as_ref().unwrap()); + assert_eq!(p["groupColors"][0], "keep", "so the Global Adjust leaves it as it is too: {p}"); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); + } + /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 754de2aea3..e3b19730e7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4686,9 +4686,12 @@ from colors alone leave its new color out. With `limitTo`, a row's `tint` (a per linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and -given the group's own colors in order and no new name, it records no undo step. And `recolor.apply` with `group` recolours the art and rewrites the +given the group's own colors in order and no new name, it records no undo step. A color key (`recolor.colors`) that +names a swatch's color, rounded to the key's steps, counts as that color, and the swatch keeps its color unrounded. And `recolor.apply` with `group` recolours the art and rewrites the group together. A `null` in `groupColors` removes the group's swatch at that place, and the swatches after it keep -their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its +their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. `"keep"` in +`groupColors` leaves the swatch at that place its color, without the Global Adjust; past the group's swatches it adds +nothing, and it is refused for a swatch that is not a color. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still reaches it; the reply's `relinked` counts the other linked paints that took the group's new colors. Art in a row that is linked to a swatch rewritten with another color keeps its row's new color, even an unchanged one, and is no longer @@ -4765,9 +4768,10 @@ dialog runs it (OK with it set in the same request runs it first): `save` (Save Changes) runs `swatch.editGroup` on the selected group with the colors OK would give it and the name in `groupName`, `new` (New Color Group) saves the new colors of the rows that are not excluded as `swatch.newGroup` does, and `delete` (Delete) runs `swatch.delete` on the selected group. Each is its own undo step, and the art keeps its -preview. When the art has colors of the group, `save` keeps the group's swatches in order: a swatch whose color a row -lists takes that row's new color (its own color when the row is excluded), so art linked to the swatch takes the color -its row shows, and every other swatch keeps its color. A row whose color was removed (`to: null`) and is not excluded +preview. An excluded row leaves its swatch its own color, with or without art. When the art has colors of the group, +`save` and OK keep the group's swatches in order: a swatch whose color a row lists, or to which an earlier `save` gave +a row's new color, takes that row's new color (its own color when the row is +excluded), so art linked to the swatch takes the color its row shows, and every other swatch keeps its color. A row whose color was removed (`to: null`) and is not excluded removes its swatch, and the colors added on the Edit tab follow the group's other colors, as at OK. After a `save` with art, the rows' new colors take the Global Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50eeb91a22..a10d6876ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1676,7 +1676,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes keeps the group's swatches in order, and a swatch no row lists keeps its color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` in `crates/engine/src/tests/swatchcmds.rs`. + - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. From 1121d6fff4d220c82aabcdc35727dc438494e256 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 02:50:06 -0800 Subject: [PATCH 088/138] Recolor Artwork: a second Save Changes keeps saved colors and finds rows read again Without art, a row excluded after Save Changes gave its swatch a new color now leaves the swatch that saved color, as OK does, instead of giving it back the row's old current color. With art linked to the group, after a save reads the rows from the art again, a swatch whose new color the save gave the art is found by that color, so a later edit of its row reaches it at Save Changes and OK. --- crates/ui-egui/src/dialogs/recolor.rs | 96 ++++++++++++++++++++++++--- 1 file changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index f3c0dde0bf..32d5492f56 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -574,27 +574,30 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // With art, the group's colors no row took follow, adjusted and snapped as OK gives them, // then the colors added on the Edit tab; a row made with New Row that holds no current // colors gives the group no color. - // An excluded row leaves its swatch its own color. + cancel_preview(app, d); + let own: Vec = doc_groups(app) + .into_iter() + .find(|(n, _)| group.as_deref() == Some(n.as_str())) + .map(|g| g.1.iter().map(key).collect()) + .unwrap_or_default(); + // An excluded row leaves its swatch the color it has now, as OK's `"keep"` does: with + // art, the swatch's color in `__assign`; without art, the swatch's color in the group, + // which an earlier Save Changes may have changed. let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); let rest: Vec = p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); - let assign: Vec = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art")).cloned().unwrap_or_default(); + let assign: Vec = + if d.bool("__art") { d.fields.get("__assign").and_then(Value::as_array).cloned().unwrap_or_default() } else { own.clone() }; let mut colors: Vec = filled .iter() .enumerate() .filter_map(|(i, r)| if excluded(r) { kept_color(&assign, i, r).cloned() } else { saved_color(app, d, r) }) .chain(group_colors(app, d, rest.iter())) .collect(); - cancel_preview(app, d); // With art in a color of the group, the group keeps its swatch order: a swatch whose row // ([`swatch_row`]) is found takes that row's new color (its own color when the row is // excluded), so the art linked to it takes the color its row shows, and every other // swatch keeps its color. The colors added on the Edit tab follow. - let own: Vec = doc_groups(app) - .into_iter() - .find(|(n, _)| group.as_deref() == Some(n.as_str())) - .map(|g| g.1.iter().map(key).collect()) - .unwrap_or_default(); let found: Vec> = (0..own.len()).map(|i| swatch_row(d, &rs, &own, i)).collect(); let mut links = None; if d.bool("__art") && found.iter().any(Option::is_some) { @@ -698,6 +701,18 @@ fn saved_color(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Option { fn reread_rows(app: &mut VectorcraftApp, d: &mut Dialog, old: &[Value], before: &[Vec], gone: &[Value]) { let given: Vec = art_colors(app).iter().zip(before).flat_map(|(now, was)| now.iter().zip(was).filter(|(n, w)| n != w).map(|(n, _)| n.clone())).collect(); + // A swatch whose color the save gave the art is found by that color again: the row its old + // color found lists other art now. + let group = d.fields.get("group").and_then(Value::as_str).map(str::to_owned); + let saved: Vec = + doc_groups(app).into_iter().find(|(n, _)| group.as_deref() == Some(n.as_str())).map(|g| g.1.iter().map(key).collect()).unwrap_or_default(); + if let Some(Value::Array(links)) = d.fields.get_mut(SWATCH_ROWS) { + for (l, c) in links.iter_mut().zip(&saved) { + if given.contains(c) { + *l = Value::Null; + } + } + } d.fields.insert(THEME_PICKS.into(), json!([])); d.fields.remove(REDUCED); sync(app, d); @@ -797,8 +812,8 @@ fn swatch_row<'a>(d: &Dialog, rs: &'a [Value], own: &[Value], i: usize) -> Optio } /// The color an excluded row leaves its swatch, the row being the `i`th of the rows with current -/// colors: the swatch's own color in `assign` (the group's colors, with art), else the row's first -/// current color, which is its swatch's color without art. +/// colors: the swatch's own color in `assign` (the group's colors), else the row's first current +/// color. fn kept_color<'a>(assign: &'a [Value], i: usize, row: &'a Value) -> Option<&'a Value> { assign.get(i).or_else(|| row["from"].as_array().and_then(|f| f.first())) } @@ -3857,6 +3872,67 @@ mod tests { assert_eq!(group_hex(&app, "Plain"), Some(vec!["#ff0000".into(), "#0000ff".into()]), "so does Save Changes"); } + /// Without art, a row excluded after Save Changes gave its swatch a new color leaves the swatch + /// that saved color at a second Save Changes, as OK does. + #[test] + fn saving_a_group_without_art_keeps_a_saved_color_when_its_row_is_excluded() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if r["to"] == json!("rgb 0 128 0") { + r["exclude"] = json!(true); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#008000", "#0000ff"], "OK keeps the saved color"); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert_eq!(group_hex(&app, "Plain"), Some(vec!["#008000".into(), "#0000ff".into()]), "so does a second Save Changes"); + } + + /// Save Changes that recolors linked art so that one swatch takes another swatch's old color: + /// read again, the row of the second swatch's new color gives that swatch a later new color. + #[test] + fn saving_a_group_twice_with_linked_art_finds_the_row_of_a_swatchs_new_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 100})).unwrap(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Linked", "fromArtwork": true, "toGlobal": true})).unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#ff0000".into(), "#0000ff".into()])); + app.run("ui.recolorDialog", json!({"group": "Linked"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("method".into(), json!(Method::Exact.id())); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, 0.0, vec![], 0); + set_row(&mut app, "#ff0000", json!("rgb 0 0 255")); + set_row(&mut app, "#0000ff", json!("rgb 0 128 0")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#008000".into()])); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + for r in &mut rs { + if from_colors(r).first().map(|c| c.to_hex()).as_deref() == Some("#008000") { + r["to"] = json!("rgb 128 0 128"); + r["exclude"] = json!(false); + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(sent_hex(&app), ["#0000ff", "#800080"], "OK gives the green swatch the green row's new color"); + act(&mut app, &ctx, 0.3, "save").unwrap(); + assert_eq!(group_hex(&app, "Linked"), Some(vec!["#0000ff".into(), "#800080".into()]), "so does Save Changes"); + } + /// Save Changes with a Global Adjust: the saved group holds it, the rows' new colors take it and /// it goes back to 0%, so OK with a new name renames the group without adjusting it again. #[test] From a31d8c31f79ab6fbca8c3b523a541ea6d3915f8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:52:18 -0800 Subject: [PATCH 089/138] MCP: confined native output refuses linked image paths outside the read roots Under automation read roots, every output that carries the native document (a native file or template, an EPS file, a .ai or .ait file of every artboard, a PDF of every artboard with Preserve Editing, from document.serialize, document.export, document.exportSelection, document.exportPdf, the saves, file.exportAs and Export for Screens rows) is refused with "a linked image file is outside the read roots" when that document names a linked image or placed file, a kept relative path or a data set's image outside the roots, or holds a stored brush entry that does not read as a brush. Nothing is written and the error names no file or folder. Outputs without the native document are written as before. The native document these files carry, and the documents file.package writes or rewrites, leave out an Export for Screens folder outside the read roots, as SVG with Preserve Editing already did. file.package refuses a linked file it copies as it is (a PDF, .ai or EPS file, or a native document with relink off) whose native document keeps such a folder, with "a linked file's export folder is outside the read roots". Export for Screens rows that write one artboard as a native, .ai or EPS file are checked against that artboard's art. Each asset, layer or selected object now writes its own native, .ai or EPS file: the per-artboard document cache was keyed by artboard index alone, so every piece after the first wrote the first piece's document. Both messages get rows in the complete-message catalogs. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/access.rs | 46 +++- crates/engine/src/cmd/fileio/eps.rs | 4 +- crates/engine/src/cmd/fileio/native.rs | 4 + crates/engine/src/cmd/fileio/pdf.rs | 5 +- crates/engine/src/cmd/fileio/save.rs | 6 +- crates/engine/src/cmd/fileio/screens.rs | 56 +++-- crates/engine/src/cmd/fileio/svg.rs | 8 +- crates/engine/src/cmd/fileio/tests_screens.rs | 22 ++ crates/engine/src/cmd/package.rs | 22 ++ crates/engine/src/tests/links.rs | 221 ++++++++++++++++++ crates/engine/src/tests/package.rs | 60 +++++ crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + 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 | 1 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/io/export.rs | 2 +- docs/mcp.md | 19 +- docs/target-app-parity.md | 1 + 39 files changed, 487 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6817f28b35..48af05935e 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -131,7 +131,7 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; -pub(crate) use access::{check_images_in, check_scripts_of}; +pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 9d2d9a4a33..1ded8d1f0b 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -171,13 +171,14 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards } } -/// The error for an SVG that would name a linked image's file outside the read roots. +/// The error for a file that would name a linked image's file outside the read roots. pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots"; /// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it -/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and -/// those too unless read roots are in force and the file would name a linked image's file outside -/// them (a relative path taken from `st`'s folder; a URL is not checked). An `` names the +/// exports), in format `format` (a format id) with options `p`: always, unless read roots are in +/// force and the file would name a linked image's file outside them (a relative path taken from +/// `st`'s folder; a URL is not checked). In any format but SVG and SVGZ, the file names them when it +/// carries the native document ([`check_native_images`]). An `` names the /// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for /// the image, for the images of the art each file draws (with chosen artboards, the art over each /// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask @@ -193,9 +194,12 @@ pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &ve /// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the /// objects on the clipboard, looked for from the document they came from). pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> { - if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() { + if crate::file_access::current().is_none() { return Ok(()); } + if !matches!(format, "svg" | "svgz") { + return check_native_images(cmd, format, d, base, p); + } // Options that don't read as the encoder's choices count as Link, Preserve Editing, hidden // layers kept and SVG 1.1: the encoder refuses them anyway. let (link, preserve, hidden, tiny) = match super::svg::options_map(p) { @@ -222,6 +226,38 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu Ok(()) } +/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: +/// always, unless read roots are in force, the file carries the native document (a native file or +/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as +/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file +/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the +/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be +/// read). The error names no file or folder. +pub(crate) fn check_native_images( + cmd: &str, + format: &str, + d: &vectorcraft_doc::Document, + base: crate::cmd::links::LinkBase, + p: &Value, +) -> Result<()> { + let carried = + crate::file_access::current().is_some() && !matches!(format, "svg" | "svgz") && names_linked_scripts(cmd, format, p, d.artboards.len()); + if carried && crate::cmd::links::names_hidden_file(d, base) { Err(bad(cmd, IMAGE_OUTSIDE)) } else { Ok(()) } +} + +/// `doc` as a file written for the request being served carries it: without an Export for Screens +/// `folder` outside the read roots ([`super::screens::leave_out_unreadable_settings_folder`]). The +/// open document keeps it. +pub(crate) fn with_readable_settings_folder(doc: &vectorcraft_doc::Document) -> std::borrow::Cow<'_, vectorcraft_doc::Document> { + let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); + if settings.len() == doc.export_settings.len() { + return std::borrow::Cow::Borrowed(doc); + } + let mut kept = doc.clone(); + kept.export_settings = settings; + std::borrow::Cow::Owned(kept) +} + /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn may_write(path: &str) -> Result<()> { diff --git a/crates/engine/src/cmd/fileio/eps.rs b/crates/engine/src/cmd/fileio/eps.rs index 3acd23e854..5067b1c6d5 100644 --- a/crates/engine/src/cmd/fileio/eps.rs +++ b/crates/engine/src/cmd/fileio/eps.rs @@ -280,8 +280,10 @@ fn thumbnail_of(preview: &Rendered, rect: Rect) -> Result { } /// What the file carries to reopen: `doc` (with only artboard `board` when the file is one of -/// several artboards), with linked images whole when `include_linked`. +/// several artboards), with linked images whole when `include_linked`, and without an Export for +/// Screens folder outside the read roots ([`super::access::with_readable_settings_folder`]). fn native(doc: &Document, board: Option, include_linked: bool) -> Vec { + let doc = &*super::access::with_readable_settings_folder(doc); let several = board.filter(|_| doc.artboards.len() > 1); if several.is_none() && !include_linked { return vectorcraft_format::save(doc, false); diff --git a/crates/engine/src/cmd/fileio/native.rs b/crates/engine/src/cmd/fileio/native.rs index cbf46c97c0..a4e0e4d24c 100644 --- a/crates/engine/src/cmd/fileio/native.rs +++ b/crates/engine/src/cmd/fileio/native.rs @@ -231,6 +231,8 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp } other => other, }; + // Without an Export for Screens folder outside the read roots. + let native = super::access::with_readable_settings_folder(&native); so.pretty = so.pretty_fits(&native); vectorcraft_format::save_to(&native, &so, w).map_err(|e| bad(cmd, e.to_string())) } @@ -308,6 +310,8 @@ pub(super) fn ai_native(cmd: &str, doc: &Document, so: &SaveOptions) -> Result = placed.into_iter().map(Note::loss).collect(); - let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?; + // The editing data leaves out an Export for Screens folder outside the read roots. + let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)); + let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?; notes.extend(drawn); if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None { for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) { @@ -500,6 +502,7 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result { let p = &*expanded; let st = s.doc()?; super::check_linked_scripts(C, "pdf", st, p)?; + super::check_linked_images(C, "pdf", st, &st.doc, p)?; let display_doc_title = super::has_own_title(&st.doc); let titled = super::titled_for_export(&st.doc, st.path.as_deref(), "pdf"); let mut q = p.clone(); diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 09b7924442..8a9b29fec2 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -896,7 +896,10 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option std::borrow::Cow::Borrowed(¶ms), }; super::check_linked_scripts(cmd, plan.format.id, st, &checked)?; + super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?; Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards }) } diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index e46982fe4b..b702a3fa8c 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1112,6 +1112,28 @@ fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool { super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len()) } +/// The document the file of `item` that row `r` writes carries when it carries one +/// ([`names_scripts`]): Full Document's PDF of every artboard, the item's artboard alone for a +/// native, `.ai` or EPS row ([`board_document`]), else the item's document. +fn carried_document<'a>(item: &'a Item, r: &Row, single: Option<&[usize]>) -> std::borrow::Cow<'a, Document> { + match (&item.every_artboard, r.format.id, single) { + (Some(all), "pdf", None) => std::borrow::Cow::Borrowed(&**all), + _ if r.whole_document() && item.artboard.is_some() => std::borrow::Cow::Owned(board_document(item)), + _ => std::borrow::Cow::Borrowed(&*item.doc), + } +} + +/// The document a native, `.ai` or EPS row writes for `item`'s artboard: that artboard alone, with +/// its background color and the art on it, as Save's separateArtboards writes it (#3868). +fn board_document(item: &Item) -> Document { + let mut d = single_artboard(&item.doc, item.region, &item.name); + if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(item.artboard.unwrap_or(0))) { + a.color = from.color; + } + super::save::keep_art_on(&mut d, item.region); + d +} + /// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF /// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard, /// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and @@ -1155,6 +1177,21 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?; } } + // The native document the files of the other rows carry, each document looked through once. + if crate::file_access::current().is_some() { + let mut looked: HashSet<(usize, bool, Option)> = HashSet::new(); + for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) { + for item in items.iter().filter(|i| names_scripts(i, r, single.as_deref())) { + let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); + let board = item.artboard.filter(|_| !all && r.whole_document()); + if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) + && crate::cmd::links::names_hidden_file(&carried_document(item, r, single.as_deref()), base) + { + return Err(bad(C, super::access::IMAGE_OUTSIDE)); + } + } + } + } // Appearance of Black › Printing / Exporting for RGB raster rows. // Include Artboard Fill off: the encoders leave the background colors out. let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) }; @@ -1268,8 +1305,9 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> } Ok(bytes) }; - // A whole-document copy of an artboard, for the formats that write documents to edit. - let mut board_docs: std::collections::HashMap> = std::collections::HashMap::new(); + // A whole-document copy of an artboard of an item's document, for the formats that write + // documents to edit. + let mut board_docs: std::collections::HashMap<(usize, usize), Arc> = std::collections::HashMap::new(); let mut files = 0u64; // One step per item and row, the files a name collision skips included. let steps = (items.len() * rows.len()) as u64; @@ -1308,19 +1346,7 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> write(all, "pdf", &options)? } else if r.whole_document() && item.artboard.is_some() { let b = item.artboard.unwrap_or(0); - // That artboard alone, as Save's separateArtboards writes it: its art, not the others' (#3868). - let d = board_docs - .entry(b) - .or_insert_with(|| { - let mut d = single_artboard(&item.doc, item.region, &item.name); - // It keeps its background color. - if let (Some(a), Some(from)) = (d.artboards.first_mut(), item.doc.artboards.get(b)) { - a.color = from.color; - } - super::save::keep_art_on(&mut d, item.region); - Arc::new(d) - }) - .clone(); + let d = board_docs.entry((Arc::as_ptr(&item.doc) as usize, b)).or_insert_with(|| Arc::new(board_document(item))).clone(); let mut options = r.options_for(item.region, None)?; // An EPS page is the artboard, not its art's bounds: an artboard without art still writes. if r.format.id == "eps" { diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index bcc01e37a4..066c6fc63f 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -183,13 +183,7 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> /// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder` /// outside the read roots of the request being served (the open document keeps it). fn native_attachment(doc: &Document) -> Vec { - let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone()); - if settings.len() == doc.export_settings.len() { - return vectorcraft_format::save(doc, false); - } - let mut kept = doc.clone(); - kept.export_settings = settings; - vectorcraft_format::save(&kept, false) + vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false) } /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index 362cc7a874..0ea3c29417 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -1334,3 +1334,25 @@ fn an_export_preset_adds_no_notes() { let r = export(&mut s, json!({"exportPreset": "Mixed"})); assert!(unused(&r).is_empty(), "{r}"); } + +/// Assets, layers and selected objects each write a native, `.ai` or EPS file of their own art: +/// every piece's file holds its own artboard, named after it, not the first piece's. +#[test] +fn each_piece_writes_its_own_native_document() { + let mut s = session(1); + s.execute("shape.ellipse", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let mut assets = vec![]; + for (id, name) in ids.iter().zip(["Square", "Circle"]) { + assets.push(s.execute("assets.add", &json!({"ids": [id], "name": name})).unwrap()["assets"][0].as_u64().unwrap()); + } + let r = export(&mut s, json!({"assets": assets, "formats": [{"format": "vectorcraft"}, {"format": "eps"}]})); + let written = files(&r); + assert_eq!(written.len(), 4, "{r}"); + for (name, bytes) in written { + let native = if name.ends_with(".eps") { vectorcraft_eps::native(&bytes).expect("native document") } else { bytes }; + let doc = vectorcraft_format::load(&native).unwrap(); + let board = doc.artboards[0].name.clone(); + assert!(name.contains(&board), "{name} holds the artboard {board}"); + } +} diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index c00f714515..3a182629df 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -137,6 +137,24 @@ fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { } } +/// The error for a linked file the package would copy with an Export for Screens folder outside +/// the read roots in the native document it is or carries. +const FOLDER_OUTSIDE: &str = "a linked file's export folder is outside the read roots"; + +/// Under read roots, the linked file `name` (`bytes`, as the package writes it) is copied only when +/// the native document it is or carries ([`carried_document`]) keeps no Export for Screens folder +/// outside them: a file copied as it is, a PDF, `.ai` or EPS file or a native document not +/// rewritten, would name it. The error names no file or folder. +fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { + if crate::file_access::current().is_none() { + return Ok(()); + } + match carried_document(name, bytes) { + Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)), + _ => Ok(()), + } +} + /// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`); /// none for other files. fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet { @@ -348,6 +366,7 @@ impl<'a> Collector<'a> { options.profiles = saved.profiles; options.compress = compressed; options.include_linked = include_linked; + let nested = super::fileio::with_readable_settings_folder(&nested); match vectorcraft_format::save_with(&nested, &options) { Ok(rewritten) => bytes = rewritten, Err(e) => self.warn( @@ -366,6 +385,7 @@ impl<'a> Collector<'a> { } } } + check_carried_folder(&file.name, &bytes)?; let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) }; self.copies.insert(found_path.to_string(), copy.clone()); local.insert(file.path.clone(), copy); @@ -505,7 +525,9 @@ fn prepare(s: &mut Session, p: &Value) -> Result { } let root = folder.map(|f| Path::new(f).join(&name)); let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None }; + // The package's document leaves out an Export for Screens folder outside the read roots. let doc = s.doc()?.doc.clone(); + let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) } diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index b3b98189fb..313d573206 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2377,6 +2377,227 @@ fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_ro every(&mut s, true, Some(&inside)); } +/// The native document a file of `format` carries: the file itself, a PDF's or `.ai` file's +/// editing data, or an EPS file's. +fn carried_document(format: &str, bytes: &[u8]) -> Document { + let native = if bytes.starts_with(b"%PDF") { + vectorcraft_pdf::editing(bytes).expect("editing data").data + } else if format == "eps" { + vectorcraft_eps::native(bytes).expect("native document") + } else { + bytes.to_vec() + }; + vectorcraft_format::load(&native).unwrap() +} + +/// A confined caller: every output that carries the native document (a native file or template, a +/// `.ai` or EPS file, a PDF with Preserve Editing) of a document that links an image +/// file outside the read roots is refused before a file or folder is written, with an error that +/// names no file or folder, and the document keeps the link. +#[test] +fn confined_native_output_refuses_a_linked_image_file_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("native-image-away"); + let home = Folder::new("native-image-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let a = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("assets.add", &json!({"ids": [a.0]})).unwrap(); + let own = home.file("own.vectorcraft"); + s.execute("file.saveAs", &json!({"path": own})).unwrap(); + let before = std::fs::read(&own).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "photo.png".to_string()]; + let refused = |s: &mut Session, cmd: &str, p: Value| { + let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd); + assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}"); + } + }; + let file = |name: &str| home.file(name); + let out = file("out"); + refused(&mut s, "document.serialize", json!({})); + for format in ["vectorcraft", "template", "pdf", "ai", "eps"] { + refused(&mut s, "document.serialize", json!({"format": format})); + refused(&mut s, "document.export", json!({"format": format})); + refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true})); + refused(&mut s, "document.exportSelection", json!({"format": format})); + } + refused(&mut s, "document.export", json!({"format": "pdf", "path": file("export.pdf")})); + refused(&mut s, "document.export", json!({"format": "ai", "path": file("export.ai")})); + refused(&mut s, "document.export", json!({"format": "eps", "path": file("export.eps")})); + refused(&mut s, "document.export", json!({"format": "vectorcraft", "path": file("export.vectorcraft")})); + refused(&mut s, "document.exportPdf", json!({})); + refused(&mut s, "document.exportPdf", json!({"path": file("direct.pdf")})); + refused(&mut s, "document.exportEps", json!({"path": file("direct.eps")})); + refused(&mut s, "document.save", json!({})); + refused(&mut s, "document.save", json!({"path": file("save.pdf")})); + refused(&mut s, "file.saveAs", json!({"path": file("save-as.ai")})); + // A saved `.ai` file has the artboards as its pages, whatever `useArtboards` says. + refused(&mut s, "file.saveAs", json!({"path": file("save-as-art.ai"), "useArtboards": false})); + refused(&mut s, "file.saveAs", json!({"path": file("save-as.eps")})); + refused(&mut s, "file.saveCopy", json!({"path": file("copy.vectorcraft")})); + refused(&mut s, "file.saveAsTemplate", json!({})); + refused(&mut s, "file.saveAsTemplate", json!({"format": "ait"})); + refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": "vectorcraft"}]})); + refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]})); + refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "ai"}]})); + refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "eps"}]})); + assert_eq!(std::fs::read(&own).unwrap(), before, "the document's own file is left as it was"); + let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(written, ["own.vectorcraft"]); + assert_eq!(image(&s, a).link.map(|l| l.path), Some(photo)); +} + +/// A confined caller's native outputs are refused when the document they carry names a file +/// outside the read roots only as a data set's image, or holds stored brushes that cannot be read. +/// Outputs that carry no native document (a PDF without Preserve Editing, a PDF or `.ai` file of +/// some artboards or of the art's bounds, a legacy `.ai` file, an image, an SVG without Preserve +/// Editing) are written, and so is a native file whose data set image is inside the read roots, or +/// any data set image without roots. +#[test] +fn confined_native_output_refuses_a_data_set_image_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("native-dataset-away"); + let home = Folder::new("native-dataset-home"); + let outside = away.file("photo.png"); + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 100, "height": 100})).unwrap(); + let set_image = |s: &mut Session, path: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect(); + doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }]; + }; + set_image(&mut s, &outside); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let refused = |s: &mut Session, cmd: &str, p: Value| { + let e = confine(roots.as_ref(), || s.execute(cmd, &p)).expect_err(cmd).to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{cmd} {p}: {e}"); + assert!(!e.contains(&away.0.to_string_lossy().into_owned()) && !e.contains("photo.png"), "{cmd} {p}: {e}"); + }; + let written = |s: &mut Session, p: Value| { + confine(roots.as_ref(), || s.execute("document.serialize", &p)).unwrap_or_else(|e| panic!("{p}: {e}")); + }; + for format in ["vectorcraft", "template", "pdf", "ai", "eps"] { + refused(&mut s, "document.serialize", json!({"format": format})); + } + refused(&mut s, "document.serialize", json!({"format": "svg", "preserveEditing": true})); + refused(&mut s, "document.exportPdf", json!({})); + for p in [ + json!({"format": "pdf", "preserveEditing": false}), + json!({"format": "pdf", "useArtboards": false}), + json!({"format": "pdf", "range": "2"}), + json!({"format": "ai", "artboards": [1]}), + json!({"format": "ai", "useArtboards": false}), + json!({"format": "ai", "aiVersion": "7"}), + json!({"format": "png"}), + json!({"format": "svg"}), + ] { + written(&mut s, p); + } + // Without roots, the native document keeps the data set's image as stored. + let r = s.execute("document.serialize", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + let carried = carried_document("vectorcraft", &bytes); + assert_eq!(carried.variables.datasets[0].values["Photo"], vectorcraft_doc::DataValue::Image(outside.clone())); + // An image inside the read roots. + set_image(&mut s, &home.file("photo.png")); + written(&mut s, json!({"format": "vectorcraft"})); + // Stored brushes that cannot be read: their links cannot be checked. + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.insert(vectorcraft_brush::DOC_KEY.into(), json!(["not a brush"])); + refused(&mut s, "document.serialize", json!({"format": "vectorcraft"})); + written(&mut s, json!({"format": "png"})); +} + +/// A confined caller's Export for Screens rows that write an artboard alone (native, `.ai` and EPS +/// files) are checked against that artboard's document: an image linked outside the read roots +/// on another artboard does not refuse them, and one on the artboard does. +#[test] +fn confined_screens_rows_check_the_artboard_each_file_holds() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("screens-board-away"); + let home = Folder::new("screens-board-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &photo); + s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 2010, "y": 10, "width": 50, "height": 20})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + for format in ["vectorcraft", "ai", "eps"] { + let p = |range: &str| json!({"range": range, "formats": [{"format": format}]}); + let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("2"))).unwrap_or_else(|e| panic!("{format}: {e}")); + assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{format}: {r}"); + let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("1"))).expect_err(format).to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{format}: {e}"); + } +} + +/// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with +/// Preserve Editing, a package's document) carry the document without the Export for Screens +/// folder when it is outside the read roots, with the other export settings and the art; the open +/// document keeps the folder. A folder inside the roots, and any folder without roots, stays. +#[test] +fn confined_native_output_leaves_out_an_export_folder_outside_the_read_roots() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("native-export-folder-away"); + let home = Folder::new("native-export-folder-home"); + let outside = away.0.to_string_lossy().into_owned(); + let inside = home.file("screens"); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + s.execute("file.saveAs", &json!({"path": home.file("own.vectorcraft")})).unwrap(); + let set_folder = |s: &mut Session, folder: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap(); + }; + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let check = |d: &Document, folder: Option<&str>, what: &str| { + assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}"); + assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}"); + assert!(d.node(rect).is_some(), "{what}: no art"); + }; + let package = home.file("package"); + let every = |s: &mut Session, confined: bool, folder: Option<&str>| { + let run = |s: &mut Session, cmd: &str, p: Value| { + let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) }; + r.unwrap_or_else(|e| panic!("{cmd} {p}: {e}")) + }; + for format in ["vectorcraft", "template", "pdf", "ai", "eps"] { + let r = run(s, "document.serialize", json!({"format": format})); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + check(&carried_document(format, &bytes), folder, &format!("{format} serialize")); + } + let pdf = home.file("direct.pdf"); + run(s, "document.exportPdf", json!({"path": pdf})); + check(&carried_document("pdf", &std::fs::read(&pdf).unwrap()), folder, "exportPdf"); + let eps = home.file("copy.eps"); + run(s, "file.saveCopy", json!({"path": eps})); + check(&carried_document("eps", &std::fs::read(&eps).unwrap()), folder, "eps copy"); + let _ = std::fs::remove_dir_all(&package); + run(s, "file.package", json!({"folder": package, "report": false, "copyFonts": false})); + let packaged = std::fs::read(Path::new(&package).join("own Folder").join("own.vectorcraft")).unwrap(); + check(&vectorcraft_format::load_file(&packaged).unwrap().doc, folder, "package"); + }; + set_folder(&mut s, &outside); + every(&mut s, true, None); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str())); + every(&mut s, false, Some(&outside)); + set_folder(&mut s, &inside); + every(&mut s, true, Some(&inside)); +} + /// A confined caller's SVG of a placed document whose art links an image: the file draws that art /// and names the image's file, so a file outside the read roots refuses it and one inside them is /// written. Any output that names no file is written. diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 218434eb8a..6ab5d73828 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -405,6 +405,66 @@ fn a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root() { assert_eq!(r["links"], 1, "{r}"); } +/// A confined request packages no linked file it would copy as it is (a PDF with Preserve Editing, +/// or a native document it does not rewrite) whose native document keeps an Export for Screens +/// folder outside its read roots: the package is refused before anything is written, with an error +/// that names no file or folder. A native document the package rewrites leaves the folder out, a +/// folder inside the roots is packaged, and the person's package copies every file. +#[test] +fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root() { + let away = Folder::new("package-folder-away"); + let home = Folder::new("package-folder-home"); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned()]; + let out = home.file("out"); + let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)); + let refused = |s: &mut Session, p: Value| { + let e = package(s, p.clone()).expect_err("refused"); + assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked file's export folder is outside the read roots"), "{p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{p} names {h}: {e}"); + } + assert!(!std::path::Path::new(&out).exists(), "{p}"); + }; + let mut part = session(); + run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})); + std::fs::create_dir_all(home.0.join("art")).unwrap(); + let native = home.file("art/part.vectorcraft"); + let pdf = home.file("art/part.pdf"); + let keep = |part: &mut Session, folder: &str| { + std::sync::Arc::make_mut(&mut part.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap(); + save(part, &native); + let r = run(part, "document.serialize", json!({"format": "pdf"})); + write(&pdf, &vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); + }; + keep(&mut part, &away.0.to_string_lossy()); + let poster = |placed: &str| { + let mut s = session(); + let r = run(&mut s, "file.place", json!({"path": placed, "link": true})); + assert_eq!(r["linked"], true, "{r}"); + save(&mut s, &home.file("poster.vectorcraft")); + s + }; + let mut s = poster(&pdf); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + let mut s = poster(&native); + refused(&mut s, json!({"folder": out, "relink": false})); + // Rewritten, the copy leaves the folder out. + let r = package(&mut s, json!({"folder": out})).unwrap(); + assert_eq!(r["links"], 1, "{r}"); + let copied = std::fs::read(std::path::Path::new(&out).join("poster Folder/Links/part.vectorcraft")).unwrap(); + assert_eq!(vectorcraft_format::load_file(&copied).unwrap().doc.export_settings.get("folder"), None); + std::fs::remove_dir_all(&out).unwrap(); + // A folder inside the read roots. + keep(&mut part, &home.file("screens")); + let mut s = poster(&pdf); + assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..69bedf6160 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5594,6 +5594,8 @@ digits Malayalam Malaiàlam @msg automation path rejected: outside the read root {root}: {path} camí d’automatització rebutjat: fora de l’arrel de lectura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} camí d’automatització rebutjat: fora de les arrels de lectura {roots}: {path} @msg a linked JavaScript file is outside the read roots un fitxer JavaScript enllaçat és fora de les arrels de lectura +@msg a linked image file is outside the read roots un fitxer d’imatge enllaçat és fora de les arrels de lectura +@msg a linked file's export folder is outside the read roots la carpeta d’exportació d’un fitxer enllaçat és fora de les arrels de lectura @msg the library's file is outside the read roots el fitxer de la biblioteca és fora de les arrels de lectura @msg {file} names more than one linked JavaScript file {file} correspon a més d’un fitxer JavaScript enllaçat @msg automation path rejected: outside the write root {root}: {path} camí d’automatització rebutjat: fora de l’arrel d’escriptura {root}: {path} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..2bb3c2e1ce 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5739,6 +5739,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg automation path rejected: outside the read root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro čtení {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro čtení {roots}: {path} @msg a linked JavaScript file is outside the read roots propojený soubor JavaScript je mimo kořeny pro čtení +@msg a linked image file is outside the read roots propojený soubor obrázku je mimo kořeny pro čtení +@msg a linked file's export folder is outside the read roots exportní složka propojeného souboru je mimo kořeny pro čtení @msg automation path rejected: outside the write root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro zápis {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro zápis {roots}: {path} @msg automation path rejected: path is empty cesta automatizace odmítnuta: cesta je prázdná diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..2d85da633f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1380,6 +1380,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a line needs at least two points en linje kræver mindst to punkter @msg a linked JavaScript file is outside the read roots en linket JavaScript-fil ligger uden for læserødderne @msg a linked image file is outside the read roots en linket billedfil ligger uden for læserødderne +@msg a linked file's export folder is outside the read roots eksportmappen for en linket fil ligger uden for læserødderne @msg a name names one asset: give multiple: false, or one object et navn angiver ét aktiv: angiv multiple: false eller ét objekt @msg a namespace declaration uses a reserved prefix or URI en navnerumserklæring bruger et reserveret præfiks eller en reserveret URI @msg a namespace qualifier is undefined en navnerumskvalifikator er udefineret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..f99f958d5b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9236,6 +9236,7 @@ breakText Glyphs Glyphen @msg a line needs at least two points eine Linie braucht mindestens zwei Punkte @msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner @msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner +@msg a linked file's export folder is outside the read roots der Exportordner einer verknüpften Datei liegt außerhalb der Lesestammordner @msg a number cannot be read eine Zahl kann nicht gelesen werden @msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang @msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..398d5b2509 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5436,6 +5436,8 @@ digits Malayalam Μαλαγιάλαμ @msg automation path rejected: outside the read root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας ανάγνωσης {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός των ριζών ανάγνωσης {roots}: {path} @msg a linked JavaScript file is outside the read roots ένα συνδεδεμένο αρχείο JavaScript είναι εκτός των ριζών ανάγνωσης +@msg a linked image file is outside the read roots ένα συνδεδεμένο αρχείο εικόνας είναι εκτός των ριζών ανάγνωσης +@msg a linked file's export folder is outside the read roots ο φάκελος εξαγωγής ενός συνδεδεμένου αρχείου είναι εκτός των ριζών ανάγνωσης @msg the library's file is outside the read roots το αρχείο της βιβλιοθήκης είναι εκτός των ριζών ανάγνωσης @msg {file} names more than one linked JavaScript file το {file} αντιστοιχεί σε περισσότερα από ένα συνδεδεμένα αρχεία JavaScript @msg automation path rejected: outside the write root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας εγγραφής {root}: {path} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..984268465a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5473,6 +5473,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg automation path rejected: outside the read root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de lectura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de lectura {roots}: {path} @msg a linked JavaScript file is outside the read roots un archivo JavaScript vinculado está fuera de las carpetas raíz de lectura +@msg a linked image file is outside the read roots un archivo de imagen vinculado está fuera de las carpetas raíz de lectura +@msg a linked file's export folder is outside the read roots la carpeta de exportación de un archivo vinculado está fuera de las carpetas raíz de lectura @msg automation path rejected: outside the write root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de escritura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de escritura {roots}: {path} @msg automation path rejected: path is empty ruta de automatización rechazada: la ruta está vacía diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..1b49c99ca6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5663,6 +5663,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg automation path rejected: outside the read root {root}: {path} automaation polku hylättiin: lukujuuren {root} ulkopuolella: {path} @msg automation path rejected: outside the read roots {roots}: {path} automaation polku hylättiin: lukujuurten {roots} ulkopuolella: {path} @msg a linked JavaScript file is outside the read roots linkitetty JavaScript-tiedosto on lukujuurten ulkopuolella +@msg a linked image file is outside the read roots linkitetty kuvatiedosto on lukujuurten ulkopuolella +@msg a linked file's export folder is outside the read roots linkitetyn tiedoston vientikansio on lukujuurten ulkopuolella @msg the library's file is outside the read roots kirjaston tiedosto on lukujuurten ulkopuolella @msg {file} names more than one linked JavaScript file {file} vastaa useampaa kuin yhtä linkitettyä JavaScript-tiedostoa @msg automation path rejected: outside the write root {root}: {path} automaation polku hylättiin: kirjoitusjuuren {root} ulkopuolella: {path} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..54b133a741 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5455,6 +5455,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg automation path rejected: outside the read root {root}: {path} chemin d’automatisation refusé : hors du dossier racine de lecture {root} : {path} @msg automation path rejected: outside the read roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines de lecture {roots} : {path} @msg a linked JavaScript file is outside the read roots un fichier JavaScript lié est hors des dossiers racines de lecture +@msg a linked image file is outside the read roots un fichier image lié est hors des dossiers racines de lecture +@msg a linked file's export folder is outside the read roots le dossier d’exportation d’un fichier lié est hors des dossiers racines de lecture @msg automation path rejected: outside the write root {root}: {path} chemin d’automatisation refusé : hors du dossier racine d’écriture {root} : {path} @msg automation path rejected: outside the write roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines d’écriture {roots} : {path} @msg automation path rejected: path is empty chemin d’automatisation refusé : le chemin est vide diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..5801e04f8c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6625,6 +6625,8 @@ antiAlias Sharp शार्प @msg automation path rejected: outside the read root {root}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ के बाहर {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} स्वचालन पाथ खारिज: पढ़ने की जड़ों के बाहर {roots}: {path} @msg a linked JavaScript file is outside the read roots एक लिंक की गई जावास्क्रिप्ट फ़ाइल पढ़ने की जड़ों के बाहर है +@msg a linked image file is outside the read roots एक लिंक की गई छवि फ़ाइल पढ़ने की जड़ों के बाहर है +@msg a linked file's export folder is outside the read roots एक लिंक की गई फ़ाइल का निर्यात फ़ोल्डर पढ़ने की जड़ों के बाहर है @msg the library's file is outside the read roots लाइब्रेरी की फ़ाइल पढ़ने की जड़ों के बाहर है @msg {file} names more than one linked JavaScript file {file} एक से अधिक लिंक की गई जावास्क्रिप्ट फ़ाइलों से मेल खाता है @msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..9d32256c22 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5193,6 +5193,8 @@ imageTrace Outline Körvonal @msg automation path rejected: outside the read root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az olvasási gyökéren ({root}): {path} @msg automation path rejected: outside the read roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az olvasási gyökereken ({roots}): {path} @msg a linked JavaScript file is outside the read roots egy csatolt JavaScript-fájl kívül esik az olvasási gyökereken +@msg a linked image file is outside the read roots egy csatolt képfájl kívül esik az olvasási gyökereken +@msg a linked file's export folder is outside the read roots egy csatolt fájl exportálási mappája kívül esik az olvasási gyökereken @msg automation path rejected: outside the write root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökéren ({root}): {path} @msg automation path rejected: outside the write roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökereken ({roots}): {path} @msg automation path rejected: parent traversal below a folder that doesn't exist: {path} az automatizálás útvonala elutasítva: szülőmappára lépés egy nem létező mappa alatt: {path} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..ab83d2e323 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5499,6 +5499,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg automation path rejected: outside the read root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di lettura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di lettura {roots}: {path} @msg a linked JavaScript file is outside the read roots un file JavaScript collegato è fuori dalle cartelle radice di lettura +@msg a linked image file is outside the read roots un file immagine collegato è fuori dalle cartelle radice di lettura +@msg a linked file's export folder is outside the read roots la cartella di esportazione di un file collegato è fuori dalle cartelle radice di lettura @msg automation path rejected: outside the write root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di scrittura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di scrittura {roots}: {path} @msg automation path rejected: path is empty percorso di automazione rifiutato: il percorso è vuoto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..a45098fc2e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5541,6 +5541,8 @@ liquify-list-end {0}, {1} {0}、{1} @msg automation path rejected: outside the read root {root}: {path} 自動化のパスを拒否しました: 読み込みルート {root} の外です: {path} @msg automation path rejected: outside the read roots {roots}: {path} 自動化のパスを拒否しました: 読み込みルート {roots} のいずれの中でもありません: {path} @msg a linked JavaScript file is outside the read roots リンクされた JavaScript ファイルが読み込みルートの外にあります +@msg a linked image file is outside the read roots リンクされた画像ファイルが読み込みルートの外にあります +@msg a linked file's export folder is outside the read roots リンクされたファイルの書き出しフォルダーが読み込みルートの外にあります @msg automation path rejected: outside the write root {root}: {path} 自動化のパスを拒否しました: 書き込みルート {root} の外です: {path} @msg automation path rejected: outside the write roots {roots}: {path} 自動化のパスを拒否しました: 書き込みルート {roots} のいずれの中でもありません: {path} @msg automation path rejected: path is empty 自動化のパスを拒否しました: パスが空です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..a14fc1f8e7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2064,6 +2064,7 @@ @msg {var_key} must be 0 or more {var_key} უნდა იყოს 0 ან მეტი @msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most} @msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg a linked file's export folder is outside the read roots დაკავშირებული ფაილის ექსპორტის საქაღალდე წაკითხვის ძირეული საქაღალდეების გარეთაა Neon & Glow ნეონი და ნათება Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან @msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor] diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..9b678e5ea6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5468,6 +5468,8 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg automation path rejected: outside the read root {root}: {path} 자동화 경로가 거부되었습니다: 읽기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the read roots {roots}: {path} 자동화 경로가 거부되었습니다: 읽기 루트 {roots} 밖입니다: {path} @msg a linked JavaScript file is outside the read roots 연결된 JavaScript 파일이 읽기 루트 밖에 있습니다 +@msg a linked image file is outside the read roots 연결된 이미지 파일이 읽기 루트 밖에 있습니다 +@msg a linked file's export folder is outside the read roots 연결된 파일의 내보내기 폴더가 읽기 루트 밖에 있습니다 @msg automation path rejected: outside the write root {root}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the write roots {roots}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {roots} 밖입니다: {path} @msg automation path rejected: path is empty 자동화 경로가 거부되었습니다: 경로가 비어 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..cc1c484470 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6219,6 +6219,7 @@ imageTrace Outline Contour @msg a legend draws at most {MAX_CHIPS} swatches een legenda tekent maximaal {MAX_CHIPS} stalen @msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots @msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots +@msg a linked file's export folder is outside the read roots de exportmap van een gekoppeld bestand staat buiten de leesroots @msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object @msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI @msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..a1e9b75723 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5565,6 +5565,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg automation path rejected: outside the read root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym odczytu {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi odczytu {roots}: {path} @msg a linked JavaScript file is outside the read roots połączony plik JavaScript jest poza katalogami głównymi odczytu +@msg a linked image file is outside the read roots połączony plik obrazu jest poza katalogami głównymi odczytu +@msg a linked file's export folder is outside the read roots folder eksportu połączonego pliku jest poza katalogami głównymi odczytu @msg automation path rejected: outside the write root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym zapisu {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi zapisu {roots}: {path} @msg automation path rejected: path is empty odrzucono ścieżkę automatyzacji: ścieżka jest pusta diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..590d0f0e29 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4735,6 +4735,8 @@ axis Both Ambos @msg automation path rejected: outside the read root {root}: {path} caminho da automação rejeitado: fora da raiz de leitura {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} caminho da automação rejeitado: fora das raízes de leitura {roots}: {path} @msg a linked JavaScript file is outside the read roots um arquivo JavaScript vinculado está fora das raízes de leitura +@msg a linked image file is outside the read roots um arquivo de imagem vinculado está fora das raízes de leitura +@msg a linked file's export folder is outside the read roots a pasta de exportação de um arquivo vinculado está fora das raízes de leitura @msg automation path rejected: outside the write root {root}: {path} caminho da automação rejeitado: fora da raiz de gravação {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} caminho da automação rejeitado: fora das raízes de gravação {roots}: {path} @msg automation path rejected: path is empty caminho da automação rejeitado: o caminho está vazio diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..021a4f5db1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5499,6 +5499,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg automation path rejected: outside the read root {root}: {path} путь автоматизации отклонён: вне корневой папки для чтения {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для чтения {roots}: {path} @msg a linked JavaScript file is outside the read roots связанный файл JavaScript находится вне корневых папок для чтения +@msg a linked image file is outside the read roots связанный файл изображения находится вне корневых папок для чтения +@msg a linked file's export folder is outside the read roots папка экспорта связанного файла находится вне корневых папок для чтения @msg automation path rejected: outside the write root {root}: {path} путь автоматизации отклонён: вне корневой папки для записи {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для записи {roots}: {path} @msg automation path rejected: path is empty путь автоматизации отклонён: путь пуст diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..199c3ab08c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5381,6 +5381,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg automation filesystem access is not granted: write authority is absent: {path} automatiseringen har inte fått åtkomst till filsystemet: skrivbehörighet saknas: {path} @msg automation path rejected: outside the read root {root}: {path} automatiseringssökvägen avvisades: utanför läsroten {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} automatiseringssökvägen avvisades: utanför läsrötterna {roots}: {path} +@msg a linked image file is outside the read roots en länkad bildfil ligger utanför läsrötterna +@msg a linked file's export folder is outside the read roots exportmappen för en länkad fil ligger utanför läsrötterna @msg automation path rejected: outside the write root {root}: {path} automatiseringssökvägen avvisades: utanför skrivroten {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} automatiseringssökvägen avvisades: utanför skrivrötterna {roots}: {path} @msg automation path rejected: path is empty automatiseringssökvägen avvisades: sökvägen är tom diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..603a918b40 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7287,6 +7287,8 @@ axis Y Axis Y ekseni @msg the guide is hidden or locked kılavuz gizli veya kilitli @msg the library's file is outside the read roots kütüphanenin dosyası okuma köklerinin dışında @msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında +@msg a linked image file is outside the read roots bağlantılı bir görüntü dosyası okuma köklerinin dışında +@msg a linked file's export folder is outside the read roots bağlantılı bir dosyanın dışa aktarma klasörü okuma köklerinin dışında @msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla @msg the method needs an XML value yöntem için bir XML değeri gerekir @msg the paint is not a freeform gradient (apply one with paint.editGradient {kind}) boya bir serbest biçimli degrade değil (paint.editGradient {kind} ile bir tane uygulayın) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..5d4e663cb1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5483,6 +5483,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg automation path rejected: outside the read root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для читання {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для читання {roots}: {path} @msg a linked JavaScript file is outside the read roots зв’язаний файл JavaScript перебуває поза кореневими папками для читання +@msg a linked image file is outside the read roots зв’язаний файл зображення перебуває поза кореневими папками для читання +@msg a linked file's export folder is outside the read roots папка експорту зв’язаного файлу перебуває поза кореневими папками для читання @msg automation path rejected: outside the write root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для запису {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для запису {roots}: {path} @msg automation path rejected: path is empty шлях автоматизації відхилено: шлях порожній diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..e4cc719e80 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4847,6 +4847,8 @@ theme Appearance Giao diện @msg automation path rejected: outside the read root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc đọc {root}: {path} @msg automation path rejected: outside the read roots {roots}: {path} đường dẫn tự động bị từ chối: ngoài các thư mục gốc đọc {roots}: {path} @msg a linked JavaScript file is outside the read roots một tệp JavaScript được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked image file is outside the read roots một tệp hình ảnh được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked file's export folder is outside the read roots thư mục xuất của một tệp được liên kết nằm ngoài các thư mục gốc đọc @msg the library's file is outside the read roots tệp của thư viện nằm ngoài các thư mục gốc đọc @msg {file} names more than one linked JavaScript file {file} khớp với nhiều hơn một tệp JavaScript được liên kết @msg automation path rejected: outside the write root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc ghi {root}: {path} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..8bcfed5519 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5215,6 +5215,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg automation path rejected: outside the read root {root}: {path} 已拒绝自动化路径:位于读取根目录 {root} 之外:{path} @msg automation path rejected: outside the read roots {roots}: {path} 已拒绝自动化路径:位于所有读取根目录 {roots} 之外:{path} @msg a linked JavaScript file is outside the read roots 链接的 JavaScript 文件位于所有读取根目录之外 +@msg a linked image file is outside the read roots 链接的图像文件位于所有读取根目录之外 +@msg a linked file's export folder is outside the read roots 链接文件的导出文件夹位于所有读取根目录之外 @msg automation path rejected: outside the write root {root}: {path} 已拒绝自动化路径:位于写入根目录 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒绝自动化路径:位于所有写入根目录 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒绝自动化路径:路径为空 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..42b9d9017c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2840,6 +2840,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg automation path rejected: outside the read root {root}: {path} 已拒絕自動化路徑:位於讀取根目錄 {root} 之外:{path} @msg automation path rejected: outside the read roots {roots}: {path} 已拒絕自動化路徑:位於所有讀取根目錄 {roots} 之外:{path} @msg a linked JavaScript file is outside the read roots 連結的 JavaScript 檔案位於所有讀取根目錄之外 +@msg a linked image file is outside the read roots 連結的影像檔案位於所有讀取根目錄之外 +@msg a linked file's export folder is outside the read roots 連結檔案的匯出資料夾位於所有讀取根目錄之外 @msg automation path rejected: outside the write root {root}: {path} 已拒絕自動化路徑:位於寫入根目錄 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒絕自動化路徑:位於所有寫入根目錄 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒絕自動化路徑:路徑是空的 diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index 32733d855c..d7e37dd998 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -84,7 +84,7 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option std::sync::Arc::new(d), } }; - fileio::check_linked_images("file.exportAs", f.id, st, &doc, params).map_err(|e| e.to_string())?; + fileio::check_linked_images("file.exportAs", f.id, st, &doc, &checked).map_err(|e| e.to_string())?; // A PDF shows its title in the viewer's title bar only when it is the document's own, not the // file name it was titled after, as `document.export` writes it. let own_title = fileio::has_own_title(&doc); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..adef77ff3b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -270,9 +270,22 @@ the suite) keep the agent to the folders you give it: selected objects only, and `clipboard.exportSvg` checks the copied objects, following a relative path from the document they came from while it is open; in a frame a request drives, Copy then puts no SVG on the system clipboard. An image whose pixels the document holds exports embedded, and a URL is not checked. -- With `preserveEditing`, the document an SVG or SVGZ of these outputs carries leaves out the Export for Screens - folder (`export_settings.folder`) when it is outside the read roots, as `document.exportSettings` does; the - other export settings and the art are kept, and the open document keeps the folder. +- The same error refuses, before any file or folder is written, every output of these commands and + `document.exportPdf` that carries the native document (the native file or template, EPS, `.ai`, `.ait` and + PDF files the JavaScript rule above lists, with `selectedOnly` and `document.exportSelection` the selected + objects' document) when that document names a file outside the read roots: a linked image or placed file, the + relative path kept of one (taken from the document's folder), or a data set's image, in every symbol, + pattern, graph design and brush, used or not. A stored brush entry that does not read as a brush is refused + too, since its links cannot be checked. Files that carry no native document are written as before, and the + document keeps every link and data set. +- The document these outputs carry (an SVG or SVGZ with `preserveEditing`, a native file or template, an EPS + file, a `.ai` or `.ait` file, a PDF with Preserve Editing, and the document `file.package` writes and the + linked native documents it rewrites) leaves out the Export for Screens folder (`export_settings.folder`) when + it is outside the read roots, as `document.exportSettings` does; the other export settings and the art are + kept, and the open document keeps the folder. `file.package` copies a linked PDF, `.ai` or EPS file, and a + linked native document with `relink: false`, as it is: when the native document such a file is or carries + keeps a folder outside the read roots, the package is refused before anything is written with "a linked + file's export folder is outside the read roots", which names no file or folder. - `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..6b53d04b36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -899,6 +899,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. The check covers the art drawn for placed documents and leaves out what the file leaves out: hidden art in symbols, patterns and graph designs, opacity masks in SVG Tiny 1.2, and objects drawn as images for effects SVG has no filter for. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`, `confined_svg_output_checks_the_images_of_placed_documents`, `confined_svg_output_leaves_hidden_symbol_art_unchecked`, `confined_svg_tiny_output_leaves_opacity_mask_images_unchecked`, `confined_svg_output_checks_the_images_drawn_for_pixel_effects`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`). - Clipboard flavors under `--automation-read-root`: `clipboard.flavours` leaves out the SVG, and its markup as text, that `clipboard.exportSvg` refuses. `crates/engine/src/tests/links.rs` (`confined_clipboard_flavours_leave_out_a_withheld_svg`). - Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`). + - Native document output and linked images under `--automation-read-root`: the outputs that carry the native document (a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard, a PDF of every artboard with Preserve Editing, also from `document.exportPdf`, the saves and Export for Screens rows) are refused, before any file or folder is written, with an error that names no file or folder, when that document names a linked image or placed file, a kept relative path or a data set's image outside the read roots, or holds a stored brush entry that does not read as a brush; files without the native document are written. Those documents, and the documents Package writes or rewrites, leave out an Export for Screens folder outside the read roots, and Package refuses a linked file it copies as it is whose native document keeps one; the open document keeps its links, data sets and folder. An Export for Screens row that writes one artboard is checked against that artboard's art, and each asset, layer or selected object writes its own native, `.ai` or EPS file. `crates/engine/src/tests/links.rs` (`confined_native_output_refuses_a_linked_image_file_outside_the_read_roots`, `confined_native_output_refuses_a_data_set_image_outside_the_read_roots`, `confined_native_output_leaves_out_an_export_folder_outside_the_read_roots`, `confined_screens_rows_check_the_artboard_each_file_holds`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root`), `crates/engine/src/cmd/fileio/tests_screens.rs` (`each_piece_writes_its_own_native_document`). - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/ (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. From cc6721f2d00cb8ad629489c06d23413edd648d3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:43:05 -0800 Subject: [PATCH 090/138] =?UTF-8?q?Type:=20Size=20=E2=80=BA=20Other?= =?UTF-8?q?=E2=80=A6=20gives=20the=20Character=20panel's=20Font=20Size=20f?= =?UTF-8?q?ield=20the=20focus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Type › Size ends with a separator and Other…, which runs the new UI command type.highlightFontSize. It shows the Character panel and gives its Font Size field the keyboard focus with the value selected, so a size the list does not hold can be typed and applied with Enter. Without selected type it fails with the existing error, as Highlight Kerning does, and the menu item is dimmed, as Bold and Italic are. The Font Size field now takes an armed focus: unit_field_from selects and focuses the field as bounded_field_reading already does. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 6 +++ crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 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/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.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/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/menus/tests.rs | 33 +++++++++++++ crates/ui-egui/src/menus/tree.rs | 9 +++- crates/ui-egui/src/menus/ui_commands.rs | 6 +++ crates/ui-egui/src/panel_docking/tests.rs | 2 +- crates/ui-egui/src/panels/character.rs | 19 +++++--- crates/ui-egui/src/panels/character/tests.rs | 51 ++++++++++++++++++++ crates/ui-egui/src/widgets/numeric.rs | 11 ++++- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 40 files changed, 190 insertions(+), 12 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0e3d6df203..e3b924a9a6 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -376,6 +376,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Alt+Shift+F", "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", ), + ( + "type.highlightFontSize", + "Highlight Font Size", + "", + "{} (Type › Size › Other…) show the Character panel if it is hidden and give its Font Size field the keyboard focus with its value selected (blank where the selected sizes differ): type a size and press Enter → {field: \"fontSize\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), ( "type.highlightKerning", "Highlight Kerning", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..b79c6978d9 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5936,6 +5936,8 @@ theme Appearance Външен вид Reset Tracking and Kerning Нулиране на разредката и кернинга Reset Horizontal Scale Нулиране на хоризонталния мащаб Highlight Font Name Маркиране на името на шрифта + Highlight Font Size Маркиране на размера на шрифта + Other… Друг… Highlight Kerning Маркиране на кернинга Highlight Tracking Маркиране на разредката @msg span must be "object" or "selection", got {v} span трябва да е "object" или "selection", а не {v} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..29637c6903 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4249,6 +4249,8 @@ axis Both Obje Reset Tracking and Kerning Vrati razmak slova i podrezivanje na početno Reset Horizontal Scale Vrati vodoravnu skalu na početno Highlight Font Name Istakni naziv fonta + Highlight Font Size Istakni veličinu fonta + Other… Druga… Highlight Kerning Istakni podrezivanje Highlight Tracking Istakni razmak slova Step Type Vrsta koraka diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..492faa37b1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1809,6 +1809,8 @@ digits Malayalam Malaiàlam Clear Similar Fonts Esborra els tipus de lletra semblants Font Preview Size Mida de previsualització del tipus de lletra Font Size Mida del tipus de lletra + Highlight Font Size Ressalta la mida del tipus de lletra + Other… Una altra… Font Style: Estil de tipus de lletra: Font Technology Tecnologia del tipus de lletra Font: Tipus de lletra: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..4f2bb4a42c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4354,6 +4354,8 @@ axis Both Obě Reset Tracking and Kerning Obnovit prostrkání a vyrovnání párů Reset Horizontal Scale Obnovit vodorovnou změnu velikosti Highlight Font Name Zvýraznit název písma + Highlight Font Size Zvýraznit velikost písma + Other… Jiná… Highlight Kerning Zvýraznit vyrovnání párů Highlight Tracking Zvýraznit prostrkání Step Type Krokovat text diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..4317afe913 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -8409,6 +8409,8 @@ mark-style Japanese Japansk Reset Tracking and Kerning Nulstil sporing og kerning Reset Horizontal Scale Nulstil vandret skalering Highlight Font Name Fremhæv skrifttypenavn + Highlight Font Size Fremhæv skriftstørrelse + Other… Anden… Highlight Kerning Fremhæv kerning Highlight Tracking Fremhæv sporing @msg span must be "object" or "selection", got {v} span skal være "object" eller "selection", fik {v} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..69e72b9ae8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1272,6 +1272,8 @@ font-technology Variable Variabel Reset Tracking and Kerning Laufweite und Kerning zurücksetzen Reset Horizontal Scale Horizontale Skalierung zurücksetzen Highlight Font Name Schriftname hervorheben + Highlight Font Size Schriftgrad hervorheben + Other… Andere… Highlight Kerning Kerning hervorheben Highlight Tracking Laufweite hervorheben Spacing Abstand diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..70fc1207d5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6310,6 +6310,8 @@ effect Points Σημεία Reset Horizontal Scale Επαναφορά οριζόντιας κλίμακας Reset Tracking and Kerning Επαναφορά απόστασης χαρακτήρων και διαγραμμάτωσης Highlight Font Name Επισήμανση ονόματος γραμματοσειράς + Highlight Font Size Επισήμανση μεγέθους γραμματοσειράς + Other… Άλλο… Highlight Kerning Επισήμανση διαγραμμάτωσης Highlight Tracking Επισήμανση απόστασης χαρακτήρων Sample Color from Screen Δειγματοληψία χρώματος από την οθόνη diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..5deae11eea 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1299,6 +1299,8 @@ font-technology Variable Variables Reset Tracking and Kerning Restablecer espaciado e interletraje Reset Horizontal Scale Restablecer escala horizontal Highlight Font Name Resaltar nombre de fuente + Highlight Font Size Resaltar tamaño de fuente + Other… Otro… Highlight Kerning Resaltar interletraje Highlight Tracking Resaltar espaciado Spacing Espaciado diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..0517937c8e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6320,6 +6320,8 @@ mark-style Japanese Japanilainen Reset Horizontal Scale Palauta vaakaskaalaus Reset Tracking and Kerning Palauta merkkiväli ja parivälistys Highlight Font Name Korosta fontin nimi + Highlight Font Size Korosta fonttikoko + Other… Muu… Highlight Kerning Korosta parivälistys Highlight Tracking Korosta merkkiväli Sample Color from Screen Poimi väri näytöltä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..ed8ea9aaa7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1289,6 +1289,8 @@ font-technology Variable Variables Reset Tracking and Kerning Réinitialiser l’approche et le crénage Reset Horizontal Scale Réinitialiser la mise à l’échelle horizontale Highlight Font Name Surligner le nom de la police + Highlight Font Size Surligner la taille de police + Other… Autre… Highlight Kerning Surligner le crénage Highlight Tracking Surligner l’approche Spacing Espacement diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..44c8b4ae8f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1691,6 +1691,8 @@ Highlight Alternate Glyphs વૈકલ્પિક ગ્લિફ હાઇલાઇટ કરો Highlight Area વિસ્તાર હાઇલાઇટ કરો Highlight Font Name ફોન્ટનું નામ હાઇલાઇટ કરો + Highlight Font Size ફોન્ટ સાઇઝ હાઇલાઇટ કરો + Other… અન્ય… Highlight Intensity હાઇલાઇટ તીવ્રતા Highlight Kerning કર્નિંગ હાઇલાઇટ કરો Highlight Rows પંક્તિઓ હાઇલાઇટ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..2593a22075 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2328,6 +2328,8 @@ antiAlias Sharp शार्प Highlight anchors on mouse over माउस ओवर पर हाइलाइट एंकर Highlight Area हाइलाइट क्षेत्र Highlight Font Name हाइलाइट फ़ॉन्ट नाम + Highlight Font Size हाइलाइट फ़ॉन्ट साइज़ + Other… अन्य… Highlight Kerning हाइलाइट कर्निंग Highlight Rows हाइलाइट पंक्तियाँ Highlight Substituted Fonts हाईलाइट सबस्टिट्यूटेड फ़ॉन्ट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..9146f7429f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3611,6 +3611,8 @@ mark-style Japanese Japán Reset Tracing Tracing visszaállítása Reset Tracking and Kerning Betűköz és alávágás visszaállítása Highlight Font Name Betűtípusnév kiemelése + Highlight Font Size Betűméret kiemelése + Other… Egyéb… Highlight Kerning Alávágás kiemelése Highlight Tracking Betűköz kiemelése Reset Typography Typography visszaállítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..19579dd31f 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5681,6 +5681,8 @@ mark-style Japanese Jepang Reset Tracking and Kerning Atur ulang tracking dan kerning Reset Horizontal Scale Atur ulang skala horizontal Highlight Font Name Sorot nama font + Highlight Font Size Sorot ukuran font + Other… Lainnya… Highlight Kerning Sorot kerning Highlight Tracking Sorot tracking @msg span must be "object" or "selection", got {v} span harus "object" atau "selection", diterima {v} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..3a037b10d2 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1306,6 +1306,8 @@ font-technology Variable Variabili Reset Tracking and Kerning Reimposta spaziatura caratteri e crenatura Reset Horizontal Scale Reimposta scala orizzontale Highlight Font Name Evidenzia nome del font + Highlight Font Size Evidenzia dimensione font + Other… Altro… Highlight Kerning Evidenzia crenatura Highlight Tracking Evidenzia spaziatura caratteri Spacing Spaziatura diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..4c2b4712b2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -461,6 +461,8 @@ digits Malayalam マラヤーラム数字 Reset Tracking and Kerning トラッキングとカーニングをリセット Reset Horizontal Scale 水平比率をリセット Highlight Font Name フォント名をハイライト + Highlight Font Size フォントサイズをハイライト + Other… その他… Highlight Kerning カーニングをハイライト Highlight Tracking トラッキングをハイライト Step Type 文字を段階的に調整 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..a3f3a9a74e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7998,6 +7998,8 @@ liquify-list-end {0}, {1} {0} და {1} Keep selected მონიშნულად დატოვება Reset Tracking and Kerning ტრეკინგისა და კერნინგის ჩამოყრა Highlight Font Name შრიფტის სახელის გამოკვეთა + Highlight Font Size შრიფტის ზომის გამოკვეთა + Other… სხვა… Highlight Kerning კერნინგის გამოკვეთა Highlight Tracking ტრეკინგის გამოკვეთა Legacy (version 7) ძველი (ვერსია 7) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..21c5bbedcb 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -454,6 +454,8 @@ digits Malayalam 말라얄람어 Reset Tracking and Kerning 자간 및 커닝 재설정 Reset Horizontal Scale 가로 비율 재설정 Highlight Font Name 글꼴 이름 강조 표시 + Highlight Font Size 글꼴 크기 강조 표시 + Other… 기타… Highlight Kerning 커닝 강조 표시 Highlight Tracking 자간 강조 표시 Step Type 단계별 문자 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..d23a677dfb 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8192,6 +8192,8 @@ mark-style Japanese Japans Reset Tracking and Kerning Tracking en kerning herstellen Reset Horizontal Scale Horizontale schaal herstellen Highlight Font Name Lettertypenaam markeren + Highlight Font Size Lettertypegrootte markeren + Other… Andere… Highlight Kerning Kerning markeren Highlight Tracking Tracking markeren @msg span must be "object" or "selection", got {v} span moet "object" of "selection" zijn, maar is {v} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..dfe3969653 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4196,6 +4196,8 @@ axis Both Obie Reset Tracking and Kerning Resetuj światło i kerning Reset Horizontal Scale Resetuj skalę poziomą Highlight Font Name Wyróżnij nazwę czcionki + Highlight Font Size Wyróżnij rozmiar czcionki + Other… Inny… Highlight Kerning Wyróżnij kerning Highlight Tracking Wyróżnij światło Step Type Krok tekstu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..d9c1d3626b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1179,6 +1179,8 @@ antiAlias Sharp Nítido Reset Tracking and Kerning Redefinir Rastreamento e Kerning Reset Horizontal Scale Redefinir Escala Horizontal Highlight Font Name Destacar Nome da Fonte + Highlight Font Size Destacar Tamanho da Fonte + Other… Outro… Highlight Kerning Destacar Kerning Highlight Tracking Destacar Rastreamento Step Type Ajustar Texto em Incrementos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..694c137d08 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1297,6 +1297,8 @@ font-technology Variable Вариативные Reset Tracking and Kerning Сбросить трекинг и кернинг Reset Horizontal Scale Сбросить масштаб по горизонтали Highlight Font Name Выделить имя шрифта + Highlight Font Size Выделить размер шрифта + Other… Другой… Highlight Kerning Выделить кернинг Highlight Tracking Выделить трекинг Spacing Интервал diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..5aad4fd2c0 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6303,6 +6303,8 @@ theme Appearance Utseende Reset Horizontal Scale Återställ horisontell skala Reset Tracking and Kerning Återställ spärrning och kerning Highlight Font Name Framhäv typsnittsnamn + Highlight Font Size Framhäv teckenstorlek + Other… Annan… Highlight Kerning Framhäv kerning Highlight Tracking Framhäv spärrning Sample Color from Screen Hämta färg från skärmen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..4c680f92b9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1248,6 +1248,8 @@ font-technology Variable Değişken Reset Tracking and Kerning Takip ve Karakter Aralığını Sıfırla Reset Horizontal Scale Yatay Ölçeği Sıfırla Highlight Font Name Yazı Tipi Adını Vurgula + Highlight Font Size Yazı Tipi Boyutunu Vurgula + Other… Diğer… Highlight Kerning Karakter Aralığını Vurgula Highlight Tracking Takibi Vurgula Spacing Aralık diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..3a70b5b8af 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1300,6 +1300,8 @@ font-technology Variable Варіативні Reset Tracking and Kerning Скинути трекінг і кернінг Reset Horizontal Scale Скинути масштаб по горизонталі Highlight Font Name Виділити назву шрифту + Highlight Font Size Виділити розмір шрифту + Other… Інший… Highlight Kerning Виділити кернінг Highlight Tracking Виділити трекінг Spacing Інтервал diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..e764fa06d2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3380,6 +3380,8 @@ mark-style Japanese Kiểu Nhật Reset to White, Black Đặt lại về Trắng, Đen Reset Tracking and Kerning Đặt lại giãn chữ và kerning Highlight Font Name Đánh dấu tên phông + Highlight Font Size Đánh dấu cỡ chữ + Other… Khác… Highlight Kerning Đánh dấu kerning Highlight Tracking Đánh dấu giãn chữ Reset with Mesh Đặt lại với lưới diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..30a2bbfa76 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1237,6 +1237,8 @@ antiAlias Sharp 锐利 Reset Tracking and Kerning 重置字距和字偶距 Reset Horizontal Scale 重置水平缩放 Highlight Font Name 突出显示字体名称 + Highlight Font Size 突出显示字号 + Other… 其他… Highlight Kerning 突出显示字偶距 Highlight Tracking 突出显示字距 Spacing 间距 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..e0ac64696d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1271,6 +1271,8 @@ font-technology Variable 可變 Reset Tracking and Kerning 重設字距與字距微調 Reset Horizontal Scale 重設水平縮放 Highlight Font Name 反白顯示字體名稱 + Highlight Font Size 反白顯示字體大小 + Other… 其他… Highlight Kerning 反白顯示字距微調 Highlight Tracking 反白顯示字距 Spacing 間距 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 495e606d6c..0b3d86f57a 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -322,6 +322,7 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::character::toggle_face(app, Face::Bold), "type.italic" => crate::panels::character::toggle_face(app, Face::Italic), "type.highlightFontName" => crate::panels::character::highlight(app, crate::panels::character::Field::FontName), + "type.highlightFontSize" => crate::panels::character::highlight(app, crate::panels::character::Field::FontSize), "type.highlightKerning" => crate::panels::character::highlight(app, crate::panels::character::Field::Kerning), "type.highlightTracking" => crate::panels::character::highlight(app, crate::panels::character::Field::Tracking), "type.underline" => crate::panels::character::toggle_underline(app), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index d4dda4698b..7a4b195ae1 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -219,7 +219,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { match id { // Save is off for a clean document that already has its own file. "file.save" => app.session.active().is_some_and(|d| d.path.is_none() || d.converted || d.is_dirty()), - "type.bold" | "type.italic" | "type.underline" | "type.lineComposer" | "type.hyphenate" => { + "type.bold" | "type.italic" | "type.underline" | "type.lineComposer" | "type.hyphenate" | "type.highlightFontSize" => { crate::panels::character::text_style(app).is_some() } id if crate::panels::paragraph::ALIGN_COMMANDS.iter().any(|c| c.0 == id) => crate::panels::character::text_style(app).is_some(), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 1bb152292e..a1e5e65c33 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -416,6 +416,39 @@ fn center_on_top_and_bottom_are_type_on_a_path_items() { assert!((start - 0.625).abs() < 1e-6, "{start}"); } +/// Type › Size ends with a separator and Other…, which runs `type.highlightFontSize`: dimmed +/// without selected type, enabled with it, and never checked. +#[test] +fn type_size_ends_with_other() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let id = "type.highlightFontSize"; + assert!(!enabled(&app, id), "no document"); + app.run("file.new", json!({})).unwrap(); + let items: Vec = menu_tree() + .into_iter() + .filter(|(menu, _)| *menu == "Type") + .flat_map(|(_, items)| items) + .filter_map(|item| match item { + Item::Sub("Size", children) => Some(children), + _ => None, + }) + .flatten() + .collect(); + let n = items.len(); + assert!(n > 2, "{n} items"); + assert!(matches!(items[n - 2], Item::Sep), "a separator comes before Other…"); + assert!(matches!(&items[n - 1], Item::Cmd("Other…", c, p) if *c == id && p.is_null()), "Other… comes last"); + assert!(items[..n - 2].iter().all(|i| matches!(i, Item::Cmd(_, "text.setStyle", _))), "the sizes come first"); + assert!(!enabled(&app, id), "nothing selected"); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [path]})).unwrap(); + assert!(!enabled(&app, id), "a path selected"); + let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Size"})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [text]})).unwrap(); + assert!(enabled(&app, id), "type selected"); + assert_eq!(checked(&app, id, &Value::Null), None); +} + /// Type › Dynamic Text Presets › Circle, Arch and Bow run `type.dynamicTextPreset` with their /// preset, enabled for point type and type on a path but not for area type alone. #[test] diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index ec8ec99018..f54f95b569 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -397,7 +397,14 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { vec![ sub("Font", font_items(english_names)), sub("Recent Fonts", RECENT_FONT_IDS.iter().map(|id| c("Recent Font", id)).collect()), - sub("Size", TYPE_SIZES.iter().map(|(l, n)| cp(l, "text.setStyle", json!({ "size": n }))).collect()), + sub( + "Size", + TYPE_SIZES + .iter() + .map(|(l, n)| cp(l, "text.setStyle", json!({ "size": n }))) + .chain([Sep, c("Other…", "type.highlightFontSize")]) + .collect(), + ), c("Bold", "type.bold"), c("Italic", "type.italic"), Sep, diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ced961e32c..2ff580f22c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -377,6 +377,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+Alt+Shift+F", "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", ), + ( + "type.highlightFontSize", + "Highlight Font Size", + "", + "{} (Type › Size › Other…) show the Character panel if it is hidden and give its Font Size field the keyboard focus with its value selected (blank where the selected sizes differ): type a size and press Enter → {field: \"fontSize\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), ( "type.highlightKerning", "Highlight Kerning", diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 266f423838..d1f7f1473a 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -408,7 +408,7 @@ fn a_character_field_shortcut_brings_the_floating_character_panel_forward() { h.frame(vec![]); assert!(showing(&h.app.ui, "character")); assert_eq!(h.app.dock_rt.raise, None); - for command in ["type.highlightKerning", "type.highlightTracking", "type.highlightFontName"] { + for command in ["type.highlightKerning", "type.highlightTracking", "type.highlightFontName", "type.highlightFontSize"] { h.app.run(command, json!({})).unwrap(); assert_eq!(h.app.dock_rt.raise.as_deref(), Some("character"), "{command}"); h.frame(vec![]); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 746a8fbdf4..1ddb45b11b 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -481,12 +481,14 @@ pub(crate) fn toggle_face(app: &mut VectorcraftApp, face: Face) -> Result &'static str { match self { Field::FontName => "ch-font", + Field::FontSize => "ch-size", Field::Kerning => "ch-kern", Field::Tracking => "ch-track", } @@ -504,17 +507,19 @@ impl Field { fn name(self) -> &'static str { match self { Field::FontName => "fontName", + Field::FontSize => "fontSize", Field::Kerning => "kerning", Field::Tracking => "tracking", } } } -/// `type.highlightFontName`, `type.highlightKerning` and `type.highlightTracking`: show the -/// Character panel if it is hidden (a shown one is activated, so its floating window comes -/// forward), and give `field` the keyboard focus when the panel next draws it, a number field with -/// its value selected (typing replaces it, Enter applies it). Without selected type or text the -/// Type tool edits, the panel shows, nothing takes the focus and the command fails. → `{field}`. +/// `type.highlightFontName`, `type.highlightFontSize`, `type.highlightKerning` and +/// `type.highlightTracking`: show the Character panel if it is hidden (a shown one is activated, +/// so its floating window comes forward), and give `field` the keyboard focus when the panel next +/// draws it, a number field with its value selected (typing replaces it, Enter applies it). +/// Without selected type or text the Type tool edits, the panel shows, nothing takes the focus and +/// the command fails. → `{field}`. pub(crate) fn highlight(app: &mut VectorcraftApp, field: Field) -> Result { // `window.panel` would hide a floating panel in front of its window, or an open flyout. if crate::panel_docking::visible(&app.ui, "character") { diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 1e3e6acec4..6ff3eeb51e 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -343,6 +343,57 @@ fn highlight_commands_focus_the_font_kerning_and_tracking_fields() { assert_eq!(app.character_focus, None); } +/// Type › Size › Other… (Highlight Font Size) shows the Character panel and gives its Font Size +/// field the keyboard focus with the value selected: what is typed replaces it, Enter applies it +/// as one undo step, and a selection of different sizes takes the one size typed into the blank +/// field. Without selected type the panel shows, the command fails and nothing takes the focus. +#[test] +fn highlight_font_size_focuses_the_font_size_field() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AVAX", "size": 12})).unwrap()["id"].clone(); + let b = app.run("text.create", json!({"x": 20, "y": 120, "text": "Wave", "size": 20})).unwrap()["id"].clone(); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + let typed = |text: &str| { + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + vec![egui::Event::Text(text.into()), enter] + }; + let size = |app: &VectorcraftApp| shared(app, |s| s.size); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); + assert_eq!(app.run("type.highlightFontSize", json!({})).unwrap(), json!({"field": "fontSize"})); + assert!(crate::panel_docking::showing(&app.ui, "character"), "the panel shows"); + frame(&mut app, vec![]); + assert_eq!(app.character_focus, None, "the Font Size field took the focus"); + frame(&mut app, typed("33")); + assert_eq!(size(&app), Some(33.0), "typing replaced the size"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(size(&app), Some(12.0), "one undo step restores the size"); + // Choosing Other again while the field holds typed text that is not applied selects all of it. + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, vec![egui::Event::Text("999".into())]); + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, typed("18")); + assert_eq!(size(&app), Some(18.0), "typing replaced the text typed before"); + ctx.memory_mut(|m| m.stop_text_input()); + // Different sizes: the field is blank, and the size typed applies to every selected object. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(size(&app), None); + app.run("type.highlightFontSize", json!({})).unwrap(); + frame(&mut app, vec![]); + frame(&mut app, typed("16")); + assert_eq!(size(&app), Some(16.0), "both objects take the size typed"); + // No type selected: the panel shows, the command fails and nothing is armed. + app.run("select.none", json!({})).unwrap(); + assert!(app.run("type.highlightFontSize", json!({})).is_err()); + assert_eq!(app.character_focus, None); +} + /// A variable font gets the Variable Font button, which opens one slider per axis named as the /// font names it; a drag along one sets that axis of the selected type in one undo step. #[test] diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 89ce8d70d5..23f48f88d2 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -142,7 +142,8 @@ fn unit_field( /// [`unit_field`] whose blank field (`value` is `None`) steps from `blank_from` (points) with /// ↑/↓ and the wheel instead of doing nothing. With `refuse_outside`, a value typed outside -/// `bounds` is refused as text that doesn't read is, rather than kept at the nearer end. +/// `bounds` is refused as text that doesn't read is, rather than kept at the nearer end. Armed +/// with id salt `id` ([`arm_field_focus`]), it takes the keyboard focus with its value selected. #[allow(clippy::too_many_arguments)] fn unit_field_from( ui: &mut Ui, @@ -160,10 +161,18 @@ fn unit_field_from( empty: &str, refuse_outside: bool, ) -> Option { + let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); let shown = value.map(|v| unit.format(v)).unwrap_or_else(|| empty.to_string()); take_dialog_focus(ui, id, &shown); + if armed { + focus_field(ui, id, &shown); + } let (mut buf, commit, resp, rect) = recessed_text(ui, id, &shown, width, 1, label, name); + if armed { + // A field armed while it has focus keeps the text typed into it: select all of that text. + select_all(ui, id, &buf); + } select_all_on_focus(ui, &resp, &buf); // ↑/↓ and the wheel step in the field's unit; a drag on its label scrubs it. let typed = typed_unit(ui.ctx(), unit); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..43884793f2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7034,7 +7034,10 @@ Pen's second anchor at (150, 431), in line with the square's centre. `type.highlightTracking` (no default key) and `type.highlightFontName` (Cmd+Alt+Shift+F) show the Character panel and give its Kerning or Tracking field the keyboard focus with the value selected, or open its font family menu with the search field focused; each replies `{field: "kerning" | "tracking" | "fontName"}`. Without selected type or text the - Type tool edits, the panel shows and the command fails. + Type tool edits, the panel shows and the command fails. Type › Size › Other… runs `type.highlightFontSize` (`{}`, no + default key), which gives the Character panel's Font Size field the keyboard focus the same way (blank when the + selected sizes differ; the size typed and Enter apply through `text.setStyle {size}` as one undo step) and replies + `{field: "fontSize"}`; the menu item is dimmed without selected type or text the Type tool edits. The UI command `type.underline` (Cmd+Shift+U, in remote mode `press_key {key: "U", mods: {cmd: true, shift: true}}` or `invoke_menu`) does what the Character panel's Underline button does: it underlines the Type tool's selected text or the selected type objects, or removes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..06a002aef9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1121,6 +1121,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Cmd/Ctrl+Alt+Shift+. and , (`type.size.increaseByFive`, `type.size.decreaseByFive`) step the font size of the selected type, or of the text the Type tool has selected, by five times the Size/Leading increment (Preferences › Type); Cmd/Ctrl+Shift+. and , still step it by one increment. - Cmd/Ctrl+Alt+Q (`type.resetTracking`) sets the tracking of the selected type, or of the text the Type tool has selected, to 0 and clears manual kerning while keeping the automatic method, in one undo step; at a caret it resets only the kerning there: of the character before it, or at the start of a line the space before the character after it (#5111). - Cmd/Ctrl+Alt+K (`type.highlightKerning`) and Cmd/Ctrl+Alt+Shift+F (`type.highlightFontName`) show the Character panel and give its Kerning field the keyboard focus with the value selected, or open its font family menu with the search field focused, 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 highlighting kerning and the font name field. The page lists the same key for selecting the tracking value; `type.highlightTracking` focuses the Tracking field the same way and has no default key in Keyboard Shortcuts. + - Type › Size ends with Other… (`type.highlightFontSize`), for a size the list does not hold: it shows the Character panel and gives its Font Size field the keyboard focus with the value selected, and the size typed applies on Enter. [The help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=488) describes Other in the Size menu as the way to enter a new size in the Character panel. Selecting the field's value, the separator before Other… and the item being dimmed without selected type are VectorCraft's own choices. - Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, 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 adding a layer through the New Layer dialog box. OK adds the layer above the current layer, and Cancel adds none. Cmd/Ctrl+L still adds a layer without the dialog. - F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does, 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 making a new symbol. OK makes the symbol and puts an instance of it in place of the art, and Cancel makes none. With nothing selected, F8 opens no dialog, and the status bar says that nothing is selected. Shift+F8 and Cmd/Ctrl+F8 still show the Transform and Info panels. - Cmd/Ctrl+Shift+X (`type.resetHorizontalScale`) sets the horizontal scale of the selected type, or of the text the Type tool has selected, to 100% as the Character panel shows it (the object's own stretch included), in one undo step; at a caret it leaves the text as it is. From 7522575af2a51609882e59950750cb76927b2feb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:01:46 -0800 Subject: [PATCH 091/138] MCP: a confined single-file PDF checks only the document it carries With Export PDFs As set to a single file, a PDF row writes the first item's document alone. The check for linked images outside the read roots now looks only at that document, so an image linked in a later asset no longer refuses a file that does not carry it. --- crates/engine/src/cmd/fileio/screens.rs | 4 +++- crates/engine/src/tests/links.rs | 28 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index b702a3fa8c..cca0f85600 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1181,7 +1181,9 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result if crate::file_access::current().is_some() { let mut looked: HashSet<(usize, bool, Option)> = HashSet::new(); for r in rows.iter().filter(|r| !matches!(r.format.id, "svg" | "svgz")) { - for item in items.iter().filter(|i| names_scripts(i, r, single.as_deref())) { + // A single-file PDF carries the first item's document alone, as the writer writes it. + let carried = items.iter().enumerate().filter(|(index, _)| !(single.is_some() && r.format.id == "pdf" && *index > 0)); + for (_, item) in carried.filter(|(_, i)| names_scripts(i, r, single.as_deref())) { let all = item.every_artboard.is_some() && r.format.id == "pdf" && single.is_none(); let board = item.artboard.filter(|_| !all && r.whole_document()); if looked.insert((Arc::as_ptr(&item.doc) as usize, all, board)) diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 313d573206..87dd7453f6 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2542,6 +2542,34 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() { } } +/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first +/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does +/// not refuse it, and one in the first asset does. +#[test] +fn confined_single_file_pdf_checks_the_document_it_carries() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("single-pdf-away"); + let home = Folder::new("single-pdf-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + let placed = place(&mut s, &photo); + let mut assets = vec![]; + for id in [rect, placed] { + assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap()); + } + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); + let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); + let reversed = [assets[1], assets[0]]; + let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{e}"); +} + /// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with /// Preserve Editing, a package's document) carry the document without the Export for Screens /// folder when it is outside the read roots, with the other export settings and the art; the open From edecf9bf4103faa42cbaf75d8d04d2e4d5237803 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:39:54 -0800 Subject: [PATCH 092/138] Shape Builder: the status bar says why a click or drag built nothing A Shape Builder gesture that builds nothing now says why when it is released: "select paths or compound paths" when nothing usable is selected, "select all paths you want to merge" when the pointer is over a path or compound path outside the selection, and "no region under the pointer" otherwise. The message changes nothing in the document, the selection or the undo history, and the next gesture that builds something clears it. A gesture made while a large selection's map is being built gives its message once, when it is replayed. Tools get Action::Status, which the session passes to the status bar; the new message has a row in every complete-message catalog. --- crates/engine/src/tests/build.rs | 33 +++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/builder.rs | 64 ++++++++++++++-- crates/tools/src/builder/tests.rs | 111 ++++++++++++++++++++++++++-- crates/tools/src/input.rs | 4 + 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/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/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/tests.rs | 15 ++++ 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/target-app-parity.md | 1 + 31 files changed, 241 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index cf56247042..75c11d7d80 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -582,6 +582,39 @@ fn shape_builder_tool_drives_the_command() { assert_eq!(layer_children(&s), 1); } +/// A Shape Builder click that builds nothing puts the reason in the status bar and leaves the +/// document, its undo history and the selection as they were; a click that merges shows no status. +#[test] +fn shape_builder_click_that_builds_nothing_shows_why() { + use vectorcraft_tools::builder::{NO_REGION, SELECT_ALL_PATHS, SELECT_PATHS}; + let mut s = session(); + let (a, _) = two(&mut s); + let v = ViewInfo::default(); + s.select_tool("shapeBuilder", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| { + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap() + }; + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone(), st.is_dirty()) + }; + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = state(&s); + assert_eq!(click(&mut s, 125.0, 50.0), vec![UiRequest::Status(SELECT_ALL_PATHS.into())]); + assert_eq!(click(&mut s, 400.0, 400.0), vec![UiRequest::Status(NO_REGION.into())]); + assert_eq!(state(&s), before, "nothing changed"); + s.execute("select.none", &json!({})).unwrap(); + let before = state(&s); + assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(SELECT_PATHS.into())]); + assert_eq!(state(&s), before, "nothing changed"); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(String::new())], "a click that merges clears the status"); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); + assert!(click(&mut s, 25.0, 50.0).is_empty(), "the next merge shows no status"); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); +} + /// A click of the Shape Builder merges over the map the tool built for the hover, as does the /// command over the same inputs with the same gap; another gap needs a map of its own. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..542ee871d3 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1530,6 +1530,7 @@ impl Session { } Action::Dialog(k, p) => ui.push(UiRequest::Dialog(k, p)), Action::SwitchTool(t) => ui.push(UiRequest::SwitchTool(t)), + Action::Status(msg) => ui.push(UiRequest::Status(msg)), Action::Notify(what) => { let view = self.last_view; self.with_tool_cx(view, |t, cx| t.notify(cx, &what)); diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 51617935f5..18825cdfe5 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -211,8 +211,26 @@ pub struct ShapeBuilderTool { prepared: Option>, /// A gesture made while the map of a large selection is being built on another thread. deferred: Option, + /// The button went down with nothing selected: the release says what to select. + empty_press: bool, + /// The last gesture put one of [`SHAPE_BUILDER_STATUS`] in the status bar: the next gesture that + /// builds something clears it. + diagnosed: bool, } +/// The status a Shape Builder gesture gives when the selection holds no path or compound path. +pub const SELECT_PATHS: &str = "Shape Builder: select paths or compound paths"; + +/// The status a Shape Builder gesture that touched nothing gives when it ends over a path or +/// compound path that is not selected. +pub const SELECT_ALL_PATHS: &str = "Shape Builder: select all paths you want to merge"; + +/// The status a Shape Builder gesture that touched nothing gives anywhere else. +pub const NO_REGION: &str = "Shape Builder: no region under the pointer"; + +/// The status messages the Shape Builder tool gives. +pub const SHAPE_BUILDER_STATUS: [&str; 3] = [SELECT_PATHS, SELECT_ALL_PATHS, NO_REGION]; + /// A Shape Builder gesture made while the map of the selection was being built on another /// thread: the map key and the inputs it was made over, its pointer events, which [`Tool::poll`] /// replays once the map is there, and whether the release has come. @@ -455,6 +473,26 @@ impl ShapeBuilderTool { } } + /// Why a gesture released at `p` that touched nothing built nothing: the selection gives no path + /// or compound path ([`SELECT_PATHS`]); the pointer is over a path or compound path that a click + /// can pick and that is neither selected nor inside a selected object ([`SELECT_ALL_PATHS`]); or + /// neither ([`NO_REGION`]). + fn nothing_built(&mut self, cx: &ToolContext, p: Point) -> Action { + self.diagnosed = true; + if self.cache.get(cx, self.opts.open_filled_as_closed).shapes.is_empty() { + return Action::Status(SELECT_PATHS.into()); + } + let unselected = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| { + let chain: Vec = h.ancestry.iter().copied().chain([h.leaf]).collect(); + let path = chain + .iter() + .filter_map(|id| cx.doc.node(*id)) + .any(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })); + path && !chain.iter().any(|id| cx.selection.contains(*id)) + }); + Action::Status(if unselected { SELECT_ALL_PATHS } else { NO_REGION }.into()) + } + /// The cursor swatch preview: the swatch before the current fill, the current fill (ringed) /// and the swatch after it, side by side above the pointer. fn swatch_chips(&self, cx: &ToolContext) -> Vec { @@ -479,7 +517,9 @@ impl Tool for ShapeBuilderTool { vec![] } PointerKind::Down => { - // While a merge is being computed, a press starts no gesture. + // While a merge is being computed, a press starts no gesture. With nothing + // selected, the release says what to select. + self.empty_press = cx.selection.is_empty() && !self.editing(); if cx.selection.is_empty() || self.editing() { return vec![]; } @@ -564,7 +604,7 @@ impl Tool for ShapeBuilderTool { let press = points.first().copied().filter(|s| marquee.is_none() && !self.far && s.distance(p) <= cx.tol(CLICK_TOL_PX)); let split = press.filter(|q| self.stroke_at(cx, *q, erase).is_some()); if std::mem::take(&mut self.touched).is_empty() && split.is_none() { - return vec![]; + return vec![self.nothing_built(cx, p)]; } self.stroke = None; let roots = sorted_roots(cx.doc, &cx.selection.objects); @@ -590,11 +630,17 @@ impl Tool for ShapeBuilderTool { if self.opts.swatches { params["pickColorFrom"] = json!("swatches"); } + // The gesture builds something: the reason the last one built nothing goes. + let mut acts: Vec = std::mem::take(&mut self.diagnosed).then(|| Action::Status(String::new())).into_iter().collect(); // A large selection's merge is computed on another thread; `poll` applies it. - if self.start_merge(cx, ¶ms) { - return vec![]; + if !self.start_merge(cx, ¶ms) { + acts.push(Action::Exec("shapeBuilder.merge".into(), params)); } - vec![Action::Exec("shapeBuilder.merge".into(), params)] + acts + } + PointerKind::Up if std::mem::take(&mut self.empty_press) => { + self.diagnosed = true; + vec![Action::Status(SELECT_PATHS.into())] } _ => vec![], } @@ -693,6 +739,7 @@ impl Tool for ShapeBuilderTool { /// Choosing another tool or another document applies the merge being computed first. fn deactivate(&mut self, cx: &ToolContext) -> Vec { + self.empty_press = false; self.finish_edit(cx) } @@ -735,9 +782,11 @@ impl Tool for ShapeBuilderTool { /// With Pick Color From Color Swatches, the Left and Right arrow keys pick the color swatch /// before or after the current fill. Escape during a drag cancels it: the release after it - /// merges and deletes nothing. + /// merges and deletes nothing, and Escape while a press with nothing selected is held keeps its + /// release from showing a status. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape) + (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) + || ((self.dragging || self.empty_press) && key == ToolKey::Escape) } /// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their @@ -753,6 +802,7 @@ impl Tool for ShapeBuilderTool { } if key == ToolKey::Escape { self.dragging = false; + self.empty_press = false; self.points.clear(); self.touched = Touched::default(); // A gesture recorded while the map is being built is canceled with it. diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index a88c14308b..84e686ccee 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -471,6 +471,106 @@ fn shape_builder_hover_builds_a_small_map_at_once() { assert_eq!((t.cache.builds, t.cache.background), (1, 0)); } +fn status(msg: &str) -> Vec { + vec![Action::Status(msg.into())] +} + +/// A click or drag with nothing selected shows what to select when it is released, and Escape +/// during the press keeps the release quiet. +#[test] +fn shape_builder_with_nothing_selected_says_what_to_select() { + let (d, _, _) = two_rects(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS), "a click"); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 125.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_PATHS), "a drag"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)).is_empty(), "a release without a press"); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)).is_empty(), "a canceled press"); + assert!(!t.claims_key(&cx, ToolKey::Escape)); +} + +/// With A of the overlapping squares A and B selected, a click on the part of B outside A builds +/// nothing and says to select every path to merge; a click on empty canvas says there is no +/// region; a click inside A still merges A alone and clears that status, and the click after it +/// gives the merge alone. +#[test] +fn shape_builder_names_the_unselected_path_under_a_release_that_built_nothing() { + let (d, a, _) = two_rects(); + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_ALL_PATHS)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION)); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!( + matches!(acts.as_slice(), [Action::Status(m), Action::Exec(id, v)] if m.is_empty() && id == "shapeBuilder.merge" && v["ids"] == json!([a.0])), + "{acts:?}" + ); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "shapeBuilder.merge"), "{acts:?}"); + // A locked or hidden B cannot be picked, so the release says there is no region. + for hide in [false, true] { + let (mut d, a, b) = two_rects(); + let n = d.node_mut(b).unwrap(); + if hide { + n.visible = false; + } else { + n.locked = true; + } + let mut s = Selection::default(); + s.set([a]); + let cx = crate::testutil::cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(NO_REGION), "hidden: {hide}"); + } +} + +/// A selection that holds no path or compound path says to select one. +#[test] +fn shape_builder_with_no_path_selected_says_to_select_paths() { + let (mut d, a, _) = two_rects(); + d.node_mut(a).unwrap().locked = true; + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS)); +} + +/// A gesture made while the map of a large selection is being built and released over nothing +/// gives its status once, when it is replayed. +#[test] +fn shape_builder_replayed_gesture_over_nothing_gives_its_status_once() { + let (d, s) = square_row(200); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, 15.0, 10.0)); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 450.0, 450.0)).is_empty()); + assert_eq!(t.cache.builds, 0, "the gesture did not wait for the map"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 450.0, 450.0)).is_empty(), "the gesture waits for the map"); + assert!(t.editing()); + assert_eq!(t.finish_edit(&cx), status(NO_REGION)); + assert!(t.finish_edit(&cx).is_empty() && !t.editing()); +} + #[test] fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let (d, a, b) = two_rects(); @@ -485,7 +585,7 @@ fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let Action::Exec(_, v) = &acts[0] else { panic!() }; assert_eq!(v["erase"], true); t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION), "the release edits nothing and says why"); } /// Squares A (0..100) and B (50..150 both ways), overlapping at a corner, selected. @@ -998,9 +1098,9 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, 0.5, 27.0)); let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; assert_eq!((&v["splitStroke"], &v["points"]), (&json!(true), &json!([[-1.0, 25.0]]))); - // A release farther away is a drag, which splits nothing. + // A release farther away is a drag, which splits nothing and says it touched no region. t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)), status(NO_REGION)); // So is a Straight Line drag that goes away and ends back near the press. t.set_option("selection", &json!("straightLine")); t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); @@ -1008,11 +1108,12 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, -0.5, 25.5)); assert!(!acts.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("splitStroke").is_some())), "{acts:?}"); t.set_option("selection", &json!("freeform")); - // A drag merges as before and sends no switch. + // A drag merges as before and sends no switch; it clears the status the drag before it gave. t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 75.0)); let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 75.0)); - let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + let [Action::Status(m), Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(m.is_empty(), "{m}"); assert!(v.get("splitStroke").is_none(), "{v}"); } diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 5362147b97..629970b066 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -218,4 +218,8 @@ pub enum Action { SwitchTool(String), /// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object). Notify(String), + /// Show this English message in the status bar (e.g. why a Shape Builder gesture built + /// nothing); an empty message clears the status bar. It changes nothing in the document and + /// records no undo step. + Status(String), } diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..2a70892ce6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6392,6 +6392,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg shadings of more than 4096 patches or triangles were left out els ombrejats de més de 4096 pedaços o triangles s’han omès @msg shadings whose functions are of an unknown type are filled with their middle colour els ombrejats les funcions dels quals són d’un tipus desconegut s’omplen amb el seu color central @msg Shape Builder: no region under the pointer Constructor de formes: no hi ha cap regió sota el punter +@msg Shape Builder: select all paths you want to merge Constructor de formes: selecciona tots els traçats que vulguis combinar @msg Shape Builder: select paths or compound paths Constructor de formes: selecciona traçats o traçats compostos @msg shortcut for `{k}` must be a string la drecera de `{k}` ha de ser una cadena @msg Show All Hidden Attributes: nothing is hidden Mostra tots els atributs ocults: no hi ha res d’ocult diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..bf55ba52ee 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4972,6 +4972,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Saved {path} Uloženo: {path} @msg Select text or click into text with the Type tool to insert glyphs Glyfy vložíte, když vyberete text nebo do něj kliknete nástrojem Text @msg Shape Builder: no region under the pointer Tvorba tvarů: pod ukazatelem není žádná oblast +@msg Shape Builder: select all paths you want to merge Tvorba tvarů: vyberte všechny cesty, které chcete sloučit @msg Shape Builder: select paths or compound paths Tvorba tvarů: vyberte cesty nebo složené cesty @msg Show All Hidden Attributes: nothing is hidden Zobrazit všechny skryté atributy: nic není skryto @msg Split Into Grid: select paths large enough for the grid Rozdělit do mřížky: vyberte cesty dost velké pro mřížku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..06d6b5b42c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7181,6 +7181,7 @@ imageTrace Outline Kontur @msg Saved {path} Gemte {path} @msg Select text or click into text with the Type tool to insert glyphs Markér tekst, eller klik i tekst med tekstværktøjet, for at indsætte glyffer @msg Shape Builder: no region under the pointer Figurbygger: intet område under markøren +@msg Shape Builder: select all paths you want to merge Figurbygger: markér alle kurver, du vil flette @msg Shape Builder: select paths or compound paths Figurbygger: markér kurver eller sammensatte kurver @msg Show All Hidden Attributes: nothing is hidden Vis alle skjulte attributter: intet er skjult @msg Split Into Grid: select paths large enough for the grid Opdel i gitter: markér kurver, der er store nok til gitteret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..9e5a5a12a9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4570,6 +4570,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Saved {path} {path} gespeichert @msg Select text or click into text with the Type tool to insert glyphs Wählen Sie Text aus oder klicken Sie mit dem Text-Werkzeug in einen Text, um Glyphen einzufügen @msg Shape Builder: no region under the pointer Formerstellung: kein Bereich unter dem Zeiger +@msg Shape Builder: select all paths you want to merge Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten @msg Shape Builder: select paths or compound paths Formerstellung: Wählen Sie Pfade oder zusammengesetzte Pfade aus @msg Show All Hidden Attributes: nothing is hidden Alle ausgeblendeten Attribute einblenden: Es ist nichts ausgeblendet @msg Split Into Grid: select paths large enough for the grid In Raster teilen: Wählen Sie Pfade aus, die groß genug für das Raster sind diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..7f0d2c21ca 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2667,6 +2667,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Saved {path} Αποθηκεύτηκε το {path} @msg Select text or click into text with the Type tool to insert glyphs Επιλέξτε κείμενο ή κάντε κλικ μέσα σε κείμενο με το εργαλείο κειμένου για εισαγωγή γλύφων @msg Shape Builder: no region under the pointer Δημιουργία σχημάτων: δεν υπάρχει περιοχή κάτω από τον δείκτη +@msg Shape Builder: select all paths you want to merge Δημιουργία σχημάτων: επιλέξτε όλες τις διαδρομές που θέλετε να συγχωνεύσετε @msg Shape Builder: select paths or compound paths Δημιουργία σχημάτων: επιλέξτε διαδρομές ή σύνθετες διαδρομές @msg Show All Hidden Attributes: nothing is hidden Εμφάνιση όλων των κρυφών χαρακτηριστικών: δεν υπάρχουν κρυφά χαρακτηριστικά @msg Split Into Grid: select paths large enough for the grid Διαίρεση σε πλέγμα: επιλέξτε αρκετά μεγάλες διαδρομές για το πλέγμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..d03ab51f1f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4676,6 +4676,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Saved {path} Se guardó {path} @msg Select text or click into text with the Type tool to insert glyphs Selecciona texto o haz clic dentro del texto con la herramienta Texto para insertar glifos @msg Shape Builder: no region under the pointer Generador de formas: no hay ninguna región bajo el puntero +@msg Shape Builder: select all paths you want to merge Generador de formas: selecciona todos los trazados que quieras combinar @msg Shape Builder: select paths or compound paths Generador de formas: selecciona trazados o trazados compuestos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos los atributos ocultos: no hay nada oculto @msg Split Into Grid: select paths large enough for the grid Dividir en cuadrícula: selecciona trazados lo bastante grandes para la cuadrícula diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..1b04d476f6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4909,6 +4909,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Saved {path} Tallennettiin {path} @msg Select text or click into text with the Type tool to insert glyphs Valitse tekstiä tai napsauta tekstiin tekstityökalulla, niin voit lisätä merkkejä @msg Shape Builder: no region under the pointer Muodonmuodostin: osoittimen alla ei ole aluetta +@msg Shape Builder: select all paths you want to merge Muodonmuodostin: valitse kaikki polut, jotka haluat yhdistää @msg Shape Builder: select paths or compound paths Muodonmuodostin: valitse polkuja tai yhdistelmäpolkuja @msg Show All Hidden Attributes: nothing is hidden Näytä kaikki piilotetut attribuutit: mitään ei ole piilotettu @msg Split Into Grid: select paths large enough for the grid Jaa ruudukoksi: valitse ruudukolle riittävän suuret polut diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..a76032a6d2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4638,6 +4638,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Saved {path} {path} enregistré @msg Select text or click into text with the Type tool to insert glyphs Sélectionnez du texte ou cliquez dans un texte avec l’outil Texte pour insérer des glyphes @msg Shape Builder: no region under the pointer Concepteur de forme : aucune zone sous le pointeur +@msg Shape Builder: select all paths you want to merge Concepteur de forme : sélectionnez tous les tracés à fusionner @msg Shape Builder: select paths or compound paths Concepteur de forme : sélectionnez des tracés ou des tracés transparents @msg Show All Hidden Attributes: nothing is hidden Afficher tous les attributs masqués : rien n’est masqué @msg Split Into Grid: select paths large enough for the grid Découper en grille : sélectionnez des tracés assez grands pour la grille diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..b5dd19aed6 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8221,6 +8221,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg shadings of more than 4096 patches or triangles were left out 4096 से अधिक पैच या त्रिकोणों के छायांकन को छोड़ दिया गया था @msg shadings whose functions are of an unknown type are filled with their middle colour छायांकन जिसका कार्य अज्ञात प्रकार के होते हैं, उनके मध्य रंग से भरे होते हैं @msg Shape Builder: no region under the pointer आकृति बिल्डर: सूचक के तहत कोई क्षेत्र नहीं +@msg Shape Builder: select all paths you want to merge आकृति बिल्डर: वे सभी पाथ सिलेक्ट करें जिन्हें आप मर्ज करना चाहते हैं @msg Shape Builder: select paths or compound paths आकृति बिल्डर: पाथ या मिश्रित पाथ सिलेक्ट करें @msg Shaper needs 1–64 source paths शेपर के लिए 1–64 स्रोत पाथ चाहिए @msg shortcut for `{k}` must be a string `{k}` के लिए शॉर्टकट एक स्ट्रिंग होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..a1eedeb72e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5904,6 +5904,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg shadings of more than 4096 patches or triangles were left out kimaradtak a 4096-nál több foltból vagy háromszögből álló árnyalások @msg shadings whose functions are of an unknown type are filled with their middle colour az ismeretlen típusú függvényt használó árnyalások a középső színükkel kitöltve jelennek meg @msg Shape Builder: no region under the pointer Alakzatépítő: a mutató alatt nincs terület +@msg Shape Builder: select all paths you want to merge Alakzatépítő: jelöld ki az összes egyesítendő útvonalat @msg Shape Builder: select paths or compound paths Alakzatépítő: jelölj ki útvonalakat vagy összetett útvonalakat @msg shortcut for `{k}` must be a string `{k}` billentyűparancsa csak szöveg lehet @msg Show All Hidden Attributes: nothing is hidden Összes rejtett attribútum megjelenítése: nincs rejtett elem diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..e5cb65be6f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4704,6 +4704,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Saved {path} Salvato {path} @msg Select text or click into text with the Type tool to insert glyphs Seleziona del testo o fai clic nel testo con lo strumento Testo per inserire glifi @msg Shape Builder: no region under the pointer Generatore forme: nessuna regione sotto il puntatore +@msg Shape Builder: select all paths you want to merge Generatore forme: seleziona tutti i tracciati da unire @msg Shape Builder: select paths or compound paths Generatore forme: seleziona tracciati o tracciati composti @msg Show All Hidden Attributes: nothing is hidden Mostra tutti gli attributi nascosti: non c'è nulla di nascosto @msg Split Into Grid: select paths large enough for the grid Dividi in griglia: seleziona tracciati abbastanza grandi per la griglia diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..2efb701c91 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4570,6 +4570,7 @@ swatch Bright Violet ビビッドバイオレット @msg Live Paint: select paths or compound paths ライブペイント: パスまたは複合パスを選択してください @msg Live Paint: these paths are too degenerate to paint ライブペイント: これらのパスは形状がつぶれすぎていてペイントできません @msg Shape Builder: no region under the pointer シェイプ形成ツール: ポインターの下に領域がありません +@msg Shape Builder: select all paths you want to merge シェイプ形成ツール: 結合するパスをすべて選択してください @msg Shape Builder: select paths or compound paths シェイプ形成ツール: パスまたは複合パスを選択してください @msg image data `{_1}` is missing 画像データ `{_1}` が見つかりません @msg no Live Paint edge near that point その位置の近くにライブペイントのエッジがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..840c2d9d55 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6392,6 +6392,7 @@ font-technology Variable ცვლადი @msg Saved {path} შენახულია: {path} @msg Select text or click into text with the Type tool to insert glyphs გლიფების ჩასასმელად მონიშნეთ ტექსტი ან ტექსტის ხელსაწყოთი დაწკაპეთ ტექსტში @msg Shape Builder: no region under the pointer ფიგურების კონსტრუქტორი: მაჩვენებლის ქვეშ არე არ არის +@msg Shape Builder: select all paths you want to merge ფიგურების კონსტრუქტორი: მონიშნეთ ყველა ტრაექტორია, რომლის გაერთიანებაც გსურთ @msg Shape Builder: select paths or compound paths ფიგურების კონსტრუქტორი: მონიშნეთ ტრაექტორიები ან შედგენილი ტრაექტორიები @msg Show All Hidden Attributes: nothing is hidden ყველა დამალული ატრიბუტის ჩვენება: დამალული არაფერია @msg Split Into Grid: select paths large enough for the grid ბადედ გაყოფა: მონიშნეთ ბადისთვის საკმარისად დიდი ტრაექტორიები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..1ff2189c69 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4497,6 +4497,7 @@ theme Appearance 외관 @msg Live Paint: select paths or compound paths 라이브 페인트: 패스 또는 컴파운드 패스를 선택하세요 @msg Live Paint: these paths are too degenerate to paint 라이브 페인트: 이 패스는 퇴화되어 칠할 수 없습니다 @msg Shape Builder: no region under the pointer 모양 빌더: 포인터 아래에 영역이 없습니다 +@msg Shape Builder: select all paths you want to merge 모양 빌더: 병합할 패스를 모두 선택하세요 @msg Shape Builder: select paths or compound paths 모양 빌더: 패스 또는 컴파운드 패스를 선택하세요 @msg image data `{_1}` is missing 이미지 데이터 `{_1}`이(가) 없습니다 @msg no Live Paint edge near that point 그 지점 근처에 라이브 페인트 가장자리가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..8d7a07ef4b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5076,6 +5076,7 @@ imageTrace Outline Contour @msg Saved {path} {path} opgeslagen @msg Select text or click into text with the Type tool to insert glyphs Selecteer tekst of klik met het tekstgereedschap in tekst om glyphs in te voegen @msg Shape Builder: no region under the pointer Vormbouwer: geen gebied onder de aanwijzer +@msg Shape Builder: select all paths you want to merge Vormbouwer: selecteer alle paden die je wilt samenvoegen @msg Shape Builder: select paths or compound paths Vormbouwer: selecteer paden of samengestelde paden @msg Show All Hidden Attributes: nothing is hidden Alle verborgen kenmerken tonen: er is niets verborgen @msg Split Into Grid: select paths large enough for the grid In raster verdelen: selecteer paden die groot genoeg zijn voor het raster diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..27a3e7a0e4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4795,6 +4795,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Saved {path} Zapisano {path} @msg Select text or click into text with the Type tool to insert glyphs Zaznacz tekst lub kliknij w tekst narzędziem Tekst, aby wstawić glify @msg Shape Builder: no region under the pointer Kreator kształtów: brak obszaru pod wskaźnikiem +@msg Shape Builder: select all paths you want to merge Kreator kształtów: zaznacz wszystkie ścieżki, które chcesz scalić @msg Shape Builder: select paths or compound paths Kreator kształtów: zaznacz ścieżki lub ścieżki złożone @msg Show All Hidden Attributes: nothing is hidden Pokaż wszystkie ukryte atrybuty: nic nie jest ukryte @msg Split Into Grid: select paths large enough for the grid Podziel na siatkę: zaznacz ścieżki wystarczająco duże dla siatki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..b21daa38e2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3991,6 +3991,7 @@ axis Both Ambos @msg Saved {path} {path} salvo @msg Select text or click into text with the Type tool to insert glyphs Selecione texto ou clique em um texto com a ferramenta Texto para inserir glifos @msg Shape Builder: no region under the pointer Criador de formas: nenhuma região sob o ponteiro +@msg Shape Builder: select all paths you want to merge Criador de formas: selecione todos os traçados que deseja mesclar @msg Shape Builder: select paths or compound paths Criador de formas: selecione traçados ou traçados compostos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos os atributos ocultos: nada está oculto @msg Split Into Grid: select paths large enough for the grid Dividir em grade: selecione traçados grandes o bastante para a grade diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..7b03b0cb13 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4700,6 +4700,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Saved {path} Сохранено: {path} @msg Select text or click into text with the Type tool to insert glyphs Выделите текст или щёлкните внутри текста инструментом «Текст», чтобы вставить глифы @msg Shape Builder: no region under the pointer Создание фигур: под указателем нет области +@msg Shape Builder: select all paths you want to merge Создание фигур: выделите все контуры, которые нужно объединить @msg Shape Builder: select paths or compound paths Создание фигур: выделите контуры или составные контуры @msg Show All Hidden Attributes: nothing is hidden Показать все скрытые атрибуты: ничего не скрыто @msg Split Into Grid: select paths large enough for the grid Разделение на сетку: выделите контуры, достаточно большие для сетки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..a30113b183 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4582,6 +4582,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Saved {path} Sparade {path} @msg Select text or click into text with the Type tool to insert glyphs Markera text eller klicka i text med textverktyget för att infoga glyfer @msg Shape Builder: no region under the pointer Formbyggare: inget område under pekaren +@msg Shape Builder: select all paths you want to merge Formbyggare: markera alla banor du vill sammanfoga @msg Shape Builder: select paths or compound paths Formbyggare: markera banor eller sammansatta banor @msg Show All Hidden Attributes: nothing is hidden Visa alla dolda attribut: ingenting är dolt @msg Split Into Grid: select paths large enough for the grid Dela upp i rutnät: markera banor som är tillräckligt stora för rutnätet diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0daefad24a..99bac818f5 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -451,6 +451,21 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The status messages the Shape Builder tool gives when a gesture builds nothing come from the +/// tools crate, which [`message_literals`] does not scan, so every complete catalog is checked for +/// them here. +#[test] +fn shape_builder_status_messages_are_in_complete_catalogs() { + use vectorcraft_tools::builder::SHAPE_BUILDER_STATUS; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in SHAPE_BUILDER_STATUS { + assert_ne!(message(lang, s), s, "{code}: {s}"); + } + } + assert_eq!(message(de(), SHAPE_BUILDER_STATUS[1]), "Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten"); +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..70e6670c99 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4413,6 +4413,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Saved {path} {path} kaydedildi @msg Select text or click into text with the Type tool to insert glyphs Glif eklemek için metni seçin veya Yazım aracıyla metne tıklayın @msg Shape Builder: no region under the pointer Şekil Oluşturucu: işaretçinin altında bölge yok +@msg Shape Builder: select all paths you want to merge Şekil Oluşturucu: birleştirmek istediğiniz tüm yolları seçin @msg Shape Builder: select paths or compound paths Şekil Oluşturucu: yolları veya bileşik yolları seçin @msg Show All Hidden Attributes: nothing is hidden Tüm Gizli Özellikleri Göster: hiçbir şey gizli değildir @msg Split Into Grid: select paths large enough for the grid Izgaraya Böl: ızgara için yeterince büyük yollar seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..0045f02543 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4688,6 +4688,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Saved {path} Збережено: {path} @msg Select text or click into text with the Type tool to insert glyphs Виділіть текст або клацніть всередині тексту інструментом «Текст», щоб вставити гліфи @msg Shape Builder: no region under the pointer Створення фігур: під вказівником немає області +@msg Shape Builder: select all paths you want to merge Створення фігур: виділіть усі контури, які потрібно об’єднати @msg Shape Builder: select paths or compound paths Створення фігур: виділіть контури або складені контури @msg Show All Hidden Attributes: nothing is hidden Показати всі приховані атрибути: нічого не приховано @msg Split Into Grid: select paths large enough for the grid Поділ на сітку: виділіть контури, досить великі для сітки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..35c8793bbc 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5592,6 +5592,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg shadings of more than 4096 patches or triangles were left out các vùng tô có hơn 4096 mảnh hoặc tam giác đã bị bỏ qua @msg shadings whose functions are of an unknown type are filled with their middle colour các vùng tô có hàm loại không xác định được tô bằng màu giữa @msg Shape Builder: no region under the pointer Xây dựng hình dạng: không có vùng nào dưới con trỏ +@msg Shape Builder: select all paths you want to merge Xây dựng hình dạng: chọn tất cả đường dẫn bạn muốn hợp nhất @msg Shape Builder: select paths or compound paths Xây dựng hình dạng: chọn đường dẫn hoặc đường dẫn phức @msg shortcut for `{k}` must be a string phím tắt cho `{k}` phải là chuỗi @msg Show All Hidden Attributes: nothing is hidden Hiện tất cả thuộc tính ẩn: không có gì bị ẩn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..932d8a96a1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4284,6 +4284,7 @@ imageTrace Outline 轮廓 @msg Live Paint: select paths or compound paths 实时上色:请选择路径或复合路径 @msg Live Paint: these paths are too degenerate to paint 实时上色:这些路径过于退化,无法上色 @msg Shape Builder: no region under the pointer 形状生成器:指针下方没有区域 +@msg Shape Builder: select all paths you want to merge 形状生成器:请选择要合并的所有路径 @msg Shape Builder: select paths or compound paths 形状生成器:请选择路径或复合路径 @msg image data `{_1}` is missing 缺少图像数据 `{_1}` @msg no Live Paint edge near that point 该点附近没有实时上色边缘 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..24e3f3e4b2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1915,6 +1915,7 @@ file-filter Templates 範本 @msg Live Paint: select paths or compound paths 即時上色:請選取路徑或複合路徑 @msg Live Paint: these paths are too degenerate to paint 即時上色:這些路徑過度退化,無法上色 @msg Shape Builder: no region under the pointer 形狀建立:指標下方沒有區域 +@msg Shape Builder: select all paths you want to merge 形狀建立:請選取要合併的所有路徑 @msg Shape Builder: select paths or compound paths 形狀建立:請選取路徑或複合路徑 @msg image data `{_1}` is missing 找不到影像資料 `{_1}` @msg no Live Paint edge near that point 該點附近沒有即時上色邊緣 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..58b230f0cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1295,6 +1295,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). + The Shape Builder works on the selected paths, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. As VectorCraft's own rule, a click or drag that builds nothing says why in the status bar when it is released: "Shape Builder: select paths or compound paths" when nothing is selected or the selection holds no unlocked, visible path; "Shape Builder: select all paths you want to merge" when the release is over a path or compound path that is not selected; and "Shape Builder: no region under the pointer" otherwise. The document, the selection and the undo history stay as they were, and the next gesture that builds something clears the message. Regression tests: `shape_builder_with_nothing_selected_says_what_to_select`, `shape_builder_names_the_unselected_path_under_a_release_that_built_nothing` and `shape_builder_replayed_gesture_over_nothing_gives_its_status_once` in `builder/tests.rs`, and `tests::build::shape_builder_click_that_builds_nothing_shows_why`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). From 28f492043f7c67d4dee81b753d70d1d159ee68df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 05:51:07 -0800 Subject: [PATCH 093/138] =?UTF-8?q?Expand:=20Alt/Option=20on=20Object=20?= =?UTF-8?q?=E2=80=BA=20Expand=E2=80=A6=20expands=20at=20once=20with=20the?= =?UTF-8?q?=20last=20OK'd=20choices?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Expand dialog now keeps the Object, Fill, Stroke, Expand Gradient To and steps choices that OK last expanded with, until the app quits, and opens on them. Cancel and an OK that fails leave them as they were. Choosing Object › Expand… in the in-window menu bar with Alt (Option on macOS) held expands the selection at once with those choices, in one undo step, as OK would. Before any OK it uses the dialog's defaults. When none of the choices has something to expand in the selection, the dialog opens on them instead and nothing changes. The help page describes the shortcut for gradients: https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html ui.expandDialog takes immediate?: bool for this. A null immediate is treated as omitted, and any other value that is not true or false is an error. --- crates/ui-egui/src/dialogs/expand.rs | 193 +++++++++++++++++++++++- crates/ui-egui/src/menus/invoke.rs | 4 +- crates/ui-egui/src/menus/run.rs | 6 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/state.rs | 6 + docs/mcp.md | 11 ++ docs/target-app-parity.md | 1 + 7 files changed, 212 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/expand.rs b/crates/ui-egui/src/dialogs/expand.rs index 383ea567df..cda98afada 100644 --- a/crates/ui-egui/src/dialogs/expand.rs +++ b/crates/ui-egui/src/dialogs/expand.rs @@ -1,7 +1,9 @@ //! Object → Expand: what to expand (Object: live shapes, type and effects; Fill: gradient and pattern fills; //! Stroke: strokes into filled outlines) and what gradient fills become (a gradient mesh, or a //! number of objects). Options the selection has nothing for are disabled. OK runs -//! `object.expand` as one undo step. +//! `object.expand` as one undo step and keeps its choices for the rest of the app's run: the dialog +//! opens on them, and Object › Expand… chosen with Alt (Option) expands with them at once +//! ([`expand_now`]). //! //! Fields: `object`, `fill`, `stroke`, `gradient` (`objects` | `mesh`), `steps` (1..1000), and //! `__object`, `__fill`, `__stroke` (that option has something to expand: `object.expand.info`), @@ -31,15 +33,51 @@ pub(crate) fn appearance_first() -> &'static str { tl!("Expand Appearance first (Object › Expand Appearance)") } -/// Open Expand for the selection, every option on (as `object.expand {}` does). A selection with -/// appearance attributes (effects, several fills or strokes…) refuses with [`appearance_first`]: -/// the menu item is dimmed for it. +/// Open Expand for the selection, on the choices OK last expanded with in this run of the app, or +/// every option on (as `object.expand {}` does) before that. A selection with appearance attributes +/// (effects, several fills or strokes…) refuses with [`appearance_first`]: the menu item is dimmed +/// for it. pub fn open(app: &mut VectorcraftApp) -> Result { + let fields = fields(app)?; + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(Value::Null) +} + +/// Object › Expand… chosen with Alt (Option): expand the selection at once, in one undo step, with +/// the choices OK last expanded with in this run of the app (the dialog's defaults before that), as +/// OK in the dialog opened on them would. When none of those choices has something to expand in the +/// selection, the dialog opens on them instead, and nothing changes. A selection with appearance +/// attributes refuses with [`appearance_first`], as [`open`] does. +pub fn expand_now(app: &mut VectorcraftApp) -> Result { + let d = Dialog::new(KIND, fields(app)?); + if !OPTIONS.iter().any(|(key, _)| d.bool(key) && option_enabled(&d, key)) { + app.ui.dialog = Some(d); + return Ok(Value::Null); + } + app.run(CMD, params(&d)) +} + +/// The choices OK last expanded with (`app.ui.expand_options`), when each one holds a value the +/// dialog shows: a switch for Object, Fill and Stroke, `objects` or `mesh`, and 1 to 1000 steps. +fn remembered(app: &VectorcraftApp) -> Option<&Value> { + let o = &app.ui.expand_options; + let switches = OPTIONS.iter().all(|(key, _)| o[key].is_boolean()); + let gradient = matches!(o["gradient"].as_str(), Some("objects" | "mesh")); + let steps = o["steps"].as_f64().is_some_and(|n| (1.0..=MAX_STEPS as f64).contains(&n.round())); + (switches && gradient && steps).then_some(o) +} + +/// The dialog's fields for the selection: the remembered choices (or the defaults) and what each +/// option has to expand. +fn fields(app: &mut VectorcraftApp) -> Result { let info = app.session.execute("object.expand.info", &json!({})).map_err(|e| e.to_string())?; if info["appearance"] == json!(true) { return Err(appearance_first().into()); } - let mut fields = json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}); + let mut fields = match remembered(app) { + Some(o) => json!({"object": o["object"], "fill": o["fill"], "stroke": o["stroke"], "gradient": o["gradient"], "steps": o["steps"]}), + None => json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": DEFAULT_STEPS}), + }; for (key, _) in OPTIONS { fields[format!("__{key}")] = info[key].clone(); } @@ -47,8 +85,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { for key in ["fill", "stroke", "gradient"] { fields[format!("__{key}_symbol")] = json!(info["symbolArt"][key] == json!(true)); } - app.ui.dialog = Some(Dialog::new(KIND, fields)); - Ok(Value::Null) + Ok(fields) } fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { @@ -112,8 +149,12 @@ fn params(d: &Dialog) -> Value { }) } +/// OK: expand, and keep the choices once the expansion succeeded. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - run_and_close(app, CMD, params(d)) + let choices = params(d); + let r = run_and_close(app, CMD, choices.clone())?; + app.ui.expand_options = choices; + Ok(r) } #[cfg(test)] @@ -253,4 +294,140 @@ mod tests { app.run("select.none", json!({})).unwrap(); assert!(!crate::menus::enabled(&app, "ui.expandDialog")); } + + /// A rectangle with a linear gradient fill and no stroke is selected. + fn gradient_rectangle(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + app.run("paint.setFill", json!({"gradient": {"kind": "linear"}})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + } + + /// Object › Expand… from the in-window menu, with Alt held or not. + fn choose_expand(app: &mut VectorcraftApp, alt: bool) { + let entries = crate::menus::menu_entries(app); + let e = entries.iter().find(|e| e.path == ["Object"] && e.label == "Expand…").expect("Object › Expand…"); + assert!(e.enabled, "Expand… is available"); + let target = crate::menus::click_target(&e.label, e.command.as_deref().unwrap(), &e.params); + let held = if alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE }; + let (cmd, p) = crate::menus::with_held_keys(target, held); + crate::menus::invoke(app, &cmd, p); + } + + /// Whether the selected object is a clip group holding a gradient mesh (Expand Gradient To › + /// Gradient Mesh) rather than solid objects. + fn expanded_to_a_mesh(app: &VectorcraftApp) -> bool { + let st = app.session.doc().unwrap(); + let g = st.doc.node(st.selection.objects[0]).unwrap(); + let NodeKind::Group { children, clip: true } = &g.kind else { panic!("a clip group: {:?}", g.kind) }; + children.iter().any(|c| matches!(c.kind, NodeKind::Mesh(_))) + } + + #[test] + fn the_dialog_opens_on_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + let d = app.ui.dialog.as_mut().expect("the Expand dialog"); + d.fields.insert("gradient".into(), json!("mesh")); + d.fields.insert("steps".into(), json!(12)); + d.fields.insert("stroke".into(), json!(false)); + super::super::confirm(&mut app).unwrap(); + assert!(expanded_to_a_mesh(&app)); + app.run("edit.undo", json!({})).unwrap(); + let kept = json!({"object": true, "fill": true, "stroke": false, "gradient": "mesh", "steps": 12.0}); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept, "it opens on the choices OK expanded with"); + // Cancel leaves them as they were. + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("objects")); + super::super::cancel(&mut app); + assert_eq!(app.ui.expand_options, kept); + // So does an OK that fails, and nothing changes. + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("steps".into(), json!(5000)); + let before = app.session.doc().unwrap().doc.clone(); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.ui.expand_options, kept); + choose_expand(&mut app, false); + assert_eq!(params(app.ui.dialog.as_ref().unwrap()), kept); + } + + #[test] + fn alt_expands_at_once_with_the_choices_ok_last_expanded_with() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + choose_expand(&mut app, false); + app.ui.dialog.as_mut().unwrap().fields.insert("gradient".into(), json!("mesh")); + super::super::confirm(&mut app).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + assert!(expanded_to_a_mesh(&app), "the kept Gradient Mesh choice"); + } + + #[test] + fn alt_before_any_ok_expands_with_the_defaults() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + assert!(app.ui.dialog.is_none(), "no dialog"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert!(!expanded_to_a_mesh(&app), "the gradient becomes objects, the default"); + assert!(app.ui.expand_options.is_null(), "Alt keeps no choices of its own"); + } + + #[test] + fn alt_opens_the_dialog_when_the_kept_choices_expand_nothing_in_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 60})).unwrap(); + // Fill alone was kept, and a plain rectangle has no gradient or pattern fill. + app.ui.expand_options = json!({"object": false, "fill": true, "stroke": false, "gradient": "objects", "steps": 255.0}); + let before = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + choose_expand(&mut app, true); + let d = app.ui.dialog.as_ref().expect("the Expand dialog"); + assert_eq!(params(d), app.ui.expand_options, "it opens on the kept choices"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing recorded"); + assert_eq!(app.session.doc().unwrap().doc, before); + } + + #[test] + fn alt_refuses_a_selection_with_appearance_attributes_and_a_bad_immediate() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + zig_zag_line(&mut app); + let before = app.session.doc().unwrap().doc.clone(); + assert_eq!(app.run("ui.expandDialog", json!({"immediate": true})).unwrap_err(), appearance_first()); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc, before, "the line is left as it was"); + app.run("effect.expandAppearance", json!({})).unwrap(); + assert!(app.run("ui.expandDialog", json!({"immediate": "yes"})).is_err()); + assert!(app.ui.dialog.is_none()); + app.run("ui.expandDialog", json!({"immediate": false})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + } + + #[test] + fn kept_choices_with_a_value_the_dialog_does_not_show_are_left_out() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + gradient_rectangle(&mut app); + for bad in [ + json!({"object": "yes", "fill": true, "stroke": true, "gradient": "mesh", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "strips", "steps": 12}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh", "steps": 0}), + json!({"object": true, "fill": true, "stroke": true, "gradient": "mesh"}), + ] { + app.ui.expand_options = bad; + app.run("ui.expandDialog", json!({})).unwrap(); + assert_eq!( + params(app.ui.dialog.as_ref().unwrap()), + json!({"object": true, "fill": true, "stroke": true, "gradient": "objects", "steps": 255.0}) + ); + app.ui.dialog = None; + } + } } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 3e48476a1a..206072dadd 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -17,10 +17,12 @@ pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { /// What an in-window menu click on `target` (a [`click_target`]) runs with `held` held: Object › /// Unlock All and Object › Show All chosen with Shift+Alt (Shift+Option) act only inside the groups /// that hold the selected objects (`scope: "group"`); Select Linked, Embedded, Missing and Modified -/// chosen with Shift add to the selection (`add: true`). +/// chosen with Shift add to the selection (`add: true`); Object › Expand… chosen with Alt (Option) +/// expands at once with the choices its dialog last expanded with (`immediate: true`). pub(crate) fn with_held_keys(target: (String, Value), held: egui::Modifiers) -> (String, Value) { match target.0.as_str() { "object.unlockAll" | "object.showAll" if held.shift && held.alt => (target.0, json!({"scope": "group"})), + "ui.expandDialog" if held.alt => (target.0, json!({"immediate": true})), // Select Linked, Embedded, Missing and Modified with Shift add to the selection. crate::addons::select::link_status::COMMAND if held.shift => (target.0, crate::addons::select::link_status::with_shift(target.1)), _ => target, diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 495e606d6c..1f4f4a0b73 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -905,7 +905,11 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); let r = match id { - "ui.expandDialog" => crate::dialogs::expand::open(app), + "ui.expandDialog" => match opt_bool(p, "immediate") { + Ok(Some(true)) => crate::dialogs::expand::expand_now(app), + Ok(_) => crate::dialogs::expand::open(app), + Err(e) => Err(e), + }, "ui.simplifyAuto" => crate::dialogs::simplify_slider::auto(app), "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::more_options(app), "ui.smoothAuto" => crate::dialogs::smooth_slider::auto(app), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ced961e32c..b6b8a3165b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1265,7 +1265,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.expandDialog", "Expand…", "", - "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + "{immediate?: bool (false)} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255), or the choices OK last expanded with since the app started): OK runs object.expand with them as one undo step and keeps them until the app quits; immediate: true (the menu item chosen with Alt/Option) runs object.expand at once with those choices (the defaults before any OK), and opens the dialog instead when none of them has something to expand in the selection; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", ), ( "attributes.openUrl", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3698aaeef..b562c05b4a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -828,6 +828,11 @@ pub struct UiState { /// them (#1732). #[serde(default)] pub transform_each: Value, + /// The Expand choices OK last expanded with in this run of the app (object, fill, stroke, + /// gradient, steps; null: none yet): the Expand dialog opens on them, and Object › Expand… + /// chosen with Alt (Option) expands with them at once. They are not kept across launches. + #[serde(skip)] + pub expand_options: Value, /// The spacing used the last time Rearrange All Artboards was confirmed. #[serde(default)] pub rearrange_artboards_spacing: Value, @@ -1266,6 +1271,7 @@ impl Default for UiState { simplify: Value::Null, move_options: Value::Null, transform_each: Value::Null, + expand_options: Value::Null, rearrange_artboards_spacing: Value::Null, dxf_import: Value::Null, psd_import: Value::Null, diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..be29782466 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5662,6 +5662,17 @@ link, the dimension stays where it was, no longer linked (see [dimensions.md](di `object.expand` rejects a param of the wrong type, such as `"fill": "yes"`, `"gradient": 3` or `"steps": "16"`, and changes nothing. Omitting a param or giving null keeps its default. +`ui.expandDialog {immediate?}` opens the Expand dialog (`object.expand` with no params opens it too). The dialog opens on +the Object, Fill, Stroke, Expand Gradient To and steps choices that OK last expanded with since the app started, and on +the defaults before that; Cancel and an OK that fails leave the kept choices as they were, and they are not kept across +launches. Choosing Object → Expand… in the in-window menu bar with Alt (Option on macOS) held sends `immediate: true`, which expands the selection +at once with those choices, or the defaults before any OK, in one undo step, as OK in the dialog would +([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) +describes this shortcut for a gradient; VectorCraft applies it to whatever the choices expand). When none of the kept +choices has something to expand in the selection, `immediate: true` opens the dialog on them instead and changes +nothing. A selection with appearance attributes refuses both, as the dimmed menu item does. An `immediate` of null is +treated as omitted, and any other value that is not true or false is an error. + ```json {"name":"run_command","arguments":{"command":"object.expand","params":{"stroke":false,"gradient":"mesh"}}} {"name":"run_command","arguments":{"command":"object.expand","params":{"steps":16}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..46edcfce9b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2120,6 +2120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pattern fills in Expand:** Object › Expand with Fill turns a pattern fill into the pattern's tiles in a clip group shaped like the object, with the fill's opacity and blend mode, and the object's other fills and strokes stay above or below it in paint order, in one undo step (`object.expand`). - **Gradient options for type in Expand:** the Expand dialog enables its gradient options for type, symbol art included, only when the outline of at least one character, ruby character, underline or strikethrough gets a gradient that Fill turns into art. A gradient that repeats or reflects in more than 256 runs across a character's outline, VectorCraft's own limit, stays a gradient after Expand (`object.expand.info`, `crates/engine/src/tests/objexpand.rs`). +- **Expand with Alt (Option):** choosing Object › Expand… in the in-window menu bar with Alt (Option on macOS) held expands the selection at once, in one undo step, with the choices OK last expanded with in the Expand dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) describes this shortcut for a gradient), and the dialog opens on those choices. VectorCraft's own rules: the shortcut applies to every expandable selection, the choices are kept until the app quits, the dialog's defaults apply before the first OK, and when none of the choices has something to expand in the selection the dialog opens instead (`ui.expandDialog`'s `immediate`). - **Type with transparency or effects:** type at less than 100% opacity, in a blend mode other than Normal, or with raster effects such as a drop shadow keeps its glyph outlines between frames, as opaque type does, and is laid out again when it is edited or the fonts change. At 2880 × 1800 on 8 threads, a page of 1,000 type objects takes 13 ms a frame instead of 23 ms at 80% opacity, 31 ms instead of 41 ms in Multiply and 16 ms instead of 26 ms with a drop shadow, with the same pixels. From 432413274ee9606f7a36b381dcbbb190d0fdf0ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:17:59 -0800 Subject: [PATCH 094/138] UI: comments describe the behavior instead of comparing it with other apps Comments in the ui-egui crate described panels, menus, dialogs, widgets and cursors by comparison with other applications ("as in ...", "...-style", "like ...'s"). They now say what VectorCraft does. The section header for raster effects in nine translation catalogs changes the same way. The change edits comments only. No code, string or catalog row changes. --- crates/ui-egui/src/canvas.rs | 4 ++-- crates/ui-egui/src/canvas/grid.rs | 2 +- crates/ui-egui/src/canvas/home.rs | 2 +- crates/ui-egui/src/canvas/view.rs | 2 +- crates/ui-egui/src/chrome.rs | 4 ++-- crates/ui-egui/src/chrome/control_bar.rs | 2 +- crates/ui-egui/src/community.rs | 4 ++-- crates/ui-egui/src/cursors.rs | 2 +- crates/ui-egui/src/dialogs/effect_gallery.rs | 6 +++--- crates/ui-egui/src/dialogs/export_for_screens.rs | 4 ++-- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/menus/bar.rs | 2 +- crates/ui-egui/src/menus/submenus.rs | 6 +++--- crates/ui-egui/src/menus/tree.rs | 2 +- crates/ui-egui/src/native_menu.rs | 8 ++++---- crates/ui-egui/src/panels/appearance.rs | 2 +- crates/ui-egui/src/panels/info.rs | 2 +- crates/ui-egui/src/panels/layers/controls.rs | 2 +- crates/ui-egui/src/panels/navigator.rs | 2 +- crates/ui-egui/src/panels/properties.rs | 2 +- crates/ui-egui/src/panels/stroke.rs | 2 +- crates/ui-egui/src/place.rs | 2 +- crates/ui-egui/src/prefs_dialog.rs | 2 +- crates/ui-egui/src/scrub.rs | 2 +- crates/ui-egui/src/state.rs | 6 +++--- crates/ui-egui/src/titlebar.rs | 2 +- crates/ui-egui/src/widgets/color.rs | 2 +- crates/ui-egui/src/widgets/labels.rs | 2 +- crates/ui-egui/src/widgets/numeric.rs | 6 +++--- crates/ui-egui/src/workspaces.rs | 2 +- 40 files changed, 55 insertions(+), 55 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 847b60fd87..73cfd87cd1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -175,7 +175,7 @@ enum Drag { }, /// A Selection tool move over a panel or toolbar: the art waits where it last moved on the /// canvas, and the panels get it ([`widgets::PanelDrag::Art`]) if it is released there. Back - /// on the canvas the move goes on, as in Illustrator (#2826). + /// on the canvas the move goes on (#2826). Art, /// Fingers making a touch gesture ([`crate::touch`]): the first one's press does nothing. Gesture, @@ -831,7 +831,7 @@ fn frame_options( // Type › Highlight Substituted Fonts: pink behind text in a substitute font. highlight_substituted_fonts: app.session.prefs.highlight_substituted_fonts, // General › Anti-aliased Artwork: off, edges are hard on screen (raster effects and - // pattern tiles stay smooth), as in Illustrator. + // pattern tiles stay smooth). anti_alias: if app.session.prefs.anti_aliased_artwork { vectorcraft_render::AntiAlias::Art } else { vectorcraft_render::AntiAlias::None }, progressive_placed: true, trace_views: true, diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 84adb0d861..001b2e31f7 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -432,7 +432,7 @@ pub(super) fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option, s let sy = left.top() + d; clip_left.line_segment([pos2(left.right() - len, sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick)); if let Some(text) = label { - // Vertical labels read top-to-bottom, one digit per line like Illustrator. + // Vertical labels read top-to-bottom, one digit per line. let top = sy + 2.0; if top < filled_to { return; diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index bffab8f06c..c103c4b7ea 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -25,7 +25,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { /// The Home screen's column: welcome, New / Open, Recent Files, Learn, presets and community links. fn home_content(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - // The welcome and the New / Open buttons sit centred, as PhotoCraft's Home screen does (#4684). + // The welcome and the New / Open buttons sit centred (#4684). ui.vertical_centered(|ui| { ui.label(egui::RichText::new(tl!("Welcome to VectorCraft")).font(theme::semibold(26.0)).color(t.text)); ui.add_space(4.0); diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 4443f12997..e0e5cc9f75 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -94,7 +94,7 @@ pub(super) const HOLD_DELAY: f32 = 0.3; /// …and how fast it zooms then (as `exp(seconds × HOLD_ZOOM)`: twice as close each second). pub(super) const HOLD_ZOOM: f64 = std::f64::consts::LN_2; -/// Performance › Animated Zoom, which needs GPU Performance as in Illustrator: the Zoom tool zooms +/// Performance › Animated Zoom, which needs GPU Performance: the Zoom tool zooms /// as it is dragged sideways or held, instead of zooming to the area dragged across, and a wheel /// notch's zoom glides in ([`wheel`]). pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 7e48fc244e..9f189ddb5d 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -36,7 +36,7 @@ use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title} pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; -/// The application bar's height, in points (compact, as in PhotoCraft). +/// The application bar's height, in points (compact). pub const APP_BAR_HEIGHT: f32 = 32.0; /// The brand mark's side. const MARK: f32 = 18.0; @@ -105,7 +105,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text); let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0); let gap = ui.spacing().item_spacing.x; - // The search icon, as in PhotoCraft: shown while a minimal switcher fits beside it. + // The search icon: shown while a minimal switcher fits beside it. let icon = 28.0; let search = switcher && room >= 64.0 + 8.0 + gap + icon; let ws_w = ws_w.min(room - 8.0 - gap - if search { icon } else { 0.0 }).max(64.0); diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 71b737dbfc..2df5067aa9 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -886,7 +886,7 @@ fn gripper(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, d } } -/// The Control bar (Window → Control), context-sensitive like Illustrator's, docked to the top or +/// The Control bar (Window → Control), context-sensitive, docked to the top or /// the bottom of the window, or floating over the window below the menu bar, where it takes no room /// from the canvas. A floating bar is [`FLOAT_WIDTH`] wide, or as wide as the window when that is /// narrower, and is kept inside the window when the window shrinks. diff --git a/crates/ui-egui/src/community.rs b/crates/ui-egui/src/community.rs index 034807b8b7..97f7dffdba 100644 --- a/crates/ui-egui/src/community.rs +++ b/crates/ui-egui/src/community.rs @@ -33,7 +33,7 @@ pub fn discord_button(app: &mut VectorcraftApp, ui: &mut Ui, large: bool) -> egu let ir = egui::Rect::from_center_size(r.left_center() + vec2(h * 0.35 + icon / 2.0, 0.0), vec2(icon, icon)); if large { // The theme's accent, as the primary buttons use it, so the call to action matches the - // rest of the window (and PhotoCraft's, #4684); Discord's colour stays on the app-bar icon. + // rest of the window (#4684); Discord's colour stays on the app-bar icon. let t = Tokens::get(ui.ctx()); let fill = if resp.hovered() { t.accent } else { t.accent_strong }; ui.painter().rect_filled(r, CornerRadius::same((h / 2.0) as u8), fill); @@ -77,7 +77,7 @@ pub fn links(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, false); } -/// [`links`] for a centred column (the Home screen's, as PhotoCraft's, #4684): the Discord button +/// [`links`] for a centred column (the Home screen's, #4684): the Discord button /// and the links, each in the middle. pub fn links_centered(app: &mut VectorcraftApp, ui: &mut Ui) { links_in(app, ui, true); diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 5495d3753c..5f04927964 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -1,5 +1,5 @@ //! Tool cursors drawn as vector glyphs (egui only offers system cursors). Black shapes with a white -//! halo, hotspot at `p`, Illustrator's visual grammar: solid arrow (Selection), hollow arrow (Direct +//! halo, hotspot at `p`, one shape per tool: solid arrow (Selection), hollow arrow (Direct //! Selection), pen nib with state badges, crosshair for drawing tools, curved arrows for rotate. //! //! The desktop app shows them as OS cursors ([`Images`]): the system moves those itself, at once, diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index fe0de205fc..6f0d0a2d35 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -1,4 +1,4 @@ -//! Effect → Effect Gallery: browse Photoshop-style raster filters by category, build a stack, and +//! Effect → Effect Gallery: browse raster filters by category, build a stack, and //! apply it as separate appearance effects in one undo step. //! //! Each filter has a thumbnail, and the dialog has its own preview, as the @@ -29,7 +29,7 @@ const PREVIEW_H: usize = 84; /// Dialog kind for the Effect Gallery. pub const KIND: &str = "effectGallery"; -/// Raster effect submenus in the gallery (the six Photoshop-style folders it holds). +/// Raster effect submenus in the gallery (the six raster filter folders it holds). const CATEGORIES: [(&str, &[&str]); 6] = [ ("Artistic", &["Effect", "Artistic"]), ("Brush Strokes", &["Effect", "Brush Strokes"]), @@ -425,7 +425,7 @@ fn sample_drawing(w: usize, h: usize) -> Vec { out } -/// Run one Photoshop-style filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` +/// Run one raster filter on a premultiplied RGBA buffer. Leaves it unchanged when `id` /// is not one of those filters or the buffer is the wrong size. fn apply_pixel(id: &str, params: &Map, data: &mut [u8], w: usize, h: usize) { let Some(n) = w.checked_mul(h).and_then(|n| n.checked_mul(4)) else { return }; diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 96b5f63c27..66087c68ea 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -1,4 +1,4 @@ -//! File → Export → Export for Screens, laid out as Illustrator's: on the left the Artboards and +//! File → Export → Export for Screens: on the left the Artboards and //! Assets tabs (thumbnails with checkboxes, in a grid or a list), Clear Selection and the prefix; //! on the right Select (All, a range or Full Document, Include Bleed, Include Artboard Fill), the destination (folder //! picker, Open Location after Export, Create Sub-folders by scale or by format; the web downloads @@ -718,7 +718,7 @@ fn tiles( ui.painter().galley(label_pos, galley, t.text); false }; - // The checkbox sits on the thumbnail's lower left corner, as Illustrator's. + // The checkbox sits on the thumbnail's lower left corner. let bx = egui::Rect::from_min_size(egui::pos2(pic.left() + 4.0, pic.bottom() - 18.0), egui::vec2(14.0, 14.0)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bx)); if widgets::check_box(&mut child, &name, checked, true) || resp.clicked() || caption_clicked { diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..7621b992e0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -990,7 +990,7 @@ Free Transform Volná transformace Perspective Distort Perspektivní deformace -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… Radiální rozostření… Blur Center Střed rozostření Smart Blur… Chytré rozostření… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..17f2235553 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -18,7 +18,7 @@ # `untranslated_report` lists gaps) — and the status and error messages. Left in English on purpose (`MENU_KEEP_AS_IS` in the # tests): the product name, language names, OpenType, the built-in workspace names and the bracketed # perspective grid preset names; `de-DE`, `de-AT`, `de-CH` and every other `de-*` locale resolve here. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Leuchtende Konturen… Glowing Edges Leuchtende Konturen Edge Width Kantenbreite diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..b5d43934a3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -11,7 +11,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Bordes resplandecientes… Glowing Edges Bordes resplandecientes Edge Width Ancho del borde diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..1e2d313c3d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -12,7 +12,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Contour lumineux… Glowing Edges Contour lumineux Edge Width Largeur du bord diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..a99135774d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -11,7 +11,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Bordi luminosi… Glowing Edges Bordi luminosi Edge Width Larghezza bordo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..ac945b5c76 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4406,7 +4406,7 @@ theme Appearance 外観 Free Transform 自由変形 Perspective Distort 遠近変形 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… ぼかし (放射状)… Blur Center ぼかしの中心 Smart Blur… ぼかし (詳細)… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..6bddba8dfb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9,7 +9,7 @@ # Coverage: the whole interface — every menu string and every `tl!` literal (`complete_menus`, # `untranslated_report` lists gaps). Left in English on purpose (`MENU_KEEP_AS_IS` in the tests): the product name, language # names, OpenType, the built-in workspace names and the bracketed perspective grid preset names. -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Glowing Edges… Светящиеся края… Glowing Edges Светящиеся края Edge Width Ширина края diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..55a52d2884 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5773,7 +5773,7 @@ axis Both 两者 Constrain 约束 Perspective Distort 透视扭曲 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… 径向模糊… Blur Center 模糊中心 Smart Blur… 智能模糊… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..7cd517065b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5604,7 +5604,7 @@ axis Both 兩者 Free Transform 任意變形 Perspective Distort 透視扭曲 -# Photoshop-style raster effects (Effect menu, their dialogs). +# Raster effects (Effect menu, their dialogs). Radial Blur… 放射狀模糊… Blur Center 模糊中心 Smart Blur… 智慧型模糊… diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0b8ee67183..b1598cdb12 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1,4 +1,4 @@ -//! VectorCraft's egui frontend: an Illustrator-style UI over `vectorcraft-engine`. +//! VectorCraft's egui frontend: menus, tools, panels and dialogs over `vectorcraft-engine`. //! //! The UI is thin: every action goes through [`VectorcraftApp::run`], which dispatches UI commands //! (view/window) here and everything else to the engine. The same entry point serves menus, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4e2d80bb45..b58505590a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1,4 +1,4 @@ -//! The menu bar (Illustrator's menu tree) and UI-level commands. +//! The menu bar (the full menu tree) and UI-level commands. //! //! Items bound to a command id run through [`VectorcraftApp::run`]. Items not implemented yet are //! listed (disabled, with their shortcut) so the full surface is visible and discoverable; the diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index 85588620e8..5e2f6aa172 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -25,7 +25,7 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { let mut clicked: Option<(String, Value)> = None; let mut file_open = false; let tree = menu_tree_named(app.session.prefs.font_names_in_english); - // No application menu in the window (as in Illustrator): the bar starts at File on every + // No application menu in the window: the bar starts at File on every // platform. The VectorCraft menu stays in the tree: the native Mac bar takes it from there. let tree: Vec<(&str, Vec)> = tree.into_iter().filter(|(title, _)| *title != "VectorCraft").collect(); // A menu bar for its layout and menu-button style, but the titles use `Popup::menu` directly: diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index 469c40e7c7..1f8facea4c 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -111,7 +111,7 @@ pub(super) fn font_items(english_names: bool) -> Vec { /// The catalogue's menu path of the effects in 3D and Materials › 3D (Classic). const CLASSIC_3D: &[&str] = &["Effect", "3D and Materials", "3D (Classic)"]; -/// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the +/// The raster effects' submenus of the Effect menu (the pixel effects, below the /// vector effects): (submenu, the catalogue's menu path of its effects). /// The raster Stylize submenu shares its path with the vector one and lists only the effects at /// that path that [`vectorcraft_effects::PIXEL_EFFECTS`] names. @@ -157,13 +157,13 @@ pub(super) fn effect_menu() -> Vec { "Warp", ]; let top_level = |e: &vectorcraft_effects::EffectInfo| e.menu == ["Effect"] && order.contains(&e.label); - // An effect goes in the vector submenu its path names unless it is a Photoshop-style effect, + // An effect goes in the vector submenu its path names unless it is a pixel effect, // which goes in the raster submenu of the same name when `RASTER_MENUS` has one (Stylize › // Glowing Edges). let in_vector_menu = |e: &vectorcraft_effects::EffectInfo| order.iter().any(|s| e.menu == ["Effect", *s]) && !vectorcraft_effects::PIXEL_EFFECTS.contains(&e.id); let item = |e: &vectorcraft_effects::EffectInfo| match e.defaults.as_object().is_some_and(|o| o.is_empty()) { - // No options (Effect → Pathfinder, Crop Marks): apply directly, like Illustrator. + // No options (Effect → Pathfinder, Crop Marks): apply directly. true => Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })), false => Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id })), }; diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index ec8ec99018..5e1b291eeb 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -15,7 +15,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { vec![ ( // The application menu: About and Discord only. The in-window bar never shows it (File - // is first there, as in Illustrator); on macOS `native_menu::mac_layout` composes the + // is first there); on macOS `native_menu::mac_layout` composes the // App menu from this entry and the other menus (About from Help, Settings from Edit, // Quit from File, Language and Appearance synthesized). It stays first: `from_tree` // gives the first menu the App role. diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 510131be0e..5f133a6686 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -3,12 +3,12 @@ //! [`Backend`] (the desktop app's, through muda). //! //! Pure and platform-free, so it is tested everywhere and builds for the web; only the backend -//! touches AppKit. What the layout does ([`mac_layout`], Illustrator on the Mac as the reference): +//! touches AppKit. What the layout does ([`mac_layout`]): //! - an **app menu** named VectorCraft: About; Settings, a submenu with one item per Preferences //! page (General… ⌘K first); Language; Appearance (the UI brightness); Services; Hide VectorCraft //! ⌃⌘H (⌘H stays View › Hide Edges), Hide Others ⌥⌘H, Show All; and Quit ⌘Q, still the app's own //! `app.quit`, so documents with unsaved changes are asked about. Language and Appearance have -//! no in-window menu (as in PhotoCraft) and are synthesized here; Quit is File › Exit in the +//! no in-window menu and are synthesized here; Quit is File › Exit in the //! window and reads as Quit in the App menu. These leave the other menus (Edit › Preferences…, //! Help › About), and Join Our Discord stays under Help only; //! - **Window** gets Minimize ⌃⌘M, Zoom and Bring All to Front, and **Help** the system's search @@ -299,7 +299,7 @@ pub struct Layout { } /// The Mac menu bar of `bar` (the in-window menus, [`from_tree`]): see the module docs. -/// Language and Appearance have no in-window menu (as in PhotoCraft); when the tree doesn't +/// Language and Appearance have no in-window menu; when the tree doesn't /// carry them they are synthesized below, so the App menu keeps them. pub fn mac_layout(app: &VectorcraftApp, bar: &MenuBar, lang: Lang) -> Layout { let mut bar = bar.clone(); @@ -400,7 +400,7 @@ fn native_item(app: &VectorcraftApp, label: &'static str, command: &'static str, } /// Settings ▸: one item per page of the Preferences dialog (its own list), each opening it there; -/// the first (General…) has Preferences' shortcut (⌘K), as in Illustrator. +/// the first (General…) has Preferences' shortcut (⌘K). fn settings_pages(preferences: &Item, lang: Lang) -> Vec { vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES .iter() diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 308b8f3602..cb6f72ac71 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -519,7 +519,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Some(n) => stack(app, ui, n, sel, r, None), None => default_stack(app, ui), } - // Spacer row like Illustrator's empty tail. + // An empty spacer row at the end of the list. ui.allocate_exact_size(vec2(ui.available_width(), 10.0), Sense::hover()); }); bottom(app, ui, node.as_ref(), sel); diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 2e81441654..19fe505c0c 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -14,7 +14,7 @@ use crate::VectorcraftApp; use crate::theme::Tokens; use crate::widgets::{self, menu_item}; -/// Colour values in the colour's own model, like Illustrator's Info panel. +/// Color values in the color's own model, for the Info panel. pub fn color_values(c: &Color) -> Vec<(&'static str, String)> { match *c { Color::Rgb { r, g, b } => vec![("R", format!("{:.0}", r * 255.0)), ("G", format!("{:.0}", g * 255.0)), ("B", format!("{:.0}", b * 255.0))], diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 381d0a65b1..9bb6ed8f22 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -82,7 +82,7 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc actions.push(("layer.new".into(), json!({"top": m.command}))); } } - // Rows dropped on the trash are deleted, on New Layer duplicated, as in Illustrator. Both are + // Rows dropped on the trash are deleted, on New Layer duplicated. Both are // outlined while rows (or, on the trash, a target circle) hang over them. Guide rows dropped on // the trash delete their guides (`guide.remove`); New Layer does not take them. for (button, cmd) in [(&trash, "ui.layerDelete"), (&new_layer, "layer.duplicate")] { diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 60eb4c18d0..d6a9763b20 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -282,7 +282,7 @@ fn view_box(region: DRect, thumb: Rect, canvas: Rect, v: &crate::state::View, ui pts } -/// Slider position (0..1) ↔ zoom percent on Illustrator's log range 3.13 %–64 000 %. +/// Slider position (0..1) ↔ zoom percent on a log range, 3.13 %–64 000 %. pub fn zoom_to_slider(z: f64) -> f64 { ((z.clamp(3.13, 64000.0)).ln() - 3.13f64.ln()) / (64000f64.ln() - 3.13f64.ln()) } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 500b967469..27cbf67b49 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1,4 +1,4 @@ -//! The Properties panel: context-sensitive sections like Illustrator's. +//! The Properties panel: sections that change with the selection. use egui::Ui; use serde_json::json; diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index c667f01200..3b48f45e91 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -76,7 +76,7 @@ fn dash_state(dash: Option<&Dash>, last: Option<(Vec, bool)>) -> (Vec, } /// Six dash/gap fields → a dash pattern: stops at the first empty dash; a dash without a gap -/// repeats its length as the gap (Illustrator's behaviour). +/// repeats its length as the gap. pub fn dash_pattern(fields: &[Option; 6]) -> Vec { edited_dash_pattern(fields, &[]) } diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 6485cafd8c..02195e18ea 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -631,7 +631,7 @@ pub fn paint_cursor(app: &mut VectorcraftApp, ctx: &egui::Context, painter: &egu // ---------- drops ---------- impl VectorcraftApp { - /// Where file `name` dropped with the pointer at `pos` (screen points) goes: as in Illustrator, + /// Where file `name` dropped with the pointer at `pos` (screen points) goes: /// onto the canvas of the open document (Shift embeds it), else opened. Where the platform /// doesn't say (`None`: desktop drags carry no position), a document opens as a tab of its /// own and a picture or text is placed in the middle of the view. A library, a presets file, a diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index e8a6368cbb..7b69bdf72c 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -1,4 +1,4 @@ -//! Edit → Preferences (⌘K): Illustrator-style category list + fields, rendered from the engine's +//! Edit → Preferences (⌘K): a category list + its fields, rendered from the engine's //! preference table ([`PREF_SPECS`]). The dialog edits a working copy in `Dialog::fields` //! (one field per preference key, so agents can `ui.dialog.set` any of them) and OK applies it //! through `prefs.set`. Also: persistence of engine prefs inside `UiState` and the per-frame diff --git a/crates/ui-egui/src/scrub.rs b/crates/ui-egui/src/scrub.rs index 5a0a2ff4f9..a68759087f 100644 --- a/crates/ui-egui/src/scrub.rs +++ b/crates/ui-egui/src/scrub.rs @@ -1,4 +1,4 @@ -//! Scrubbing numeric fields (#400, beyond Illustrator; Photoshop's scrubby labels): a horizontal +//! Scrubbing numeric fields (#400): a horizontal //! drag on a numeric field's label (`W:`, `Opacity:`, the Character panel's size icon) steps the //! field's value by one unit every [`PX_PER_STEP`] points, ten with Shift and a tenth with //! Ctrl/Cmd, as the arrow keys step a focused field; a click on the label focuses the field. A diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3698aaeef..de85047376 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -101,7 +101,7 @@ pub fn sync_zoom_stops_display_print_size(v: bool) { ZOOM_STOPS_PRINT_SIZE.store(v, Ordering::Relaxed); } -/// Illustrator's preset zoom stops, in percent. +/// The preset zoom stops, in percent. pub const ZOOM_STOPS: [f64; 26] = [ 3.13, 4.17, 6.25, 8.33, 12.5, 16.67, 25.0, 33.33, 50.0, 66.67, 100.0, 150.0, 200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0, 4800.0, 6400.0, 12800.0, 25600.0, 64000.0, @@ -135,7 +135,7 @@ pub fn next_zoom_with_display(z: f64, up: bool, display_print_size: bool) -> f64 zoom_from_display_percent(stop, display_print_size) } -/// Format like Illustrator's tab/zoom field: up to 2 decimals, no trailing zeros. +/// Format for the tab/zoom field: up to 2 decimals, no trailing zeros. pub fn zoom_label(z: f64, display_print_size: bool) -> String { let s = format!("{:.2}", zoom_display_percent(z, display_print_size)); let s = s.trim_end_matches('0').trim_end_matches('.'); @@ -454,7 +454,7 @@ pub struct UiState { pub toolbar_advanced: bool, #[serde(default = "yes")] pub task_bar: bool, - /// Where the Contextual Task Bar was dragged or pinned. Not saved, as in Illustrator: the bar + /// Where the Contextual Task Bar was dragged or pinned. Not saved: the bar /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index cbbd216e75..3a18dce216 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -326,7 +326,7 @@ mod tests { let texts: Vec = texts(&out).into_iter().map(|(t, _)| t).collect(); let has = |s: &str| texts.iter().any(|t| t == s); assert_eq!(has("Discord"), width > 1000.0, "{width}: {texts:?}"); - // Search is an icon only (as in PhotoCraft): its label lives in the tooltip. + // Search is an icon only: its label lives in the tooltip. assert!(!has("Search commands and tools"), "{width}: {texts:?}"); } } diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 04aae5be55..84f847a14f 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -12,7 +12,7 @@ pub enum Live { } /// A colour slider with a gradient track (`track(t)` gives the colour at 0..1) and a triangular -/// thumb below it, like Illustrator's Color panel. Returns the new normalized value and the phase. +/// thumb below it, as in the Color panel. Returns the new normalized value and the phase. pub fn color_slider(ui: &mut Ui, id: impl std::hash::Hash, value: f32, width: f32, track: &dyn Fn(f32) -> Color32) -> (Option, Live) { color_slider_named(ui, id, "", value, width, track) } diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index 103f53ab65..526556d65b 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -175,7 +175,7 @@ pub fn subheader(ui: &mut Ui, text: &str) { ui.label(egui::RichText::new(tl!(text)).size(12.5).color(t.text)); } -/// A label drawn with a dotted underline (Illustrator's link labels: "Stroke:", "Opacity:"). +/// A label drawn with a dotted underline (the panels' link labels: "Stroke:", "Opacity:"). pub fn link_label(ui: &mut Ui, text: &str) -> Response { let t = Tokens::get(ui.ctx()); let galley = ui.painter().layout_no_wrap(tl!(text).to_string(), egui::FontId::proportional(12.5), t.text_strong); diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 89ce8d70d5..d2ea34213e 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -293,8 +293,8 @@ pub(super) fn shown_alike(show: impl Fn(f64) -> String) -> impl Fn(f64, f64) -> /// goes to the next whole number in its direction (5.1 up to 6, down to 5), a Ctrl/Cmd step goes to /// the next tenth, and a Shift step adds or takes ten. Steps stop at the field's `bounds` (#3370: /// a weight stops at 0, a miter limit at 1), and a plain step also stops at each of `stops` -/// ([`step_through`]). The new value is applied at once, as in -/// Illustrator's panels and dialogs, and the new text replaces `buf`, all selected so typing +/// ([`step_through`]). The new value is applied at once, and +/// the new text replaces `buf`, all selected so typing /// replaces it when focused. Returns the new number when a step was taken. An enabled field takes /// the wheel without taking keyboard focus, and the panel under it doesn't scroll, when the wheel /// stream began over the field and the pointer was moved onto it, or pressed on it, after the @@ -745,7 +745,7 @@ impl egui::Plugin for WheelTailPlugin { /// A [`num_field`] for a width or height (Transform panel, Properties panel, Control bar): Ctrl/Cmd+Enter /// also commits it and ends its editing, as Enter does, and [`enter_modifiers`] reports Command. A -/// percentage typed alone (`50%`) is that share of the size shown, as in Illustrator (#2401). +/// percentage typed alone (`50%`) is that share of the size shown (#2401). pub fn size_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option, unit: Unit, width: f32) -> Option { size_field_named(ui, id, None, value, unit, width) } diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 2a764a6968..886589b5f0 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -94,7 +94,7 @@ pub const ESSENTIALS: &str = "Essentials"; /// Touch workspace (Window → Workspace → Touch; Preferences › Devices › Enable Touch Workspace). pub const TOUCH: &str = "Touch"; -/// Built-in workspaces, in Illustrator's menu order (Essentials first). +/// Built-in workspaces, in menu order (Essentials first). pub fn builtins() -> Vec { let base = Workspace::default(); let w = |name: &str, f: &dyn Fn(&mut Workspace)| { From 7f72a7c46d3afdb5366f7d8b5d49b2b30a28220a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:45:22 -0800 Subject: [PATCH 095/138] Links: Unembed writes several selected embedded images to one chosen folder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Links panel menu's Unembed… now works with several embedded images selected: it asks for one folder, writes a file for each image there in the format the image is stored in, and links each image to its file, keeping its bounds, in one undo step. On the web each image is downloaded instead. links.unembed takes `ids` and `folder` for this form. Each file is named after its image, with characters a file name can't hold replaced by `_`; a taken name is numbered (`Name 2`), and a file already in the folder is never replaced. Linked images among `ids` are skipped and listed. When an image can't be written, the files the call wrote are removed and the document does not change. A folder outside the automation write roots is refused. The one-image `{id, path}` form is unchanged. --- crates/engine/src/cmd/links.rs | 189 ++++++++++++++++++++++- crates/engine/src/tests/linkspanel.rs | 122 +++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/links.rs | 47 +++++- crates/ui-egui/src/panels/tests_links.rs | 30 ++++ docs/mcp.md | 11 ++ docs/target-app-parity.md | 1 + 30 files changed, 461 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 1ec0f7ceaa..0c31b968e3 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -36,7 +36,7 @@ use vectorcraft_doc::{ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or}; +use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to)", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (with folder; default: the selected embedded images), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). Several images, with ids and folder: write each embedded image to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id or path with ids or folder is an error", has_doc, unembed ), @@ -2669,8 +2669,28 @@ fn convert_image(bytes: &[u8], ext: &str) -> std::result::Result, String craft_image_codecs::encode(&raw, format, &craft_image_codecs::EncodeOptions::default()).map_err(|e| e.to_string()) } +/// The extension of the format embedded image `blob` is stored in (PNG for one Unembed doesn't +/// name). +fn stored_extension(blob: &vectorcraft_doc::ImageBlob) -> &'static str { + fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")) +} + +/// The bytes of embedded image `blob` in the format of extension `ext`: its own bytes when it is +/// stored in that format, else converted. +fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::Result, String> { + let same = fileio::format(ext).is_some_and(|f| f.mime == blob.mime); + if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } +} + fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + if given("ids") || given("folder") { + if given("id") || given("path") { + return Err(bad(C, "give id and path for one image, or ids and folder for several")); + } + return unembed_to_folder(s, p); + } let st = s.doc()?; let doc = with_brush_art(&st.doc); let id = image_param(st, &doc, p, C)?; @@ -2681,15 +2701,14 @@ fn unembed(s: &mut Session, p: &Value) -> Result { } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. - let stored = fileio::FORMATS.iter().find(|f| f.raster && f.mime == blob.mime).map_or("png", |f| f.extensions.first().copied().unwrap_or("png")); + let stored = stored_extension(blob); let path = str_param(p, "path"); let ext = match path.map(fileio::extension) { Some(e) if UNEMBED_EXTS.contains(&e.as_str()) => e, Some(e) if !e.is_empty() => return Err(bad(C, format!("can't write .{e} images: use .png, .jpg, .gif, .webp, .tif or .bmp"))), _ => stored.to_string(), }; - let same = fileio::format(&ext).is_some_and(|f| f.mime == blob.mime); - let bytes = if same { blob.bytes.to_vec() } else { convert_image(&blob.bytes, &ext).map_err(|e| bad(C, e))? }; + let bytes = unembed_bytes(blob, &ext).map_err(|e| bad(C, e))?; let Some(path) = path else { let name = n.display_name(); let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); @@ -2705,6 +2724,142 @@ fn unembed(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "path": path })) } +/// `links.unembed {ids?, folder}`: each embedded image of `ids` (default: the selected embedded +/// images) written to a new file in `folder` as stored (as PNG when that format is not one of +/// VectorCraft's raster file formats) and linked to it, in one undo step. Linked images are skipped. When any image fails, the files written before it +/// are removed and the document does not change. +fn unembed_to_folder(s: &mut Session, p: &Value) -> Result { + const C: &str = "links.unembed"; + let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `folder`"))?; + let st = s.doc()?; + let doc = with_brush_art(&st.doc); + let ids = ids_param(p, "ids", C)?.unwrap_or_else(|| selected_images(st, |im| im.link.is_none())); + let mut seen = BTreeSet::new(); + if !ids.iter().all(|id| seen.insert(id.0)) { + return Err(bad(C, "`ids` names an object twice")); + } + let (mut embedded, mut skipped) = (vec![], vec![]); + for &id in &ids { + let n = stored(&doc, id).ok_or(crate::EngineError::NoNode(id))?; + let im = image_of(&doc, id).ok_or_else(|| bad(C, format!("object {} is not an image", id.0)))?; + if im.link.is_some() { + skipped.push(id); + continue; + } + let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; + embedded.push((id, n.display_name(), blob)); + } + match (embedded.is_empty(), skipped.first()) { + (true, Some(id)) => return Err(bad(C, format!("image {} is linked already", id.0))), + (true, None) => return Err(bad(C, "select an image")), + _ => {} + } + let dir = absolute_path(folder); + writable_folder(&dir)?; + // One image at a time: its bytes are read before its file is written, so pixels that can't be + // read leave no file behind. + let mut written: Vec = vec![]; + let mut reads = Vec::with_capacity(embedded.len()); + let wrote = embedded.iter().try_for_each(|(id, name, blob)| { + vectorcraft_doc::cancel::check()?; + let ext = stored_extension(blob); + let bytes = unembed_bytes(blob, ext).map_err(|e| bad(C, e))?; + let name = format!("{}.{ext}", unembed_stem(name)); + let img = linked_image(&bytes, Some(Path::new(&dir).join(&name).to_string_lossy().as_ref()))?; + let path = write_numbered(&dir, &name, &bytes)?; + written.push(path.clone()); + reads.push((*id, (link_info(&path, &bytes), img))); + Ok(()) + }); + let remove_written = |written: &[String]| { + for path in written { + let _ = std::fs::remove_file(path); + } + }; + if let Err(e) = wrote { + remove_written(&written); + return Err(e); + } + drop(doc); + let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); + let edited = s.edit("Unembed", |d, _| { + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + }); + if let Err(e) = edited { + remove_written(&written); + return Err(e); + } + Ok(json!({ "unembedded": done, "skipped": ids_json(&skipped) })) +} + +/// The name Unembed gives image `name`'s file in a folder, before its extension: the name without +/// a folder part or extension, each character a file name can't hold on some system +/// (`/ \ : * ? " < > |` and control characters) as `_`, without leading spaces or trailing dots and +/// spaces, at most 150 bytes long, and `Image` when nothing is left. A name Windows keeps for a +/// device (`CON`, `NUL`, `COM1` …) gets `_` after it. +fn unembed_stem(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or_default(); + let stem = match base.rfind('.') { + Some(i) if i > 0 => &base[..i], + _ => base, + }; + let mut clean = String::new(); + for c in stem.chars().map(|c| if c.is_control() || "/\\:*?\"<>|".contains(c) { '_' } else { c }) { + if clean.len() + c.len_utf8() > 150 { + break; + } + clean.push(c); + } + let clean = clean.trim_start_matches(' ').trim_end_matches(['.', ' ']); + if clean.is_empty() { + return "Image".to_string(); + } + let device = clean.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); + let numbered = |prefix: &str| device.strip_prefix(prefix).is_some_and(|d| d.len() == 1 && matches!(d.as_bytes().first(), Some(b'1'..=b'9'))); + if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") { + format!("{clean}_") + } else { + clean.to_string() + } +} + +/// Folder `path` may take Unembed's files: inside the automation write roots, and a folder. +#[cfg(not(target_arch = "wasm32"))] +fn writable_folder(path: &str) -> Result<()> { + crate::file_access::check_write(path).map_err(EngineError::Other)?; + if !std::fs::metadata(path).is_ok_and(|m| m.is_dir()) { + return Err(EngineError::Other(format!("{path} is not a folder"))); + } + Ok(()) +} + +/// Write `bytes` to a new file named `name` in folder `dir`, never replacing a file there: `Name.ext`, +/// else `Name 2.ext` up to `Name 99.ext`, as [`fileio::copy_new`] names them → its path. +#[cfg(not(target_arch = "wasm32"))] +fn write_numbered(dir: &str, name: &str, bytes: &[u8]) -> Result { + use std::io::Write as _; + let create = |to: &Path| { + crate::file_access::check_write(&to.to_string_lossy()).map_err(|e| std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))?; + vectorcraft_format::write_new_with(to, |f| f.write_all(bytes)) + }; + match fileio::copy_new(Path::new(name), Path::new(dir), create, |_, _| false) { + Ok(Some(fileio::Placed::Copied(to) | fileio::Placed::Kept(to))) => Ok(to.to_string_lossy().into_owned()), + Ok(None) => Err(EngineError::Other(format!("every numbered name for {name} is taken in that folder"))), + Err(e) => Err(EngineError::Other(format!("{dir}: {e}"))), + } +} + +/// The web has no folders to write to. +#[cfg(target_arch = "wasm32")] +fn writable_folder(_: &str) -> Result<()> { + Err(EngineError::Other("no file system here".into())) +} + +#[cfg(target_arch = "wasm32")] +fn write_numbered(_: &str, _: &str, _: &[u8]) -> Result { + Err(EngineError::Other("no file system here".into())) +} + /// Placement Options as `{preserve, align, clip}`. fn placement_json(o: PlacementOptions) -> Value { json!({ "preserve": o.preserve.id(), "align": o.align.id(), "clip": o.clip }) @@ -2884,4 +3039,28 @@ mod tests { let c = read(); assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + + #[test] + fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { + for (name, stem) in [ + ("photo.png", "photo"), + ("Image", "Image"), + ("../../etc/passwd", "passwd"), + ("C:\\art\\logo.tif", "logo"), + ("a:b*c?d\"eg|h", "a_b_c_d_e_f_g_h"), + ("tab\there", "tab_here"), + (" name. .png", "name"), + ("..", "Image"), + ("", "Image"), + (".hidden", ".hidden"), + ("CON.png", "CON_"), + ("lpt1", "lpt1_"), + ("COM0", "COM0"), + ("console", "console"), + ] { + assert_eq!(unembed_stem(name), stem, "{name:?}"); + } + let long = unembed_stem(&"é".repeat(200)); + assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len()); + } } diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index a1402cc43f..05b7e9a405 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -203,6 +203,128 @@ fn unembed_of_pixels_that_cant_be_read_writes_no_file() { assert!(image(&s, id).link.is_none()); } +/// The files of folder `dir`, sorted by name. +fn files_in(dir: &str) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names +} + +/// The path of the file `name` in folder `dir`. +fn file_in(dir: &str, name: &str) -> String { + std::path::Path::new(dir).join(name).to_string_lossy().into_owned() +} + +/// Several images unembed into one folder: each gets a new file named after it (a taken name +/// numbered, a file already there never replaced), links to it and keeps its bounds, linked images +/// are skipped, and one undo step makes them embedded again while the files stay. +#[test] +fn unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step() { + let dir = Folder::new("unembed-folder"); + let out = dir.file("out"); + for sub in ["a", "b", "out"] { + std::fs::create_dir_all(dir.file(sub)).unwrap(); + } + let (red, blue) = (png(60, 30, RED), png(40, 20, BLUE)); + write(&dir.file("a/photo.png"), &red); + write(&dir.file("b/photo.png"), &blue); + write(&dir.file("a/linked.png"), &red); + let kept = b"not an image".to_vec(); + write(&file_in(&out, "photo.png"), &kept); + let mut s = session(); + let a = place_embedded(&mut s, &dir.file("a/photo.png")); + let b = place_embedded(&mut s, &dir.file("b/photo.png")); + let linked = place(&mut s, &dir.file("a/linked.png")); + let linked_path = image(&s, linked).link.unwrap().path; + let (bounds_a, bounds_b) = (bounds(&s, a), bounds(&s, b)); + let undo_before = s.doc().unwrap().history.undo.len(); + let r = run(&mut s, "links.unembed", json!({"ids": [a.0, linked.0, b.0], "folder": out})); + let (path_a, path_b) = (file_in(&out, "photo 2.png"), file_in(&out, "photo 3.png")); + assert_eq!(r, json!({"unembedded": [{"id": a.0, "path": path_a}, {"id": b.0, "path": path_b}], "skipped": [linked.0]})); + assert_eq!(files_in(&out), ["photo 2.png", "photo 3.png", "photo.png"]); + assert_eq!(std::fs::read(file_in(&out, "photo.png")).unwrap(), kept, "a file already there is not replaced"); + assert_eq!(std::fs::read(&path_a).unwrap(), red); + assert_eq!(std::fs::read(&path_b).unwrap(), blue); + assert_eq!(image(&s, a).link.unwrap().path, path_a); + assert_eq!(image(&s, b).link.unwrap().path, path_b); + assert_eq!(image(&s, linked).link.unwrap().path, linked_path, "a linked image is left as it is"); + assert_eq!((bounds(&s, a), bounds(&s, b)), (bounds_a, bounds_b)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before + 1, "one undo step"); + run(&mut s, "edit.undo", json!({})); + assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none(), "both embedded again"); + assert_eq!(files_in(&out).len(), 3, "undo leaves the files"); + // With no ids, the selected embedded images. + s.doc_mut().unwrap().selection.objects = vec![b, linked]; + let r = run(&mut s, "links.unembed", json!({"folder": out})); + assert_eq!(r, json!({"unembedded": [{"id": b.0, "path": file_in(&out, "photo 4.png")}], "skipped": []})); + assert_eq!(std::fs::read(file_in(&out, "photo 4.png")).unwrap(), blue); +} + +/// A batch that fails part way writes no file and changes nothing; requests that don't fit the +/// command are refused before anything is written. +#[test] +fn unembed_to_a_folder_that_fails_leaves_no_file_and_no_change() { + let dir = Folder::new("unembed-folder-fail"); + let out = dir.file("out"); + std::fs::create_dir_all(&out).unwrap(); + write(&dir.file("one.png"), &png(60, 30, RED)); + write(&dir.file("two.png"), &png(60, 30, BLUE)); + let mut s = session(); + let a = place_embedded(&mut s, &dir.file("one.png")); + let b = place_embedded(&mut s, &dir.file("two.png")); + // The second image's pixels can't be read: the first one's file is removed again. + let key = image(&s, b).key; + let saved = s.doc().unwrap().doc.images.get(&key).cloned().unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key.clone(), vectorcraft_doc::ImageBlob::png(png_header(60, 30))); + let undo_before = s.doc().unwrap().history.undo.len(); + let e = s.execute("links.unembed", &json!({"ids": [a.0, b.0], "folder": out})).unwrap_err(); + assert!(e.to_string().ends_with("the image's pixels can't be read"), "{e}"); + assert!(files_in(&out).is_empty(), "no file left behind"); + assert!(image(&s, a).link.is_none() && image(&s, b).link.is_none()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_before); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).images.insert(key, saved); + + let refused = |s: &mut Session, p: Value| s.execute("links.unembed", &p).unwrap_err().to_string(); + let both = "give id and path for one image, or ids and folder for several"; + assert!(refused(&mut s, json!({"ids": [a.0, a.0], "folder": out})).ends_with("`ids` names an object twice")); + assert!(refused(&mut s, json!({"id": a.0, "folder": out})).ends_with(both)); + assert!(refused(&mut s, json!({"ids": [a.0], "path": file_in(&out, "x.png")})).ends_with(both)); + assert!(refused(&mut s, json!({"ids": [a.0]})).ends_with("missing `folder`")); + assert!(refused(&mut s, json!({"ids": [a.0], "folder": 5})).ends_with("`folder` must be a string")); + assert!(refused(&mut s, json!({"ids": [], "folder": out})).ends_with("select an image")); + let file = dir.file("one.png"); + assert!(refused(&mut s, json!({"ids": [a.0], "folder": file})).ends_with(&format!("{file} is not a folder"))); + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + let rect = s.doc().unwrap().selection.objects[0]; + assert!(refused(&mut s, json!({"ids": [a.0, rect.0], "folder": out})).ends_with(&format!("object {} is not an image", rect.0))); + assert!(files_in(&out).is_empty(), "nothing written for a refused request"); + run(&mut s, "links.unembed", json!({"ids": [a.0], "folder": out})); + assert!(refused(&mut s, json!({"ids": [a.0], "folder": out})).ends_with(&format!("image {} is linked already", a.0))); + assert_eq!(files_in(&out), ["one.png"]); +} + +/// Under automation write roots, a folder outside them takes no file. +#[test] +fn unembed_to_a_folder_outside_the_write_roots_is_refused() { + use crate::file_access::{AutomationRoots, confine}; + let dir = Folder::new("unembed-folder-roots"); + let (inside, outside) = (dir.file("inside"), dir.file("outside")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + write(&file_in(&inside, "pic.png"), &png(60, 30, RED)); + let mut s = session(); + let id = place_embedded(&mut s, &file_in(&inside, "pic.png")); + let roots = AutomationRoots::new(&[dir.0.as_path()], &[std::path::Path::new(&inside)]).unwrap(); + let p = json!({"ids": [id.0], "folder": outside}); + let e = confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap_err().to_string(); + assert!(e.contains("outside the write root"), "{e}"); + assert!(files_in(&outside).is_empty()); + assert!(image(&s, id).link.is_none()); + let p = json!({"ids": [id.0], "folder": inside}); + confine(roots.as_ref(), || s.execute("links.unembed", &p)).unwrap(); + assert!(image(&s, id).link.is_some()); +} + #[test] fn go_to_selects_the_image() { let dir = Folder::new("goto"); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ac55a78ff4..4884672616 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6628,6 +6628,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg Trap: select two or more objects filled with solid colours Trap: selecciona dos o més objectes emplenats amb colors sòlids @msg truncated truncat @msg Unembedded to {_1} S’ha desincrustat a {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} S’ha desincrustat {n} imatge a {folder}|S’han desincrustat {n} imatges a {folder} +@msg every numbered name for {name} is taken in that folder tots els noms numerats per a {name} estan ocupats en aquesta carpeta +@msg give id and path for one image, or ids and folder for several indiqueu id i path per a una imatge, o ids i folder per a diverses @msg unknown command `{0}` ordre desconeguda `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` el pas {step} de “{action}” executa l’ordre desconeguda `{command}` @msg unknown command `{0}`; did you mean `{1}`? ordre desconeguda `{0}`; volies dir `{1}`? diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 69dd46dc23..5b8af44327 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5636,6 +5636,9 @@ liquify-list-end {0}, {1} {0} a {1} @msg All colors are within the CMYK gamut Všechny barvy jsou v gamutu CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} barva je mimo gamut CMYK|{n} barvy jsou mimo gamut CMYK|{n} barev je mimo gamut CMYK @msg Unembedded to {_1} Vložení zrušeno, uloženo do: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Vložení zrušeno u {n} obrázku, uloženo do: {folder}|Vložení zrušeno u {n} obrázků, uloženo do: {folder}|Vložení zrušeno u {n} obrázků, uloženo do: {folder} +@msg every numbered name for {name} is taken in that folder v této složce jsou obsazena všechna číslovaná jména pro {name} +@msg give id and path for one image, or ids and folder for several zadejte id a path pro jeden obrázek, nebo ids a folder pro více obrázků @msg Reset {_1} Obnoveno: {_1} @msg Sent to {_1} Odesláno do {_1} @msg {_1} files Soubory {_1} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7bc0ed6c94..e8aeb4acff 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7742,6 +7742,9 @@ imageTrace Outline Kontur @msg All colors are within the CMYK gamut Alle farver er inden for CMYK-farveomfanget @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} farve er uden for CMYK-farveomfanget|{n} farver er uden for CMYK-farveomfanget @msg Unembedded to {_1} Fjernede indlejring til {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Fjernede indlejring af {n} billede til {folder}|Fjernede indlejring af {n} billeder til {folder} +@msg every numbered name for {name} is taken in that folder alle nummererede navne til {name} er optaget i den mappe +@msg give id and path for one image, or ids and folder for several angiv id og path for ét billede, eller ids og folder for flere @msg Reset {_1} Nulstillede {_1} @msg Sent to {_1} Sendte til {_1} @msg {_1} files {_1}-filer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4b17261bfb..7d7dc5d181 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5237,6 +5237,9 @@ liquify-list-end {0}, {1} {0} und {1} @msg All colors are within the CMYK gamut Alle Farben liegen im CMYK-Farbumfang @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} Farbe liegt außerhalb des CMYK-Farbumfangs|{n} Farben liegen außerhalb des CMYK-Farbumfangs @msg Unembedded to {_1} Einbettung aufgehoben, gespeichert unter {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Einbettung von {n} Bild aufgehoben, gespeichert unter {folder}|Einbettung von {n} Bildern aufgehoben, gespeichert unter {folder} +@msg every numbered name for {name} is taken in that folder alle nummerierten Namen für {name} sind in diesem Ordner bereits vergeben +@msg give id and path for one image, or ids and folder for several geben Sie id und path für ein Bild oder ids und folder für mehrere an @msg Reset {_1} {_1} zurückgesetzt @msg Sent to {_1} An {_1} gesendet @msg {_1} files {_1}-Dateien diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bba8d392ad..3d779a0b98 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5291,6 +5291,9 @@ digits Malayalam Μαλαγιάλαμ @msg All colors are within the CMYK gamut Όλα τα χρώματα βρίσκονται εντός της χρωματικής γκάμας CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} χρώμα βρίσκεται εκτός της χρωματικής γκάμας CMYK|{n} χρώματα βρίσκονται εκτός της χρωματικής γκάμας CMYK @msg Unembedded to {_1} Καταργήθηκε η ενσωμάτωση στο {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Καταργήθηκε η ενσωμάτωση {n} εικόνας στο {folder}|Καταργήθηκε η ενσωμάτωση {n} εικόνων στο {folder} +@msg every numbered name for {name} is taken in that folder όλα τα αριθμημένα ονόματα για το {name} χρησιμοποιούνται ήδη σε αυτόν τον φάκελο +@msg give id and path for one image, or ids and folder for several δώστε id και path για μία εικόνα ή ids και folder για πολλές @msg Reset {_1} Επαναφορά {_1} @msg Sent to {_1} Στάλθηκε στο {_1} @msg {_1} files {_1} αρχεία diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 57e7f44e87..9d7dc87750 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5344,6 +5344,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg All colors are within the CMYK gamut Todos los colores están dentro de la gama CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} color está fuera de la gama CMYK|{n} colores están fuera de la gama CMYK @msg Unembedded to {_1} Se desincrustó en {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Se desincrustó {n} imagen en {folder}|Se desincrustaron {n} imágenes en {folder} +@msg every numbered name for {name} is taken in that folder todos los nombres numerados para {name} ya existen en esa carpeta +@msg give id and path for one image, or ids and folder for several indique id y path para una imagen, o ids y folder para varias @msg Reset {_1} Se restableció {_1} @msg Sent to {_1} Se envió a {_1} @msg {_1} files {_1} archivos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0276e5b6ed..c6f89c572b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5560,6 +5560,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg All colors are within the CMYK gamut Kaikki värit ovat CMYK-väriavaruuden sisällä @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} väri on CMYK-väriavaruuden ulkopuolella|{n} väriä on CMYK-väriavaruuden ulkopuolella @msg Unembedded to {_1} Upotus purettiin kohteeseen {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Upotus purettiin {n} kuvalta kohteeseen {folder}|Upotus purettiin {n} kuvalta kohteeseen {folder} +@msg every numbered name for {name} is taken in that folder kaikki kohteen {name} numeroidut nimet ovat jo käytössä siinä kansiossa +@msg give id and path for one image, or ids and folder for several anna id ja path yhdelle kuvalle tai ids ja folder useammalle @msg Reset {_1} Palautettiin oletukseksi {_1} @msg Sent to {_1} Lähetettiin kohteeseen {_1} @msg {_1} files {_1}-tiedostot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 75f4f14c6f..409d165561 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5302,6 +5302,9 @@ liquify-list-end {0}, {1} {0} et {1} @msg All colors are within the CMYK gamut Toutes les couleurs sont dans la gamme CMJN @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} couleur est hors de la gamme CMJN|{n} couleurs sont hors de la gamme CMJN @msg Unembedded to {_1} Incorporation annulée vers {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Incorporation annulée pour {n} image vers {folder}|Incorporation annulée pour {n} images vers {folder} +@msg every numbered name for {name} is taken in that folder tous les noms numérotés pour {name} sont déjà pris dans ce dossier +@msg give id and path for one image, or ids and folder for several indiquez id et path pour une image, ou ids et folder pour plusieurs @msg Reset {_1} {_1} réinitialisé @msg Sent to {_1} Envoyé à {_1} @msg {_1} files Fichiers {_1} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 094d49ce52..3bdb1a8bbe 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8697,6 +8697,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg type that changes writing direction inside a text object opens in the direction of its first character टेक्स्ट ऑब्जेक्ट के भीतर लेखन दिशा बदलने वाला टेक्स्ट अपने पहले वर्ण की दिशा में खुलता है @msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip लिंक्ड एरिया, रैपअराउंड टेक्स्ट या कंपाउंड पाथ में मास्क के रूप में इस्तेमाल किया गया टाइप क्लिप नहीं करता @msg Unembedded to {_1} एम्बेड हटाकर {_1} में रखा गया +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} इमेज का एम्बेड हटाकर {folder} में रखा गया|{n} इमेज का एम्बेड हटाकर {folder} में रखा गया +@msg every numbered name for {name} is taken in that folder {name} के लिए हर नंबर वाला नाम उस फ़ोल्डर में पहले से लिया गया है +@msg give id and path for one image, or ids and folder for several एक इमेज के लिए id और path दें, या कई के लिए ids और folder दें @msg unexpected host trap होस्ट में अप्रत्याशित ट्रैप @msg unexpected resources अप्रत्याशित संसाधन @msg unknown {k} key `{key}` (size, position) अज्ञात {k} कुंजी `{key}` (size, position) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d5f42ce788..ae4ff60666 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6029,6 +6029,9 @@ liquify-list-end {0}, {1} {0} és {1} @msg tool shortcuts must be a single key (optionally with Shift) eszköz billentyűparancsa egyetlen billentyű lehet (Shifttel vagy anélkül) @msg truncated csonka @msg Unembedded to {_1} Beágyazás megszüntetve, ide: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Beágyazás megszüntetve, képek: {n}, ide: {folder} +@msg every numbered name for {name} is taken in that folder abban a mappában minden sorszámozott név foglalt: {name} +@msg give id and path for one image, or ids and folder for several egy képhez adja meg az id és a path, többhöz az ids és a folder értékét @msg unknown command `{0}` ismeretlen parancs: `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` „{action}”, lépés: {step}: ismeretlen parancsot futtat: `{command}` @msg unknown command `{0}`; did you mean `{1}`? ismeretlen parancs: `{0}`; erre gondolt: `{1}`? diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8bc9d44147..8b8731b54d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5370,6 +5370,9 @@ liquify-list-end {0}, {1} {0} e {1} @msg All colors are within the CMYK gamut Tutti i colori rientrano nella gamma CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} colore è fuori dalla gamma CMYK|{n} colori sono fuori dalla gamma CMYK @msg Unembedded to {_1} Incorporamento rimosso, salvato in {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Incorporamento rimosso per {n} immagine, salvata in {folder}|Incorporamento rimosso per {n} immagini, salvate in {folder} +@msg every numbered name for {name} is taken in that folder tutti i nomi numerati per {name} sono già usati in quella cartella +@msg give id and path for one image, or ids and folder for several indica id e path per un’immagine, oppure ids e folder per più immagini @msg Reset {_1} Reimpostato {_1} @msg Sent to {_1} Inviato a {_1} @msg {_1} files {_1} file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 57c9aee61e..9e52214354 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5439,6 +5439,9 @@ liquify-list-end {0}, {1} {0}、{1} @msg All colors are within the CMYK gamut すべてのカラーが CMYK の色域内です @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個のカラーが CMYK の色域外です @msg Unembedded to {_1} 埋め込みを解除して {_1} に保存しました +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} 枚の画像の埋め込みを解除して {folder} に保存しました +@msg every numbered name for {name} is taken in that folder そのフォルダーでは、{name} の番号付きの名前がすべて使われています +@msg give id and path for one image, or ids and folder for several 1 つの画像には id と path を、複数の画像には ids と folder を指定してください @msg no swatch library `{l}` (see swatch.library.list) スウォッチライブラリ `{l}` が見つかりません (swatch.library.list を参照) @msg no user library folder here この環境にはユーザーライブラリフォルダーがありません @msg Couldn't place {name}: the document it was dropped on was closed {name} を配置できませんでした: ドロップ先のドキュメントは閉じられています diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a661bc0cbb..1858315d79 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7004,6 +7004,9 @@ font-technology Variable ცვლადი @msg All colors are within the CMYK gamut ყველა ფერი CMYK-ის გამის ფარგლებშია @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut CMYK-ის გამის ფარგლებს გარეთაა ფერი ({n}) @msg Unembedded to {_1} ჩაშენება მოხსნილია: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} ჩაშენება მოხსნილია, გამოსახულებები: {n}, საქაღალდე: {folder} +@msg every numbered name for {name} is taken in that folder იმ საქაღალდეში {name}-ის ყველა დანომრილი სახელი დაკავებულია +@msg give id and path for one image, or ids and folder for several ერთი გამოსახულებისთვის მიუთითეთ id და path, რამდენიმესთვის კი ids და folder @msg Reset {_1} ჩამოყრილია: {_1} @msg Sent to {_1} გაგზავნილია: {_1} @msg {_1} files ფაილები: {_1} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 632c2473f8..a9c2f64c34 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5366,6 +5366,9 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg All colors are within the CMYK gamut 모든 색상이 CMYK 색상 범위 안에 있습니다 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut 색상 {n}개가 CMYK 색상 범위를 벗어났습니다 @msg Unembedded to {_1} {_1}에 포함 해제했습니다 +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 이미지 {n}개를 {folder}에 포함 해제했습니다 +@msg every numbered name for {name} is taken in that folder 해당 폴더에서 {name}을(를) 위한 번호 이름이 모두 사용 중입니다 +@msg give id and path for one image, or ids and folder for several 이미지 하나에는 id와 path를, 여러 개에는 ids와 folder를 지정하세요 @msg no swatch library `{l}` (see swatch.library.list) 견본 라이브러리 `{l}`이(가) 없습니다(swatch.library.list 참조) @msg no user library folder here 여기에는 사용자 라이브러리 폴더가 없습니다 @msg Couldn't place {name}: the document it was dropped on was closed {name}을(를) 가져올 수 없습니다: 놓은 문서가 닫혔습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0137b7ac5b..d62e2d58b8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5636,6 +5636,9 @@ imageTrace Outline Contour @msg All colors are within the CMYK gamut Alle kleuren vallen binnen het CMYK-gamut @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kleur valt buiten het CMYK-gamut|{n} kleuren vallen buiten het CMYK-gamut @msg Unembedded to {_1} Extern gemaakt: {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} afbeelding extern gemaakt in {folder}|{n} afbeeldingen extern gemaakt in {folder} +@msg every numbered name for {name} is taken in that folder elke genummerde naam voor {name} is al vergeven in die map +@msg give id and path for one image, or ids and folder for several geef id en path voor één afbeelding, of ids en folder voor meerdere @msg Reset {_1} {_1} opnieuw ingesteld @msg Sent to {_1} Verzonden naar {_1} @msg {_1} files {_1}-bestanden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a2909473c2..290b6d7708 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5462,6 +5462,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg All colors are within the CMYK gamut Wszystkie kolory mieszczą się w gamucie CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} kolor nie mieści się w gamucie CMYK|{n} kolory nie mieszczą się w gamucie CMYK|{n} kolorów nie mieści się w gamucie CMYK @msg Unembedded to {_1} Wyodrębniono do {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Wyodrębniono {n} obraz do {folder}|Wyodrębniono {n} obrazy do {folder}|Wyodrębniono {n} obrazów do {folder} +@msg every numbered name for {name} is taken in that folder wszystkie numerowane nazwy dla {name} są zajęte w tym folderze +@msg give id and path for one image, or ids and folder for several podaj id i path dla jednego obrazu albo ids i folder dla kilku @msg Reset {_1} Zresetowano {_1} @msg Sent to {_1} Wysłano do {_1} @msg {_1} files Pliki {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9c7e0fddd5..9acb322df7 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4643,6 +4643,9 @@ axis Both Ambos @msg All colors are within the CMYK gamut Todas as cores estão dentro do gamut CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} cor está fora do gamut CMYK|{n} cores estão fora do gamut CMYK @msg Unembedded to {_1} Desincorporado para {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} imagem desincorporada para {folder}|{n} imagens desincorporadas para {folder} +@msg every numbered name for {name} is taken in that folder todos os nomes numerados para {name} já existem nessa pasta +@msg give id and path for one image, or ids and folder for several informe id e path para uma imagem, ou ids e folder para várias @msg Reset {_1} Redefinir {_1} @msg Sent to {_1} Enviado para {_1} @msg {_1} files {_1} arquivos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 87424a1938..03e571d721 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5368,6 +5368,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg All colors are within the CMYK gamut Все цвета входят в цветовой охват CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} цвет выходит за пределы цветового охвата CMYK|{n} цвета выходят за пределы цветового охвата CMYK|{n} цветов выходят за пределы цветового охвата CMYK @msg Unembedded to {_1} Извлечено в {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Извлечено {n} изображение в {folder}|Извлечено {n} изображения в {folder}|Извлечено {n} изображений в {folder} +@msg every numbered name for {name} is taken in that folder все нумерованные имена для {name} уже заняты в этой папке +@msg give id and path for one image, or ids and folder for several укажите id и path для одного изображения или ids и folder для нескольких @msg Reset {_1} Сброшено: {_1} @msg Sent to {_1} Отправлено в {_1} @msg {_1} files {_1} файлов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 62ac5b67a8..2a0c199535 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5232,6 +5232,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg All colors are within the CMYK gamut Alla färger ligger inom CMYK-färgomfånget @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} färg ligger utanför CMYK-färgomfånget|{n} färger ligger utanför CMYK-färgomfånget @msg Unembedded to {_1} Extraherad till {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Extraherade {n} bild till {folder}|Extraherade {n} bilder till {folder} +@msg every numbered name for {name} is taken in that folder alla numrerade namn för {name} är upptagna i den mappen +@msg give id and path for one image, or ids and folder for several ange id och path för en bild, eller ids och folder för flera @msg Reset {_1} Återställ {_1} @msg Sent to {_1} Skickat till {_1} @msg {_1} files {_1}-filer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9076b8da7c..c348362813 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5061,6 +5061,9 @@ liquify-list-end {0}, {1} {0} ve {1} @msg All colors are within the CMYK gamut Tüm renkler CMYK gamındadır @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} renk CMYK gamının dışında @msg Unembedded to {_1} {_1}'ye gömülü değil +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} {n} görselin gömülmesi kaldırıldı: {folder} +@msg every numbered name for {name} is taken in that folder {name} için numaralandırılmış her ad o klasörde zaten kullanılıyor +@msg give id and path for one image, or ids and folder for several tek görsel için id ve path, birden çok görsel için ids ve folder verin @msg Reset {_1} {_1}'yi sıfırla @msg Sent to {_1} {_1}'ye gönderildi @msg {_1} files {_1} dosyaları diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c701f1bd5d..1c6f068b29 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5354,6 +5354,9 @@ liquify-list-end {0}, {1} {0} і {1} @msg All colors are within the CMYK gamut Усі кольори входять у колірне охоплення CMYK @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} колір виходить за межі колірного охоплення CMYK|{n} кольори виходять за межі колірного охоплення CMYK|{n} кольорів виходять за межі колірного охоплення CMYK @msg Unembedded to {_1} Вилучено у {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Вилучено {n} зображення у {folder}|Вилучено {n} зображення у {folder}|Вилучено {n} зображень у {folder} +@msg every numbered name for {name} is taken in that folder усі нумеровані імена для {name} уже зайняті в цій папці +@msg give id and path for one image, or ids and folder for several укажіть id і path для одного зображення або ids і folder для кількох @msg Reset {_1} Скинуто: {_1} @msg Sent to {_1} Відправлено до {_1} @msg {_1} files {_1} файлів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7ce09032d1..afbe3c059b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5784,6 +5784,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg tool shortcuts must be a single key (optionally with Shift) phím tắt công cụ phải là một phím đơn (tùy chọn với Shift) @msg truncated bị cắt ngắn @msg Unembedded to {_1} Đã bỏ nhúng vào {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} Đã bỏ nhúng {n} ảnh vào {folder} +@msg every numbered name for {name} is taken in that folder mọi tên đánh số cho {name} đã được dùng trong thư mục đó +@msg give id and path for one image, or ids and folder for several hãy nhập id và path cho một ảnh, hoặc ids và folder cho nhiều ảnh @msg unknown command `{0}` lệnh không xác định `{0}` @msg step {step} of “{action}” runs the unknown command `{command}` bước {step} của “{action}” chạy lệnh không xác định `{command}` @msg unknown command `{0}`; did you mean `{1}`? lệnh không xác định `{0}`; ý bạn là `{1}`? diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 86f04f416e..aef0eaec5f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5116,6 +5116,9 @@ liquify-list-end {0}, {1} {0}和{1} @msg All colors are within the CMYK gamut 所有颜色皆在 CMYK 色域内 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 个颜色超出 CMYK 色域 @msg Unembedded to {_1} 已取消嵌入到 {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 已将 {n} 张图像取消嵌入到 {folder} +@msg every numbered name for {name} is taken in that folder 该文件夹中 {name} 的所有带编号的名称均已被占用 +@msg give id and path for one image, or ids and folder for several 单个图像请提供 id 和 path,多个图像请提供 ids 和 folder @msg no swatch library `{l}` (see swatch.library.list) 没有色板库 `{l}` (请参阅 swatch.library.list) @msg no user library folder here 此处没有用户库文件夹 @msg Couldn't place {name}: the document it was dropped on was closed 无法置入 {name}:将它拖放到的文档已关闭 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 65e5274812..b917cfe755 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2749,6 +2749,9 @@ liquify-list-end {0}, {1} {0}和{1} @msg All colors are within the CMYK gamut 所有顏色皆在 CMYK 色域內 @msgplural {n} color is out of the CMYK gamut|{n} colors are out of the CMYK gamut {n} 個顏色超出 CMYK 色域 @msg Unembedded to {_1} 已取消內嵌至 {_1} +@msgplural Unembedded {n} image to {folder}|Unembedded {n} images to {folder} 已將 {n} 個影像取消內嵌至 {folder} +@msg every numbered name for {name} is taken in that folder 該資料夾中 {name} 的所有編號名稱都已被使用 +@msg give id and path for one image, or ids and folder for several 單一影像請提供 id 和 path,多個影像請提供 ids 和 folder @msg no swatch library `{l}` (see swatch.library.list) 沒有色票資料庫 `{l}` (請參閱 swatch.library.list) @msg no user library folder here 此處沒有使用者資料庫資料夾 @msg Couldn't place {name}: the document it was dropped on was closed 無法置入 {name}:放置它的文件已關閉 diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 611c9e472a..3b45e450d4 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -335,6 +335,37 @@ pub(crate) fn unembed(app: &mut VectorcraftApp, id: u64, name: &str) { }); } +/// Whether Unembed… can act on `embedded` selected embedded images: one goes to a picked file, +/// several to a picked folder (the web downloads each one). +pub(crate) fn can_unembed(app: &VectorcraftApp, embedded: usize) -> bool { + match embedded { + 0 => false, + 1 => true, + _ => app.services.download.is_some() || app.services.pick_folder.is_some(), + } +} + +/// Write embedded images `ids` to new files in a picked folder and link each one to its file, in +/// one undo step (the web downloads each one and links none). +pub(crate) fn unembed_several(app: &mut VectorcraftApp, ids: Vec) { + if app.services.download.is_some() { + for id in ids { + unembed(app, id, ""); + } + return; + } + crate::picks::button(app, move |app| unembed_to_picked_folder(app, ids.clone())); +} + +fn unembed_to_picked_folder(app: &mut VectorcraftApp, ids: Vec) { + let Some(folder) = crate::picks::folder(app) else { return }; + let r = app.run("links.unembed", json!({ "ids": ids, "folder": folder })); + report(app, r, |v| { + let n = v["unembedded"].as_array().map_or(0, Vec::len); + crate::i18n::msg_n(n as u64, "Unembedded {n} image to {folder}", "Unembedded {n} images to {folder}", &[("folder", &folder)]) + }); +} + /// The UI commands `links.editOriginal` (open the linked file in its app) and `links.reveal` /// (show it in its folder) for image `id` (default: the selected linked image) → `{path}`. pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Result { @@ -834,12 +865,16 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); } - if menu_item(ui, tl!("Unembed…"), embedded.len() == 1, false) - && let Some(r) = embedded.first() - && let Some(id) = r["id"].as_u64() - { - let name = r["name"].as_str().unwrap_or("Image").to_string(); - unembed(app, id, &name); + if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { + match &embedded[..] { + [r] => { + if let Some(id) = r["id"].as_u64() { + let name = r["name"].as_str().unwrap_or("Image").to_string(); + unembed(app, id, &name); + } + } + rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), + } } if menu_item(ui, tl!("Placement Options…"), any, false) { crate::menus::invoke(app, "ui.placementOptionsDialog", json!({ "ids": ids(&sel, |_| true) })); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 781c4f5840..aaf0ed0be7 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -500,6 +500,36 @@ fn properties_shows_the_selected_image_and_its_link_actions() { assert!(text.contains("Linked File") && text.contains("Edit Original") && text.contains("Embed"), "{text}"); } +/// Unembed… acts on several selected embedded images: it asks for one folder, writes a file for +/// each image there and links each one to its file; with no folder picked, nothing changes. +#[test] +fn unembed_writes_several_images_to_one_picked_folder() { + let dir = Folder::new("unembed-several"); + let (mut app, _, embedded) = app(&dir); + let c = dir.file("other.png", &png(30, 10)); + let other = app.run("file.place", json!({"path": c, "at": [50, 50], "link": false})).unwrap()["ids"][0].as_u64().unwrap(); + assert!(super::links::can_unembed(&app, 1)); + assert!(!super::links::can_unembed(&app, 0)); + assert!(!super::links::can_unembed(&app, 2), "no folder to pick"); + let out = dir.0.join("out"); + std::fs::create_dir_all(&out).unwrap(); + // No folder picked: nothing written or linked. + app.services.pick_folder = Some(Box::new(|| None)); + assert!(super::links::can_unembed(&app, 2)); + super::links::unembed_several(&mut app, vec![embedded, other]); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0); + assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["status"], "embedded"); + let picked = out.to_string_lossy().into_owned(); + let answer = picked.clone(); + app.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); + super::links::unembed_several(&mut app, vec![embedded, other]); + for (id, name) in [(embedded, "embedded.png"), (other, "other.png")] { + let info = app.run("links.info", json!({"id": id})).unwrap(); + assert_eq!(info["path"], out.join(name).to_string_lossy().as_ref(), "{info}"); + } + assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); +} + #[test] fn the_links_menu_items_run_commands() { let tree = crate::menus::menu_tree(); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..ce2a1b509d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8278,6 +8278,16 @@ every object in the layers each time the list is read. A `dcsTransparency` that returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. +`links.unembed {ids?, folder}` writes each embedded image of `ids` (default: the selected embedded images) to a new +file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo +step; undo does not remove the files. A file is named after its image, with each character a file name can't hold +(`/ \ : * ? " < > |` and control characters) as `_` and `Image` when nothing is left; when the name is taken it is +`Name 2.png` … `Name 99.png`, and a file already in the folder is never replaced. Linked images among `ids` are left +as they are and listed in `skipped`. It returns `{unembedded: [{id, path}], skipped}`. When an image can't be written, +the files the call wrote are removed and the document does not change. A folder outside the automation write roots, +`id` or `path` given with `ids` or `folder`, an id given twice, and `ids` with no embedded image are errors. The Links +panel menu's Unembed… with several embedded images selected asks for one folder and runs this form (on the web it +downloads each image instead and links none). `links.placementOptions {ids?, preserve?: transforms|bounds|fileDimensions|fit|fill, align?: topLeft…bottomRight, clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and @@ -8296,6 +8306,7 @@ malformed `ids`, or nothing to copy is an error, and the clipboard is left as it {"name":"run_command","arguments":{"command":"links.list","params":{"show":"missing"}}} {"name":"run_command","arguments":{"command":"links.placementOptions","params":{"ids":[12],"preserve":"fit","align":"top"}}} {"name":"run_command","arguments":{"command":"links.unembed","params":{"id":14,"path":"/tmp/logo.png"}}} +{"name":"run_command","arguments":{"command":"links.unembed","params":{"ids":[14,15],"folder":"/tmp/images"}}} ``` ## Package and Document Info diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af7974b880..5ba7be6af8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2022,6 +2022,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Missing linked files can be looked for in a folder and its subfolders: Find in Folder… in the Linked File Not Found dialog and in the Links panel menu lists the files with each one's name, those with the size and contents saved with the link first, and relinks the files chosen, copying an image's file into the document's folder when asked, without replacing a file there (`links.findFiles`, `links.relink {copy}`). In the Links panel it looks for the selected linked files when any are selected. - The Links panel's Relink… opens a Relink dialog whose Replace menu picks which links take the new file: Selected Instances (the selected images, as before), All Instances (every image linked to the same file), Missing Links from This Folder (then every other missing link whose file name is in the new file's folder) and Each Link Separately (a file for each selected link in turn). Each relinks as one undo step (`links.relink {scope}`, `ui.relinkDialog`). Relink to Folder… stays as it is. - The Links panel menu's Copy Info ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) copies the selected link's file name to the clipboard (`links.copyInfo`). VectorCraft's own rules: with several rows selected it copies one name per line in the order the panel shows them, an embedded image gives the name its row shows, and the item is off with no row selected. + - The Links panel menu's Unembed… works on several selected embedded images at once and writes them all to one chosen folder ([Embed and unembed images and files](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/manage-linked-and-embedded-files/embed-images-and-files.html)): it asks for a folder once, writes a file for each image there and links each image to its file in one undo step (`links.unembed {ids, folder}`). VectorCraft's own rules: each file keeps the format its image is stored in (or PNG when that format is not one of VectorCraft's raster file formats) and is named after the image, a taken name gets a number (`Name 2`) and a file already in the folder is never replaced, linked rows in the selection are left as they are, and when one image can't be written the files already written are removed and nothing is unembedded. On the web each image is downloaded instead. Evidence: `unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step`, `unembed_to_a_folder_that_fails_leaves_no_file_and_no_change`, `unembed_writes_several_images_to_one_picked_folder`. - Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Update Links, and opening with Update Links: Automatically, read a modified file again for that art too, and saving a document refreshes its placed copies inside symbols and patterns of the other open documents. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`, `update_links_reads_files_again_inside_symbols_patterns_and_masks`, `saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns`. - A linked file that is missing when a moved document is saved keeps the folder its relative path names, instead of a relative path worked out from the out-of-date absolute path, also for a `.ai` file another app wrote (such as `src/`), so the file is found once it is back in that folder. Evidence: `a_missing_link_keeps_its_relative_path_when_the_moved_document_is_saved`, `links_of_an_imported_file_are_found_by_their_relative_folder`, `a_missing_link_of_a_moved_document_keeps_its_relative_place`. - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. From 7d4aa9d8ab25ea96b76ce51c6bc5d1c2b8c12e0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:02:57 -0800 Subject: [PATCH 096/138] MCP: the ui.expandDialog mirror lists immediate and the kept choices crates/mcp/src/ui_catalog.rs now matches the desktop entry in crates/ui-egui/src/menus/ui_commands.rs, so cargo xtask ui-commands --check passes and MCP discovery lists the immediate parameter. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0e3d6df203..939c656378 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1264,7 +1264,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.expandDialog", "Expand…", "", - "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + "{immediate?: bool (false)} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255), or the choices OK last expanded with since the app started): OK runs object.expand with them as one undo step and keeps them until the app quits; immediate: true (the menu item chosen with Alt/Option) runs object.expand at once with those choices (the defaults before any OK), and opens the dialog instead when none of them has something to expand in the selection; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", ), ( "attributes.openUrl", From be27667228f9edf6f06134328700512fa92f0752 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:16:50 -0800 Subject: [PATCH 097/138] =?UTF-8?q?EPS=20Options:=20Custom=E2=80=A6=20sets?= =?UTF-8?q?=20the=20flattener=20options=20the=20export=20uses?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit EPS Options gets a Custom… button beside the flattener Preset. It opens Custom Transparency Flattener Options over EPS Options, on the options the export would use (the raster/vector balance, both resolutions, the outline switches, Clip Complex Regions and Anti-alias Rasters). OK sends them as `flattener` with the export, and the preset shows [Custom] when they differ from its options; Cancel goes back unchanged. Choosing a preset, in the dropdown or with `ui.dialog.set`, drops the custom options. Preserve Alpha Transparency stays off for EPS, and overprints follow the Overprints choice. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs.rs | 8 +- crates/ui-egui/src/dialogs/eps_options.rs | 122 ++++++++++++++++++++-- crates/ui-egui/src/dialogs/flatten.rs | 28 +++-- crates/ui-egui/src/dialogs/tests_eps.rs | 102 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/control-protocol.md | 10 +- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 37 files changed, 341 insertions(+), 23 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0e3d6df203..a8b477fe63 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1658,7 +1658,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.epsOptionsDialog", "EPS Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), ( "file.saveForWeb", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index da1062838f..685642f323 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -415,6 +415,7 @@ registry! { SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, + EpsFlattenerOptions: [eps_options::CUSTOM_KIND] => eps_options::CUSTOM_SPEC, Recovery: [crate::recovery::KIND] => recovery::SPEC, PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC, SafeMode: [safe_mode::KIND] => safe_mode::SPEC, @@ -652,7 +653,8 @@ pub(crate) fn parent(d: &Dialog) -> Option { } /// `ui.dialog.set` changed `field` of the open dialog from `old`: a choice that sets other fields -/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`), a change +/// sets them as choosing it in the dialog does (Export for Screens' `exportPreset`, EPS Options' +/// `flattenerPreset`, which drops the Custom… options), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in /// the dialog, and Transform Each's Relative / Absolute keeps the Scale fields' size. A value /// Composite Fonts' Show Sample can't take is refused. @@ -664,6 +666,10 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { return composite_fonts::field_set(d, field); } + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { + eps_options::field_set(d, field); + return Ok(()); + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == export_for_screens::KIND) else { return Ok(()) }; match field { "exportPreset" => export_for_screens::preset_set(app), diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 8d34706df4..afe0553f87 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -6,14 +6,20 @@ //! Fields: `document.export` params (`format: eps`, `path?`, the artboard choice) and the EPS //! options of `document.exportEps`. OK remembers the options for next time and writes the file //! (asking where when there is no path); bad options keep the dialog open. +//! +//! Custom… beside the flattener preset opens Custom Transparency Flattener Options over the +//! dialog: its OK sets every flattener option as `flattener` (the preset then shows [Custom]) and +//! goes back to EPS Options; Cancel goes back with the options as they were. Choosing a preset +//! drops the custom options. use serde_json::{Map, Value, json}; -use vectorcraft_engine::cmd::{FlattenOptions, fileio}; +use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; use super::DialogSpec; use super::document_setup::{LABEL, check, choice}; use crate::state::Dialog; +use crate::theme::Tokens; use crate::{VectorcraftApp, io, widgets}; pub(super) const KIND: &str = "epsOptions"; @@ -25,7 +31,18 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ok: Some("Export"), min_width: 420.0, max_width: Some(460.0), - inputs: |_| &["path"], + inputs: |_| &["path", "flattener"], + ..DialogSpec::FORM +}; + +/// Custom Transparency Flattener Options, opened over EPS Options by Custom…. +pub(super) const CUSTOM_KIND: &str = "epsFlattenerOptions"; + +pub(super) const CUSTOM_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Custom Transparency Flattener Options").into(), + body: custom_body, + confirm: custom_confirm, + min_width: 420.0, ..DialogSpec::FORM }; @@ -61,11 +78,12 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { fields.extend(o.iter().map(|(k, v)| (k.clone(), v.clone()))); } } - fields.insert("format".into(), json!("eps")); - // A built-in preset named by id (`medium`) shows as its name. - if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { - fields.insert("flattenerPreset".into(), json!(label)); + // A preset asked for without options of its own replaces the custom options used last. + if params.get("flattenerPreset").is_some() && params.get("flattener").is_none() { + fields.remove("flattener"); } + fields.insert("format".into(), json!("eps")); + builtin_label(&mut fields); app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); } @@ -90,8 +108,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let overprints: Vec<(&str, &str)> = Overprint::ALL.iter().map(|o| (o.id(), o.label())).collect(); choice(ui, d, "overprints", tl!("Overprints:"), &overprints); let presets = app.session.flattener_presets(); - let names: Vec<(&str, &str)> = presets.iter().map(|p| (p.name.as_str(), p.name.as_str())).collect(); - choice(ui, d, "flattenerPreset", tl!("Preset:"), &names); + let current = flattener(d, &app.session.prefs.flattener_presets).ok(); + let mut custom = false; + widgets::label_row(ui, tl!("Preset:"), LABEL, |ui| { + if let Some(p) = super::flatten::preset_dropdown(ui, "eps-flattener-preset", &presets, &d.str("flattenerPreset"), current.as_ref(), 180.0) { + d.fields.insert("flattenerPreset".into(), json!(p.name)); + d.fields.remove("flattener"); + } + custom = widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked(); + }); + if custom { + *d = over(d, &app.session.prefs.flattener_presets); + return false; + } ui.add_space(8.0); widgets::subheader(ui, tl!("Fonts")); // Type is written as glyph outlines, which need no fonts. @@ -122,6 +151,83 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } +/// `ui.dialog.set` changed `field` of EPS Options `d`: a preset set there drops the Custom… +/// options, as choosing it in the dropdown does, and a built-in one named by id shows as its name. +pub(super) fn field_set(d: &mut Dialog, field: &str) { + if field == "flattenerPreset" { + d.fields.remove("flattener"); + builtin_label(&mut d.fields); + } +} + +/// A built-in preset named by id (`medium`) in `fields` shows as its name. +fn builtin_label(fields: &mut Map) { + if let Some(label) = fields.get("flattenerPreset").and_then(Value::as_str).and_then(|p| FlattenOptions::preset_label(&p.to_ascii_lowercase())) { + fields.insert("flattenerPreset".into(), json!(label)); + } +} + +/// The flattener options EPS Options `d` exports with: its preset, with the Custom… options over it. +fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result { + FlattenOptions::for_export(d.fields.get("flattenerPreset").and_then(Value::as_str), d.fields.get("flattener"), saved) +} + +/// Custom Transparency Flattener Options over EPS Options `parent`, on the options it exports with +/// (the default preset's while those are not valid), without alpha: EPS has none. +pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog { + let mut o = flattener(parent, saved).unwrap_or_default(); + o.preserve_alpha = false; + let mut d = Dialog::new(CUSTOM_KIND, json!({})); + super::flatten::put_options(&mut d.fields, &o); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + d +} + +/// The options Custom Transparency Flattener Options `d` holds. +fn custom_options(d: &Dialog) -> Result { + FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[]) +} + +/// Whether the EPS Options under `d` keep overprints (Overprints: Preserve). +fn overprints_kept(d: &Dialog) -> bool { + super::parent(d).is_none_or(|p| Overprint::from_id(&p.str("overprints")) != Some(Overprint::Discard)) +} + +/// The flattener options; the two Preserve switches show what the export does and are set by the +/// format (no alpha) and by EPS Options' Overprints. +fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let current = custom_options(d); + let mut o = current.clone().unwrap_or_default(); + let kept = o.preserve_overprints; + o.preserve_alpha = false; + o.preserve_overprints = kept && overprints_kept(d); + if super::flatten::options_editor_fixed_preserve(ui, "eps-flattener", &mut o) { + o.preserve_overprints = kept; + super::flatten::put_options(&mut d.fields, &o); + } + if let Err(e) = ¤t { + ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); + } + ui.add_space(8.0); + super::form::caption(ui, tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + false +} + +/// OK: EPS Options again, exporting with these options (a built-in preset under them, so that +/// deleting a saved preset leaves them whole); bad options keep the dialog open. +fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut o = custom_options(d)?; + o.preserve_alpha = false; + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + if FlattenOptions::preset(&parent.str("flattenerPreset")).is_none() { + let medium = FlattenOptions::preset_label(FlattenOptions::PRESETS[1]).unwrap_or_default(); + parent.fields.insert("flattenerPreset".into(), json!(medium)); + } + parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?); + app.ui.dialog = Some(parent); + Ok(Value::Null) +} + /// Check the options, remember them, and write the file(s). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let params = fileio::eps::resolve(&super::form::params(d), &app.session.prefs.flattener_presets)?; diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 0c5bc7dbee..bb392557af 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -180,6 +180,16 @@ const FIELD: f32 = 56.0; /// panel edit them: the raster/vector balance, both resolutions and the six switches. Returns true /// when one changed. pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool) -> bool { + editor(ui, id, o, enabled, false) +} + +/// [`options_editor`] with Preserve Alpha Transparency and Preserve Overprints and Spot Colors +/// shown but not editable (the file format or another control sets them). +pub(crate) fn options_editor_fixed_preserve(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions) -> bool { + editor(ui, id, o, true, true) +} + +fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fixed_preserve: bool) -> bool { let t = Tokens::get(ui.ctx()); let before = o.clone(); let dim = |ui: &mut egui::Ui, s: &str| { @@ -226,16 +236,16 @@ pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions } }); ui.add_space(4.0); - let switches: [(&str, &mut bool); 6] = [ - (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines), - (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines), - (tl!("Clip Complex Regions"), &mut o.clip_complex_regions), - (tl!("Anti-alias Rasters"), &mut o.anti_alias), - (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha), - (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints), + let switches: [(&str, &mut bool, bool); 6] = [ + (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, false), + (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, false), + (tl!("Clip Complex Regions"), &mut o.clip_complex_regions, false), + (tl!("Anti-alias Rasters"), &mut o.anti_alias, false), + (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, fixed_preserve), + (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, fixed_preserve), ]; - for (label, v) in switches { - if widgets::check(ui, label, *v, enabled) { + for (label, v, fixed) in switches { + if widgets::check(ui, label, *v, enabled && !fixed) { *v = !*v; } } diff --git a/crates/ui-egui/src/dialogs/tests_eps.rs b/crates/ui-egui/src/dialogs/tests_eps.rs index bebe8a1407..f97207e215 100644 --- a/crates/ui-egui/src/dialogs/tests_eps.rs +++ b/crates/ui-egui/src/dialogs/tests_eps.rs @@ -67,6 +67,108 @@ fn eps_options_take_saved_flattener_presets_and_refuse_bad_ones() { assert!(written.borrow()[0].1.starts_with(b"%!PS-Adobe-3.0 EPSF-3.0"), "{:?}", &written.borrow()[0].1[..8]); } +/// Two overlapping squares, the second half transparent, so that an EPS export flattens them. +fn transparent_art(app: &mut VectorcraftApp) { + for (x, color) in [(5, "#ff0000"), (20, "#0000ff")] { + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": color})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 5, "width": 30, "height": 30})).unwrap(); + } + app.run("transparency.set", json!({"opacity": 50})).unwrap(); +} + +/// Custom… over EPS Options, as its button opens it. +fn open_custom(app: &mut VectorcraftApp) { + let parent = app.ui.dialog.clone().expect("EPS Options are open"); + app.ui.dialog = Some(eps_options::over(&parent, &app.session.prefs.flattener_presets)); + frame(app); +} + +#[test] +fn custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "flattenerPreset": "high"})).unwrap(); + frame(&mut app); + let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + open_custom(&mut app); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("balance", 0.0), d.f64("lineArtPpi", 0.0), d.bool("clipComplexRegions")), (100.0, 1200.0, true), "High Resolution's"); + assert!(!d.bool("preserveAlpha"), "EPS has no alpha"); + set(&mut app, "balance", json!(10)); + cancel(&mut app); + assert_eq!(kind(&app), Some("epsOptions")); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "Cancel leaves EPS Options as they were"); +} + +#[test] +fn custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen() { + let (mut app, written) = app(1); + transparent_art(&mut app); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 100})).unwrap(); + let opts = json!({"path": "/out/a.eps", "flattenerPreset": "Mine", "previewFormat": "none", "thumbnails": false}); + app.run("ui.epsOptionsDialog", opts).unwrap(); + frame(&mut app); + open_custom(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("balance", 0.0), 100.0, "the saved preset's"); + set(&mut app, "balance", json!(0)); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some("epsOptions"), "OK goes back to EPS Options"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["flattener"]["balance"].as_f64(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(0.0), Some(false))); + assert_eq!(d.str("flattenerPreset"), "Medium Resolution", "a built-in preset under options that set everything"); + frame(&mut app); + // The custom options don't need the saved preset they started from. + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + confirm(&mut app).unwrap(); + assert!(ps(&written.borrow()[0].1).contains("image"), "balance 0 rasterizes the flattened art"); + // The next EPS Options start from them; a preset asked for without options drops them. + crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["balance"].as_f64(), Some(0.0)); + cancel(&mut app); + app.run("ui.epsOptionsDialog", json!({"path": "/out/b.eps", "flattenerPreset": "medium"})).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + confirm(&mut app).unwrap(); + assert!(!ps(&written.borrow()[1].1).contains("image"), "Medium Resolution keeps the squares vector"); +} + +#[test] +fn a_flattener_preset_set_from_outside_drops_the_custom_options() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "balance", json!(20)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + // `ui.dialog.set {flattenerPreset: "low"}`, as the control channel sets it. + let old = app.ui.dialog.as_ref().unwrap().fields.get("flattenerPreset").cloned(); + set(&mut app, "flattenerPreset", json!("low")); + field_set(&mut app, "flattenerPreset", old.as_ref()).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key("flattener"), "the preset replaces the custom options"); + assert_eq!(d.str("flattenerPreset"), "Low Resolution"); +} + +#[test] +fn bad_custom_flattener_options_keep_the_dialog_open() { + let (mut app, _) = app(1); + app.run("ui.epsOptionsDialog", json!({"path": "/out/a.eps", "overprints": "discard"})).unwrap(); + frame(&mut app); + open_custom(&mut app); + set(&mut app, "gradientPpi", json!(9000)); + frame(&mut app); + let e = confirm(&mut app).unwrap_err(); + assert!(e.contains("resolutions"), "{e}"); + assert_eq!(kind(&app), Some(eps_options::CUSTOM_KIND)); + // Overprints decides whether overprints are kept, so OK keeps the option as it was. + set(&mut app, "gradientPpi", json!(150)); + set(&mut app, "preserveAlpha", json!(true)); + confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields["flattener"]["preserveOverprints"].as_bool(), d.fields["flattener"]["preserveAlpha"].as_bool()), (Some(true), Some(false))); +} + #[test] fn the_eps_options_dialog_needs_a_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 613d5cd1e3..8f6b8c29cd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2467,6 +2467,9 @@ font-technology Variable Променливи Overprint Напечатване върху друго Overprint and Transparency Flattener Сплескване на надпечатването и прозрачността Overprint and Transparency Flattener Options Опции за сплескване на надпечатването и прозрачността + Custom… Потребителски… + Custom Transparency Flattener Options Потребителски опции за сплескване на прозрачността + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS няма алфа прозрачност, а „Надпечати“ определя дали надпечатванията се запазват. Overprint Black… Напечатване на черното върху друго… Overprint Fill Напечатване на запълването върху друго Overprint Preview Преглед на напечатването върху друго diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index fcc034cd0f..cb0b20955b 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2858,6 +2858,9 @@ digits Malayalam Malajalam Open a document to preview its pages Otvorite dokument da pregledate njegove stranice Output › Mode Izlaz › Način Overprint and Transparency Flattener Options Opcije pretiska i spljoštavanja prozirnosti + Custom… Prilagođeno… + Custom Transparency Flattener Options Prilagođene opcije spljoštavanja prozirnosti + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nema alfa prozirnost, a Pretisci određuju da li se pretisci zadržavaju. Place the pages with the placement again Ponovo postavi stranice s postavljanjem Placement: Postavljanje: Preserve CMYK Numbers Očuvaj CMYK brojeve diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index ac55a78ff4..ce25f2f1ab 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3136,6 +3136,9 @@ digits Malayalam Malaiàlam Overprint Sobrimpressió Overprint and Transparency Flattener Aplanador de sobremipressió i transparència Overprint and Transparency Flattener Options Opcions de l’aplanador de sobremipressió i transparència + Custom… Personalitzat… + Custom Transparency Flattener Options Opcions personalitzades de l’aplanador de transparència + EPS has no alpha transparency, and Overprints sets whether overprints are kept. L’EPS no té transparència alfa, i Sobreimpressions determina si es conserven les sobreimpressions. Overprint Black… Sobrimpressió del negre… Overprint Fill Sobrimpressió del farciment Overprint Preview Previsualització de la sobremipressió diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 69dd46dc23..4a54d08ee6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2942,6 +2942,9 @@ digits Malayalam Malajálamské Open a document to preview its pages Otevřete dokument, abyste viděli náhled jeho stránek Output › Mode Výstup › Režim Overprint and Transparency Flattener Options Možnosti přetisku a sloučení průhlednosti + Custom… Vlastní nastavení… + Custom Transparency Flattener Options Vlastní možnosti sloučení průhlednosti + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nemá průhlednost alfa a Přetisky určují, zda se přetisky zachovají. Place the pages with the placement again Znovu rozmístit stránky podle umístění Placement: Umístění: Preserve CMYK Numbers Zachovat hodnoty CMYK diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7bc0ed6c94..02d9e66a5e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5390,6 +5390,9 @@ digits Malayalam Malayalam Open a document to preview its pages Åbn et dokument for at forhåndsvise dets sider Output › Mode Output › Tilstand Overprint and Transparency Flattener Options Indstillinger for overtryk og udfladning af gennemsigtighed + Custom… Brugerdefineret… + Custom Transparency Flattener Options Brugerdefinerede indstillinger for udfladning af gennemsigtighed + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfa-gennemsigtighed, og Overtryk bestemmer, om overtryk bevares. Place the pages with the placement again Placér siderne igen med placeringen Placement: Placering: Preserve CMYK Numbers Bevar CMYK-tal diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4b17261bfb..9ba155f2c0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2509,6 +2509,9 @@ file-filter Templates Vorlagen Overprint Überdrucken Overprint and Transparency Flattener Überdrucken und Transparenzreduzierung Overprint and Transparency Flattener Options Optionen für Überdrucken und Transparenzreduzierung + Custom… Benutzerdefiniert… + Custom Transparency Flattener Options Benutzerdefinierte Optionen für Transparenzreduzierung + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS hat keine Alphatransparenz, und „Überdrucken“ legt fest, ob Überdrucken erhalten bleibt. Overprint Black… Schwarz überdrucken… Overprint Fill Fläche überdrucken Overprint Preview Überdruckenvorschau diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bba8d392ad..e6daf4f6ea 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3445,6 +3445,9 @@ theme Appearance Εμφάνιση Overprint Υπερεκτύπωση Overprint and Transparency Flattener Υπερεκτύπωση και ισοπέδωση διαφάνειας Overprint and Transparency Flattener Options Επιλογές υπερεκτύπωσης και ισοπέδωσης διαφάνειας + Custom… Προσαρμοσμένο… + Custom Transparency Flattener Options Προσαρμοσμένες επιλογές ισοπέδωσης διαφάνειας + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Το EPS δεν έχει διαφάνεια άλφα και οι Υπερεκτυπώσεις ορίζουν αν διατηρούνται οι υπερεκτυπώσεις. Overprint Black… Υπερεκτύπωση μαύρου… Overprint Fill Υπερεκτύπωση γεμίσματος Overprint Preview Προεπισκόπηση υπερεκτύπωσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 57e7f44e87..d7d9eea30b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2554,6 +2554,9 @@ font-technology Variable Variables Overprint Sobreimprimir Overprint and Transparency Flattener Sobreimpresión y acoplador de transparencia Overprint and Transparency Flattener Options Opciones de sobreimpresión y acoplador de transparencia + Custom… Personalizado… + Custom Transparency Flattener Options Opciones personalizadas de acoplador de transparencia + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS no tiene transparencia alfa, y Sobreimpresiones determina si se conservan las sobreimpresiones. Overprint Black… Sobreimprimir negro… Overprint Fill Sobreimprimir relleno Overprint Preview Vista previa de sobreimpresión diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0276e5b6ed..f3d1716173 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2886,6 +2886,9 @@ digits Malayalam Malajalam Open a document to preview its pages Avaa asiakirja, niin voit esikatsella sen sivuja Output › Mode Tuloste › Tila Overprint and Transparency Flattener Options Päällepainatuksen ja läpinäkyvyyden litistyksen asetukset + Custom… Mukautettu… + Custom Transparency Flattener Options Läpinäkyvyyden litistyksen mukautetut asetukset + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS:ssä ei ole alfa-läpinäkyvyyttä, ja Päällepainatukset määrää, säilytetäänkö päällepainatukset. Place the pages with the placement again Sijoita sivut uudelleen sijoittelun mukaan Placement: Sijoittelu: Preserve CMYK Numbers Säilytä CMYK-arvot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 75f4f14c6f..1001c05651 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2542,6 +2542,9 @@ font-technology Variable Variables Overprint Surimpression Overprint and Transparency Flattener Surimpression et aplatissement des transparences Overprint and Transparency Flattener Options Options de surimpression et d’aplatissement des transparences + Custom… Personnalisé… + Custom Transparency Flattener Options Options personnalisées d’aplatissement des transparences + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Le format EPS n’a pas de transparence alpha, et Surimpressions détermine si les surimpressions sont conservées. Overprint Black… Surimpression du noir… Overprint Fill Surimpression du fond Overprint Preview Aperçu de la surimpression diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..2aeecb0f00 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2587,6 +2587,9 @@ Overprint Stroke ઓવરપ્રિન્ટ સ્ટ્રોક Overprint and Transparency Flattener ઓવરપ્રિન્ટ અને પારદર્શિતા ફ્લેટનર Overprint and Transparency Flattener Options ઓવરપ્રિન્ટ અને પારદર્શિતા ફ્લેટનર વિકલ્પો + Custom… કસ્ટમ… + Custom Transparency Flattener Options કસ્ટમ પારદર્શિતા ફ્લેટનર વિકલ્પો + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS માં આલ્ફા પારદર્શિતા નથી, અને ઓવરપ્રિન્ટ્સ નક્કી કરે છે કે ઓવરપ્રિન્ટ્સ જાળવવામાં આવે કે નહીં. Overprint: ઓવરપ્રિન્ટ: Overprints: ઓવરપ્રિન્ટ્સ: Override Character Color અક્ષરનો રંગ ઓવરરાઇડ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 094d49ce52..38f40fce55 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3414,6 +3414,9 @@ antiAlias Sharp शार्प Overprint ओवरप्रिंट Overprint and Transparency Flattener ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर Overprint and Transparency Flattener Options ओवरप्रिंट और ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + Custom… कस्टम… + Custom Transparency Flattener Options कस्टम ट्रांसपेरेंसी फ़्लैटनर ऑप्शन्स + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS में अल्फा पारदर्शिता नहीं होती, और ओवरप्रिंट तय करता है कि ओवरप्रिंट रखे जाएँ या नहीं। Overprint Black ओवरप्रिंट ब्लैक Overprint Black… ओवरप्रिंट ब्लैक… Overprint Fill फ़िल ओवरप्रिंट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d5f42ce788..af7cc37280 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3042,6 +3042,9 @@ file-filter Templates Sablonok Overprint Felülnyomás Overprint and Transparency Flattener Felülnyomás és átlátszóság-lapítás Overprint and Transparency Flattener Options Felülnyomás és átlátszóság-lapítás beállításai + Custom… Egyéni… + Custom Transparency Flattener Options Egyéni átlátszóság-lapítási beállítások + EPS has no alpha transparency, and Overprints sets whether overprints are kept. Az EPS-ben nincs alfa-átlátszóság, és a Felülnyomások beállítás dönti el, hogy megmaradnak-e a felülnyomások. Overprint Black… Fekete felülnyomása… Overprint Fill Kitöltés felülnyomása Overprint Preview Felülnyomás-előnézet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b349f589a5..161f879e2a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2667,6 +2667,9 @@ digits Malayalam Malayalam Open a document to preview its pages Buka dokumen untuk melihat pratinjau halamannya Output › Mode Keluaran › Mode Overprint and Transparency Flattener Options Opsi overprint dan perataan transparansi + Custom… Kustom… + Custom Transparency Flattener Options Opsi perataan transparansi kustom + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS tidak memiliki transparansi alfa, dan Overprint menentukan apakah overprint dipertahankan. Place the pages with the placement again Tempatkan halaman lagi dengan penempatan tersebut Placement: Penempatan: Preserve CMYK Numbers Pertahankan angka CMYK diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8bc9d44147..1947602b6f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2590,6 +2590,9 @@ file-filter Templates Modelli Overprint Sovrastampa Overprint and Transparency Flattener Sovrastampa e appiattimento trasparenza Overprint and Transparency Flattener Options Opzioni sovrastampa e appiattimento trasparenza + Custom… Personalizzato… + Custom Transparency Flattener Options Opzioni di appiattimento trasparenza personalizzate + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS non ha trasparenza alfa, e Sovrastampe stabilisce se le sovrastampe vengono mantenute. Overprint Black… Sovrastampa nero… Overprint Fill Sovrastampa riempimento Overprint Preview Anteprima sovrastampa diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 57c9aee61e..25b4846c2d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2710,6 +2710,9 @@ antiAlias Sharp シャープ Overprint Stroke 線をオーバープリント Overprint and Transparency Flattener オーバープリントと透明の分割・統合 Overprint and Transparency Flattener Options オーバープリントと透明の分割・統合オプション + Custom… カスタム… + Custom Transparency Flattener Options カスタムの透明の分割・統合オプション + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS にはアルファ透明がなく、オーバープリントを保持するかどうかは「オーバープリント」で決まります。 Overprint: オーバープリント: Overprints: オーバープリント: Override Character Color 文字カラーを上書き diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a661bc0cbb..6140346b14 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4723,6 +4723,9 @@ digits Malayalam მალაიალამური Open a document to preview its pages გახსენით დოკუმენტი მისი გვერდების წინასწარ სანახავად Output › Mode გამოტანა › რეჟიმი Overprint and Transparency Flattener Options ზედდაბეჭდვისა და გამჭვირვალობის გაბრტყელების პარამეტრები + Custom… მორგებული… + Custom Transparency Flattener Options გამჭვირვალობის გაბრტყელების მორგებული პარამეტრები + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS-ს არ აქვს ალფა-გამჭვირვალობა, ხოლო ზედდაბეჭდვები განსაზღვრავს, შენარჩუნდება თუ არა ზედდაბეჭდვები. Place the pages with the placement again გვერდების ხელახლა განთავსება განთავსების მიხედვით Placement: განთავსება: Preserve CMYK Numbers CMYK მნიშვნელობების შენარჩუნება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 632c2473f8..7f1738cae9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2700,6 +2700,9 @@ antiAlias Sharp 날카롭게 Overprint Stroke 선 오버프린트 Overprint and Transparency Flattener 오버프린트 및 투명도 병합 Overprint and Transparency Flattener Options 오버프린트 및 투명도 병합 옵션 + Custom… 사용자 지정… + Custom Transparency Flattener Options 사용자 지정 투명도 병합 옵션 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS에는 알파 투명도가 없으며, 오버프린트 설정에 따라 오버프린트 유지 여부가 결정됩니다. Overprint: 오버프린트: Overprints: 오버프린트: Override Character Color 문자 색상 덮어쓰기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 0137b7ac5b..cea935eeef 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3284,6 +3284,9 @@ digits Malayalam Malayalam Open a document to preview its pages Open een document om een voorbeeld van de pagina's te bekijken Output › Mode Uitvoer › Modus Overprint and Transparency Flattener Options Opties voor overprint en transparantiepletter + Custom… Aangepast… + Custom Transparency Flattener Options Aangepaste opties voor transparantieafvlakking + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS heeft geen alfatransparantie, en Overdrukken bepaalt of overdrukken behouden blijven. Place the pages with the placement again Plaats de pagina's opnieuw met de plaatsing Placement: Plaatsing: Preserve CMYK Numbers CMYK-waarden behouden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a2909473c2..362c7083a8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2855,6 +2855,9 @@ digits Malayalam Malajalam Open a document to preview its pages Otwórz dokument, aby podejrzeć jego strony Output › Mode Wyjście › Tryb Overprint and Transparency Flattener Options Opcje nadruku i spłaszczania przezroczystości + Custom… Niestandardowe… + Custom Transparency Flattener Options Niestandardowe opcje spłaszczania przezroczystości + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS nie ma przezroczystości alfa, a Nadruki określają, czy nadruki są zachowywane. Place the pages with the placement again Ponownie rozmieść strony według położenia Placement: Położenie: Preserve CMYK Numbers Zachowaj wartości CMYK diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9c7e0fddd5..96f419b023 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2100,6 +2100,9 @@ antiAlias Sharp Nítido Overprint Stroke Sobreimpressão de Traçado Overprint and Transparency Flattener Sobreimpressão e Achatamento de Transparência Overprint and Transparency Flattener Options Opções de Sobreimpressão e Achatamento de Transparência + Custom… Personalizado… + Custom Transparency Flattener Options Opções Personalizadas de Achatamento de Transparência + EPS has no alpha transparency, and Overprints sets whether overprints are kept. O EPS não tem transparência alfa, e Sobreimpressões define se as sobreimpressões são mantidas. Overprint: Sobreimpressão: Overprints: Sobreimpressões: Override Character Color Substituir Cor do Caractere diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 87424a1938..ccc29149ed 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2579,6 +2579,9 @@ file-filter Templates Шаблоны Overprint Наложение Overprint and Transparency Flattener Наложение и объединение прозрачностей Overprint and Transparency Flattener Options Параметры наложения и объединения прозрачностей + Custom… Пользовательские… + Custom Transparency Flattener Options Пользовательские параметры объединения прозрачностей + EPS has no alpha transparency, and Overprints sets whether overprints are kept. В EPS нет альфа-прозрачности, а параметр «Наложения» определяет, сохраняются ли наложения. Overprint Black… Наложение чёрного… Overprint Fill Наложение заливки Overprint Preview Просмотр наложения diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 62ac5b67a8..4d673c01bd 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2487,6 +2487,9 @@ font-technology Variable Variabla Overprint Övertryck Overprint and Transparency Flattener Övertryck och transparensutplattning Overprint and Transparency Flattener Options Alternativ för övertryck och transparensutplattning + Custom… Anpassad… + Custom Transparency Flattener Options Anpassade alternativ för transparensutplattning + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS har ingen alfatransparens, och Övertryck avgör om övertryck behålls. Overprint Black… Övertryck svart… Overprint Fill Övertryck fyllning Overprint Preview Förhandsgranskning av övertryck diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 9076b8da7c..8b8f2c0872 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2326,6 +2326,9 @@ shape Open Açık Overprint Üst Baskı Overprint and Transparency Flattener Üst Baskı ve Asetat Düzleştirici Overprint and Transparency Flattener Options Üst Baskı ve Asetat Düzleştirici Seçenekleri + Custom… Özel… + Custom Transparency Flattener Options Özel Şeffaflık Düzleştirici Seçenekleri + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS'de alfa şeffaflığı yoktur ve Üst baskılar, üst baskıların korunup korunmayacağını belirler. Overprint Black… Üst Baskı Siyah… Overprint Fill Üst Baskı Dolgusu Overprint Preview Üst Baskı Önizleme diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c701f1bd5d..02d40e923a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2582,6 +2582,9 @@ file-filter Templates Шаблони Overprint Накладення Overprint and Transparency Flattener Накладання та зведення прозорості Overprint and Transparency Flattener Options Параметри накладання та зведення прозорості + Custom… Користувацькі… + Custom Transparency Flattener Options Користувацькі параметри зведення прозорості + EPS has no alpha transparency, and Overprints sets whether overprints are kept. У EPS немає альфа-прозорості, а параметр «Накладення» визначає, чи зберігаються накладення. Overprint Black… Накладення чорного… Overprint Fill Накладання заливки Overprint Preview Перегляд накладання diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7ce09032d1..4271afb609 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2860,6 +2860,9 @@ digits Hindi Hindi Overprint In chồng Overprint and Transparency Flattener In chồng và làm phẳng trong suốt Overprint and Transparency Flattener Options Tùy chọn in chồng và làm phẳng trong suốt + Custom… Tùy chỉnh… + Custom Transparency Flattener Options Tùy chọn làm phẳng trong suốt tùy chỉnh + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS không có trong suốt kênh Alpha, và In chồng quyết định có giữ in chồng hay không. Overprint Black… In chồng đen… Overprint Fill Tô in chồng Overprint Preview Xem trước in chồng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 86f04f416e..1ee9db73d0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2442,6 +2442,9 @@ file-filter Templates 模板 Overprint 叠印 Overprint and Transparency Flattener 叠印和透明度拼合器 Overprint and Transparency Flattener Options 叠印和透明度拼合器选项 + Custom… 自定义… + Custom Transparency Flattener Options 自定义透明度拼合器选项 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 没有 Alpha 透明度,“叠印”决定是否保留叠印。 Overprint Black… 黑色叠印… Overprint Fill 叠印填色 Overprint Preview 叠印预览 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 65e5274812..fb8c665f7a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3713,6 +3713,9 @@ liquify-list-end {0}, {1} {0}和{1} Overprint 疊印 Overprint and Transparency Flattener 疊印與透明度平面化 Overprint and Transparency Flattener Options 疊印與透明度平面化選項 + Custom… 自訂… + Custom Transparency Flattener Options 自訂透明度平面化選項 + EPS has no alpha transparency, and Overprints sets whether overprints are kept. EPS 沒有 Alpha 透明度,「疊印」決定是否保留疊印。 Overprint Black… 疊印黑色… Overprint Fill 疊印填色 Overprint Preview 疊印預視 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ced961e32c..efe874e007 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1659,7 +1659,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.epsOptionsDialog", "EPS Options Dialog", "", - "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last; Custom… sets `flattener`, which a flattenerPreset given without it drops); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", ), ( "file.saveForWeb", diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df83c6eb04..d72d306e84 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -812,13 +812,21 @@ selected slices. Hidden or locked slices (`view.slices.hide`, `view.slices.lock` EPS Options: Export As… with the EPS format (`file.exportAs {format: "eps"}`, then the save dialog), or `ui.epsOptionsDialog {path?, …document.exportEps options}` for agents, opens the `epsOptions` dialog. Its fields are `document.export` params: `previewFormat` (`none`, `tiffBw`, `tiffColor`), `transparentPreview`, `overprints` -(`preserve`, `discard`), `flattenerPreset` (a built-in or saved preset's name), `includeLinkedFiles`, `thumbnails`, +(`preserve`, `discard`), `flattenerPreset` (a built-in or saved preset's name), `flattener` (custom flattener options +over the preset, as `object.flattenTransparency` takes them), `includeLinkedFiles`, `thumbnails`, `cmykPostScript`, `compatibleGradients`, `level` (`2`, `3`), plus `path` and the artboard choice (`useArtboards`, `range`). `ui.dialog.confirm` checks them (a bad value or an unknown preset keeps the dialog open), remembers them for the next EPS Options and writes the file(s), asking for a path when there is none. With Use Artboards and two or more artboards, it writes a central file of the whole document under the chosen name and one `{stem}_{artboard}.eps` per artboard. When no art shows, it writes only the artboard files. +The Custom… button beside the preset opens the `epsFlattenerOptions` dialog over EPS Options, on the options the +export would use. Its fields are the flattener options; `preserveAlpha` is always off, and overprints are kept only +with `overprints: "preserve"`. Its `ui.dialog.confirm` sets every option as `flattener` (the preset then shows +[Custom]) and goes back to EPS Options; `ui.dialog.cancel` goes back with the options unchanged. Choosing a preset, +in the dropdown or with `ui.dialog.set {flattenerPreset}`, drops `flattener`, and so does `ui.epsOptionsDialog` with +a `flattenerPreset` and no `flattener`. + Data Recovery: at launch, copies left behind by a crash open the `recovery` dialog (never copies another running instance keeps, so instances started side by side for screenshots don't get it). Fields: `copies` (`[{file, title, saved}]`, from `file.recovery.list`) and `discard`. `ui.dialog.confirm` restores them all (`file.recovery.restore` diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..d432c154ec 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8492,8 +8492,9 @@ Colorized grayscale and 1-bit images use their process or spot ink; the flattene PostScript has no transparency: it is flattened first with `flattenerPreset` (`high`, `medium` (default), `low` or a saved preset, see `flattener.presets.list`) and `flattener: {…}` options over it (those of -`object.flattenTransparency`); a warning says so. `previewFormat` adds a TIFF preview behind a binary header (`tiffColor` -(default), transparent unless `transparentPreview: false`, or 1-bit `tiffBw`; `none` writes plain PostScript), +`object.flattenTransparency`); a warning says so. EPS Options' Custom… button sets every `flattener` option. +`previewFormat` adds a TIFF preview behind a binary header (`tiffColor` (default), transparent unless +`transparentPreview: false`, or 1-bit `tiffBw`; `none` writes plain PostScript), `thumbnails` a PNG thumbnail in comments, and the native document always rides along in the trailer's comments (with linked images whole when `includeLinkedFiles`), so a later EPS import can reopen the file as it was. Export for Screens doesn't write EPS. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af7974b880..fe2c0fe7b2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -706,6 +706,7 @@ since 2026-10-01. - **Effects in the art's bounds:** Export with Use Artboards off, Fit to Artwork Bounds, and the other exports of the whole art (EPS without artboards, Export for Screens' Full Document, Save for Web (Legacy) with Clip to Artboard off) measure each visible object as the export crops above do. The drop shadows and other effects of groups, layers, type and images are inside the image or the artboard. A Shaper group without effects of its own is measured by the art it shows, and the hidden members of a group with a drop shadow, a glow or another raster effect do not count unless it is a Shaper group or also has a geometry, Pathfinder, Crop Marks or 3D effect or a visible effect on its own fill or stroke. The SVG of an artboard keeps an object whose effects alone reach the artboard. Tests measure a group, type and an image with a drop shadow, export a group and type with Use Artboards off and fit an artboard to them. - **EPS Save with Use Artboards:** Save As › EPS Options show Use Artboards with All or Range, for a separate file per artboard ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)), unchecked by default (the scripting reference's EPS save options list `saveMultipleArtboards` with a default of false, [scripting reference](https://web.archive.org/web/20160803105056/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20JavaScript%20Scripting%20Reference.pdf)). Unchecked, Save writes one file whose bounding box fits all the visible art, as Export does, without the artboards' background colors; when no art shows, the page is the first artboard in its color. An opened EPS saved back this way loses its page margins. Checked with two or more chosen artboards, the file at the path is the central file of the visible art and each artboard is also written to `_.eps` beside it. Checked with one chosen artboard, VectorCraft writes that artboard as the page of the file at the path alone (the behavior Save had since #4293). Evidence: `cmd::fileio::tests_artboard_fill::eps_save_draws_the_color_on_an_artboard_page`, `tests::save::eps_save_without_use_artboards_fits_the_box_to_art_past_the_artboard`, `tests::save::opened_eps_saves_to_its_own_file_around_its_art_or_on_its_page`, `tests::save::eps_save_with_use_artboards_writes_the_central_file_and_one_per_artboard`, `dialogs::save_options::tests::eps_save_as_shows_use_artboards_off_and_writes_the_art_or_the_artboard`. +- **EPS Options custom flattener settings:** the help page describes flattening an EPS's transparency with a preset or with custom options, adjusted through Custom ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)). EPS Options now has Custom… beside the flattener Preset. It opens Custom Transparency Flattener Options on the settings the export would use: the raster/vector balance, both resolutions, the text and stroke outline switches, Clip Complex Regions and Anti-alias Rasters. OK goes back to EPS Options with the preset shown as [Custom], the export flattens with those settings, and the next EPS Options start from them; choosing a preset drops them, and Cancel goes back to EPS Options unchanged. Preserve Alpha Transparency stays off, and overprints are kept only with Overprints set to Preserve. The [Custom] label, the remembering, the Cancel behavior, Anti-alias Rasters and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::tests_eps::custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged`, `custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen`, `bad_custom_flattener_options_keep_the_dialog_open`. - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. From 9b1823c54c099462abfcbb2026a41ac302d64795 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 07:37:40 -0800 Subject: [PATCH 098/138] Pathfinder: Shape Mode buttons warn when a line encloses no area MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unite, Minus Front, Intersect, Exclude and Minus Back close open paths, so a straight line encloses no area and does not change the result. Until now the line was dropped with no message. Reported in #7849. - The reply of object.pathfinder.unite, minusFront, intersect, exclude and minusBack now carries a warning, which the status bar shows, when a selected object is or holds an open path that encloses no area once closed (a line in a group or compound path included). The message names Object › Path › Outline Stroke. The area is measured with the path's fill rule, as Make Compound Shape's check in #7894 does. - When such a path is what leaves the result empty (Intersect, or a line at the back in Minus Front), the error says so. Objects that leave nothing without the line keep the plain error. - Both messages have rows in each complete-message catalog. The params text and docs/mcp.md describe the reply field. --- crates/engine/src/cmd.rs | 3 + crates/engine/src/cmd/pathops.rs | 65 +++++++++++++++--- crates/engine/src/tests/pathops.rs | 100 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.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 | 21 ++++++ crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 5 +- 29 files changed, 233 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e2bc50cdc5..c15c9c7ad2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -886,6 +886,9 @@ pub(crate) use buildcmds::TracePresetChanges; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The Shape Mode commands' warning when a selected open path encloses no area. +pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA; + /// The gaps View › Show Live Paint Gaps shows on a Live Paint group. pub use buildcmds::live_paint_gaps; diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 5b7f22abd9..f6ae1a1a6c 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Unite", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Unite) ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Minus Front", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusFront) ), @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Intersect", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Intersect) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Exclude", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::Exclude) ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Minus Back", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}", + "{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids, warning?: when a selected object is or holds a line or another open path that encloses no area once closed, and so does not change the result (when such a path leaves the result empty, as in Intersect, the error says so)}", has_selection, |s, p| run_pf(s, p, PathfinderOp::MinusBack) ), @@ -286,6 +286,37 @@ impl Style { } /// All subpaths of a path or compound path node, in document coordinates, with its fill rule. +/// The Shape Mode commands' warning, which the status bar shows, when a selected object is or holds +/// a line or another open path that encloses no area once closed, and so does not change the result. +pub const SHAPE_MODE_OPEN_PATH_NO_AREA: &str = + "a line or other open path that encloses no area does not change the result; to include it, apply Object › Path › Outline Stroke to it first"; + +/// `path` has an open subpath that encloses no area once closed (a straight line, or an evenodd +/// contour traced twice), by the area its fill rule gives, so a self-crossing path whose signed +/// area is zero (a bow tie) still counts as enclosing area, as Divide measures it. +fn has_open_subpath_without_area(path: &PathData, rule: FillRule) -> bool { + path.subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // A point or a straight two-anchor line needs no area measurement. + if sp.anchors.len() < 2 || (sp.anchors.len() == 2 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)) { + return true; + } + let mut closed = sp.clone(); + closed.closed = true; + // The signed-area test alone only holds for nonzero: evenodd can fill nothing where the + // signed area is not zero (a contour traced twice). + !(rule == FillRule::NonZero && po::encloses_area(sp)) && po::area(&PathData::single(closed), rule) <= 0.0 + }) +} + +/// The area `path` fills with its open subpaths closed, as the Shape Modes fill it. +fn closed_area(path: &PathData, rule: FillRule) -> f64 { + let mut closed = path.clone(); + for sp in &mut closed.subpaths { + sp.closed = true; + } + po::area(&closed, rule) +} + pub(crate) fn node_path(n: &Node) -> Option<(PathData, FillRule)> { match &n.kind { NodeKind::Path { path, rule, .. } => Some((path.clone(), *rule)), @@ -593,8 +624,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack); let label = pf_label(op); let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?; - let ids = s.edit(label, |d, sel| { + let (ids, no_area) = s.edit(label, |d, sel| { // Build the stack (back → front); names are separate from paint/style identity. + let mut no_area = false; let mut styles: Vec